PackageManagerService.java revision 190440d62fc8c5ab24498178cd2ce6901bec2852
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.res.Resources;
181import android.database.ContentObserver;
182import android.graphics.Bitmap;
183import android.hardware.display.DisplayManager;
184import android.net.Uri;
185import android.os.Binder;
186import android.os.Build;
187import android.os.Bundle;
188import android.os.Debug;
189import android.os.Environment;
190import android.os.Environment.UserEnvironment;
191import android.os.FileUtils;
192import android.os.Handler;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Parcel;
197import android.os.ParcelFileDescriptor;
198import android.os.PatternMatcher;
199import android.os.Process;
200import android.os.RemoteCallbackList;
201import android.os.RemoteException;
202import android.os.ResultReceiver;
203import android.os.SELinux;
204import android.os.ServiceManager;
205import android.os.ShellCallback;
206import android.os.SystemClock;
207import android.os.SystemProperties;
208import android.os.Trace;
209import android.os.UserHandle;
210import android.os.UserManager;
211import android.os.UserManagerInternal;
212import android.os.storage.IStorageManager;
213import android.os.storage.StorageEventListener;
214import android.os.storage.StorageManager;
215import android.os.storage.StorageManagerInternal;
216import android.os.storage.VolumeInfo;
217import android.os.storage.VolumeRecord;
218import android.provider.Settings.Global;
219import android.provider.Settings.Secure;
220import android.security.KeyStore;
221import android.security.SystemKeyStore;
222import android.service.pm.PackageServiceDumpProto;
223import android.system.ErrnoException;
224import android.system.Os;
225import android.text.TextUtils;
226import android.text.format.DateUtils;
227import android.util.ArrayMap;
228import android.util.ArraySet;
229import android.util.Base64;
230import android.util.TimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
453    /** Should not be with the scan flags */
454    static final int FLAGS_REMOVE_CHATTY = 1<<31;
455
456    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
457    /** Extension of the compressed packages */
458    private final static String COMPRESSED_EXTENSION = ".gz";
459    /** Suffix of stub packages on the system partition */
460    private final static String STUB_SUFFIX = "-Stub";
461
462    private static final int[] EMPTY_INT_ARRAY = new int[0];
463
464    private static final int TYPE_UNKNOWN = 0;
465    private static final int TYPE_ACTIVITY = 1;
466    private static final int TYPE_RECEIVER = 2;
467    private static final int TYPE_SERVICE = 3;
468    private static final int TYPE_PROVIDER = 4;
469    @IntDef(prefix = { "TYPE_" }, value = {
470            TYPE_UNKNOWN,
471            TYPE_ACTIVITY,
472            TYPE_RECEIVER,
473            TYPE_SERVICE,
474            TYPE_PROVIDER,
475    })
476    @Retention(RetentionPolicy.SOURCE)
477    public @interface ComponentType {}
478
479    /**
480     * Timeout (in milliseconds) after which the watchdog should declare that
481     * our handler thread is wedged.  The usual default for such things is one
482     * minute but we sometimes do very lengthy I/O operations on this thread,
483     * such as installing multi-gigabyte applications, so ours needs to be longer.
484     */
485    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
486
487    /**
488     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
489     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
490     * settings entry if available, otherwise we use the hardcoded default.  If it's been
491     * more than this long since the last fstrim, we force one during the boot sequence.
492     *
493     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
494     * one gets run at the next available charging+idle time.  This final mandatory
495     * no-fstrim check kicks in only of the other scheduling criteria is never met.
496     */
497    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
498
499    /**
500     * Whether verification is enabled by default.
501     */
502    private static final boolean DEFAULT_VERIFY_ENABLE = true;
503
504    /**
505     * The default maximum time to wait for the verification agent to return in
506     * milliseconds.
507     */
508    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
509
510    /**
511     * The default response for package verification timeout.
512     *
513     * This can be either PackageManager.VERIFICATION_ALLOW or
514     * PackageManager.VERIFICATION_REJECT.
515     */
516    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
517
518    static final String PLATFORM_PACKAGE_NAME = "android";
519
520    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
521
522    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
523            DEFAULT_CONTAINER_PACKAGE,
524            "com.android.defcontainer.DefaultContainerService");
525
526    private static final String KILL_APP_REASON_GIDS_CHANGED =
527            "permission grant or revoke changed gids";
528
529    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
530            "permissions revoked";
531
532    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
533
534    private static final String PACKAGE_SCHEME = "package";
535
536    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
537
538    /** Permission grant: not grant the permission. */
539    private static final int GRANT_DENIED = 1;
540
541    /** Permission grant: grant the permission as an install permission. */
542    private static final int GRANT_INSTALL = 2;
543
544    /** Permission grant: grant the permission as a runtime one. */
545    private static final int GRANT_RUNTIME = 3;
546
547    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
548    private static final int GRANT_UPGRADE = 4;
549
550    /** Canonical intent used to identify what counts as a "web browser" app */
551    private static final Intent sBrowserIntent;
552    static {
553        sBrowserIntent = new Intent();
554        sBrowserIntent.setAction(Intent.ACTION_VIEW);
555        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
556        sBrowserIntent.setData(Uri.parse("http:"));
557    }
558
559    /**
560     * The set of all protected actions [i.e. those actions for which a high priority
561     * intent filter is disallowed].
562     */
563    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
564    static {
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
566        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
568        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
569    }
570
571    // Compilation reasons.
572    public static final int REASON_FIRST_BOOT = 0;
573    public static final int REASON_BOOT = 1;
574    public static final int REASON_INSTALL = 2;
575    public static final int REASON_BACKGROUND_DEXOPT = 3;
576    public static final int REASON_AB_OTA = 4;
577    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
578
579    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
580
581    /** All dangerous permission names in the same order as the events in MetricsEvent */
582    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
583            Manifest.permission.READ_CALENDAR,
584            Manifest.permission.WRITE_CALENDAR,
585            Manifest.permission.CAMERA,
586            Manifest.permission.READ_CONTACTS,
587            Manifest.permission.WRITE_CONTACTS,
588            Manifest.permission.GET_ACCOUNTS,
589            Manifest.permission.ACCESS_FINE_LOCATION,
590            Manifest.permission.ACCESS_COARSE_LOCATION,
591            Manifest.permission.RECORD_AUDIO,
592            Manifest.permission.READ_PHONE_STATE,
593            Manifest.permission.CALL_PHONE,
594            Manifest.permission.READ_CALL_LOG,
595            Manifest.permission.WRITE_CALL_LOG,
596            Manifest.permission.ADD_VOICEMAIL,
597            Manifest.permission.USE_SIP,
598            Manifest.permission.PROCESS_OUTGOING_CALLS,
599            Manifest.permission.READ_CELL_BROADCASTS,
600            Manifest.permission.BODY_SENSORS,
601            Manifest.permission.SEND_SMS,
602            Manifest.permission.RECEIVE_SMS,
603            Manifest.permission.READ_SMS,
604            Manifest.permission.RECEIVE_WAP_PUSH,
605            Manifest.permission.RECEIVE_MMS,
606            Manifest.permission.READ_EXTERNAL_STORAGE,
607            Manifest.permission.WRITE_EXTERNAL_STORAGE,
608            Manifest.permission.READ_PHONE_NUMBERS,
609            Manifest.permission.ANSWER_PHONE_CALLS);
610
611
612    /**
613     * Version number for the package parser cache. Increment this whenever the format or
614     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
615     */
616    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
617
618    /**
619     * Whether the package parser cache is enabled.
620     */
621    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
622
623    final ServiceThread mHandlerThread;
624
625    final PackageHandler mHandler;
626
627    private final ProcessLoggingHandler mProcessLoggingHandler;
628
629    /**
630     * Messages for {@link #mHandler} that need to wait for system ready before
631     * being dispatched.
632     */
633    private ArrayList<Message> mPostSystemReadyMessages;
634
635    final int mSdkVersion = Build.VERSION.SDK_INT;
636
637    final Context mContext;
638    final boolean mFactoryTest;
639    final boolean mOnlyCore;
640    final DisplayMetrics mMetrics;
641    final int mDefParseFlags;
642    final String[] mSeparateProcesses;
643    final boolean mIsUpgrade;
644    final boolean mIsPreNUpgrade;
645    final boolean mIsPreNMR1Upgrade;
646
647    // Have we told the Activity Manager to whitelist the default container service by uid yet?
648    @GuardedBy("mPackages")
649    boolean mDefaultContainerWhitelisted = false;
650
651    @GuardedBy("mPackages")
652    private boolean mDexOptDialogShown;
653
654    /** The location for ASEC container files on internal storage. */
655    final String mAsecInternalPath;
656
657    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
658    // LOCK HELD.  Can be called with mInstallLock held.
659    @GuardedBy("mInstallLock")
660    final Installer mInstaller;
661
662    /** Directory where installed third-party apps stored */
663    final File mAppInstallDir;
664
665    /**
666     * Directory to which applications installed internally have their
667     * 32 bit native libraries copied.
668     */
669    private File mAppLib32InstallDir;
670
671    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
672    // apps.
673    final File mDrmAppPrivateInstallDir;
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    // System configuration read by SystemConfig.
752    final int[] mGlobalGids;
753    final SparseArray<ArraySet<String>> mSystemPermissions;
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    // If mac_permissions.xml was found for seinfo labeling.
758    boolean mFoundPolicyFile;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            List<PackageParser.Package> overlayPackages = null;
785            for (PackageParser.Package p : allPackages) {
786                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
787                    if (overlayPackages == null) {
788                        overlayPackages = new ArrayList<PackageParser.Package>();
789                    }
790                    overlayPackages.add(p);
791                }
792            }
793            if (overlayPackages != null) {
794                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
795                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
796                        return p1.mOverlayPriority - p2.mOverlayPriority;
797                    }
798                };
799                Collections.sort(overlayPackages, cmp);
800            }
801            return overlayPackages;
802        }
803
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    };
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mIsStaticOverlay) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
900                String declaringPackageName, int declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Mapping from permission names to info about them.
937    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
938            new ArrayMap<String, PackageParser.PermissionGroup>();
939
940    // Packages whose data we have transfered into another package, thus
941    // should no longer exist.
942    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
943
944    // Broadcast actions that are only available to the system.
945    @GuardedBy("mProtectedBroadcasts")
946    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
947
948    /** List of packages waiting for verification. */
949    final SparseArray<PackageVerificationState> mPendingVerification
950            = new SparseArray<PackageVerificationState>();
951
952    /** Set of packages associated with each app op permission. */
953    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
954
955    final PackageInstallerService mInstallerService;
956
957    private final PackageDexOptimizer mPackageDexOptimizer;
958    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
959    // is used by other apps).
960    private final DexManager mDexManager;
961
962    private AtomicInteger mNextMoveId = new AtomicInteger();
963    private final MoveCallbacks mMoveCallbacks;
964
965    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
966
967    // Cache of users who need badging.
968    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
969
970    /** Token for keys in mPendingVerification. */
971    private int mPendingVerificationToken = 0;
972
973    volatile boolean mSystemReady;
974    volatile boolean mSafeMode;
975    volatile boolean mHasSystemUidErrors;
976    private volatile boolean mEphemeralAppsDisabled;
977
978    ApplicationInfo mAndroidApplication;
979    final ActivityInfo mResolveActivity = new ActivityInfo();
980    final ResolveInfo mResolveInfo = new ResolveInfo();
981    ComponentName mResolveComponentName;
982    PackageParser.Package mPlatformPackage;
983    ComponentName mCustomResolverComponentName;
984
985    boolean mResolverReplaced = false;
986
987    private final @Nullable ComponentName mIntentFilterVerifierComponent;
988    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
989
990    private int mIntentFilterVerificationToken = 0;
991
992    /** The service connection to the ephemeral resolver */
993    final EphemeralResolverConnection mInstantAppResolverConnection;
994    /** Component used to show resolver settings for Instant Apps */
995    final ComponentName mInstantAppResolverSettingsComponent;
996
997    /** Activity used to install instant applications */
998    ActivityInfo mInstantAppInstallerActivity;
999    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1000
1001    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1002            = new SparseArray<IntentFilterVerificationState>();
1003
1004    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1005
1006    // List of packages names to keep cached, even if they are uninstalled for all users
1007    private List<String> mKeepUninstalledPackages;
1008
1009    private UserManagerInternal mUserManagerInternal;
1010
1011    private DeviceIdleController.LocalService mDeviceIdleController;
1012
1013    private File mCacheDir;
1014
1015    private ArraySet<String> mPrivappPermissionsViolations;
1016
1017    private Future<?> mPrepareAppDataFuture;
1018
1019    private static class IFVerificationParams {
1020        PackageParser.Package pkg;
1021        boolean replacing;
1022        int userId;
1023        int verifierUid;
1024
1025        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1026                int _userId, int _verifierUid) {
1027            pkg = _pkg;
1028            replacing = _replacing;
1029            userId = _userId;
1030            replacing = _replacing;
1031            verifierUid = _verifierUid;
1032        }
1033    }
1034
1035    private interface IntentFilterVerifier<T extends IntentFilter> {
1036        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1037                                               T filter, String packageName);
1038        void startVerifications(int userId);
1039        void receiveVerificationResponse(int verificationId);
1040    }
1041
1042    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1043        private Context mContext;
1044        private ComponentName mIntentFilterVerifierComponent;
1045        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1046
1047        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1048            mContext = context;
1049            mIntentFilterVerifierComponent = verifierComponent;
1050        }
1051
1052        private String getDefaultScheme() {
1053            return IntentFilter.SCHEME_HTTPS;
1054        }
1055
1056        @Override
1057        public void startVerifications(int userId) {
1058            // Launch verifications requests
1059            int count = mCurrentIntentFilterVerifications.size();
1060            for (int n=0; n<count; n++) {
1061                int verificationId = mCurrentIntentFilterVerifications.get(n);
1062                final IntentFilterVerificationState ivs =
1063                        mIntentFilterVerificationStates.get(verificationId);
1064
1065                String packageName = ivs.getPackageName();
1066
1067                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1068                final int filterCount = filters.size();
1069                ArraySet<String> domainsSet = new ArraySet<>();
1070                for (int m=0; m<filterCount; m++) {
1071                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1072                    domainsSet.addAll(filter.getHostsList());
1073                }
1074                synchronized (mPackages) {
1075                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1076                            packageName, domainsSet) != null) {
1077                        scheduleWriteSettingsLocked();
1078                    }
1079                }
1080                sendVerificationRequest(verificationId, ivs);
1081            }
1082            mCurrentIntentFilterVerifications.clear();
1083        }
1084
1085        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1086            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1089                    verificationId);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1092                    getDefaultScheme());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1095                    ivs.getHostsString());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1098                    ivs.getPackageName());
1099            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1100            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1101
1102            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1103            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1104                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1105                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1106
1107            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Sending IntentFilter verification broadcast");
1110        }
1111
1112        public void receiveVerificationResponse(int verificationId) {
1113            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1114
1115            final boolean verified = ivs.isVerified();
1116
1117            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1118            final int count = filters.size();
1119            if (DEBUG_DOMAIN_VERIFICATION) {
1120                Slog.i(TAG, "Received verification response " + verificationId
1121                        + " for " + count + " filters, verified=" + verified);
1122            }
1123            for (int n=0; n<count; n++) {
1124                PackageParser.ActivityIntentInfo filter = filters.get(n);
1125                filter.setVerified(verified);
1126
1127                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1128                        + " verified with result:" + verified + " and hosts:"
1129                        + ivs.getHostsString());
1130            }
1131
1132            mIntentFilterVerificationStates.remove(verificationId);
1133
1134            final String packageName = ivs.getPackageName();
1135            IntentFilterVerificationInfo ivi = null;
1136
1137            synchronized (mPackages) {
1138                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1139            }
1140            if (ivi == null) {
1141                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1142                        + verificationId + " packageName:" + packageName);
1143                return;
1144            }
1145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1146                    "Updating IntentFilterVerificationInfo for package " + packageName
1147                            +" verificationId:" + verificationId);
1148
1149            synchronized (mPackages) {
1150                if (verified) {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1152                } else {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1154                }
1155                scheduleWriteSettingsLocked();
1156
1157                final int userId = ivs.getUserId();
1158                if (userId != UserHandle.USER_ALL) {
1159                    final int userStatus =
1160                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1161
1162                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1163                    boolean needUpdate = false;
1164
1165                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1166                    // already been set by the User thru the Disambiguation dialog
1167                    switch (userStatus) {
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                            } else {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1173                            }
1174                            needUpdate = true;
1175                            break;
1176
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                                needUpdate = true;
1181                            }
1182                            break;
1183
1184                        default:
1185                            // Nothing to do
1186                    }
1187
1188                    if (needUpdate) {
1189                        mSettings.updateIntentFilterVerificationStatusLPw(
1190                                packageName, updatedStatus, userId);
1191                        scheduleWritePackageRestrictionsLocked(userId);
1192                    }
1193                }
1194            }
1195        }
1196
1197        @Override
1198        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1199                    ActivityIntentInfo filter, String packageName) {
1200            if (!hasValidDomains(filter)) {
1201                return false;
1202            }
1203            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1204            if (ivs == null) {
1205                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1206                        packageName);
1207            }
1208            if (DEBUG_DOMAIN_VERIFICATION) {
1209                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1210            }
1211            ivs.addFilter(filter);
1212            return true;
1213        }
1214
1215        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1216                int userId, int verificationId, String packageName) {
1217            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1218                    verifierUid, userId, packageName);
1219            ivs.setPendingState();
1220            synchronized (mPackages) {
1221                mIntentFilterVerificationStates.append(verificationId, ivs);
1222                mCurrentIntentFilterVerifications.add(verificationId);
1223            }
1224            return ivs;
1225        }
1226    }
1227
1228    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1229        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1230                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1231                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1232    }
1233
1234    // Set of pending broadcasts for aggregating enable/disable of components.
1235    static class PendingPackageBroadcasts {
1236        // for each user id, a map of <package name -> components within that package>
1237        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1238
1239        public PendingPackageBroadcasts() {
1240            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1241        }
1242
1243        public ArrayList<String> get(int userId, String packageName) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            return packages.get(packageName);
1246        }
1247
1248        public void put(int userId, String packageName, ArrayList<String> components) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            packages.put(packageName, components);
1251        }
1252
1253        public void remove(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1255            if (packages != null) {
1256                packages.remove(packageName);
1257            }
1258        }
1259
1260        public void remove(int userId) {
1261            mUidMap.remove(userId);
1262        }
1263
1264        public int userIdCount() {
1265            return mUidMap.size();
1266        }
1267
1268        public int userIdAt(int n) {
1269            return mUidMap.keyAt(n);
1270        }
1271
1272        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1273            return mUidMap.get(userId);
1274        }
1275
1276        public int size() {
1277            // total number of pending broadcast entries across all userIds
1278            int num = 0;
1279            for (int i = 0; i< mUidMap.size(); i++) {
1280                num += mUidMap.valueAt(i).size();
1281            }
1282            return num;
1283        }
1284
1285        public void clear() {
1286            mUidMap.clear();
1287        }
1288
1289        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1290            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1291            if (map == null) {
1292                map = new ArrayMap<String, ArrayList<String>>();
1293                mUidMap.put(userId, map);
1294            }
1295            return map;
1296        }
1297    }
1298    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1299
1300    // Service Connection to remote media container service to copy
1301    // package uri's from external media onto secure containers
1302    // or internal storage.
1303    private IMediaContainerService mContainerService = null;
1304
1305    static final int SEND_PENDING_BROADCAST = 1;
1306    static final int MCS_BOUND = 3;
1307    static final int END_COPY = 4;
1308    static final int INIT_COPY = 5;
1309    static final int MCS_UNBIND = 6;
1310    static final int START_CLEANING_PACKAGE = 7;
1311    static final int FIND_INSTALL_LOC = 8;
1312    static final int POST_INSTALL = 9;
1313    static final int MCS_RECONNECT = 10;
1314    static final int MCS_GIVE_UP = 11;
1315    static final int UPDATED_MEDIA_STATUS = 12;
1316    static final int WRITE_SETTINGS = 13;
1317    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1318    static final int PACKAGE_VERIFIED = 15;
1319    static final int CHECK_PENDING_VERIFICATION = 16;
1320    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1321    static final int INTENT_FILTER_VERIFIED = 18;
1322    static final int WRITE_PACKAGE_LIST = 19;
1323    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1324
1325    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1326
1327    // Delay time in millisecs
1328    static final int BROADCAST_DELAY = 10 * 1000;
1329
1330    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1331            2 * 60 * 60 * 1000L; /* two hours */
1332
1333    static UserManagerService sUserManager;
1334
1335    // Stores a list of users whose package restrictions file needs to be updated
1336    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1337
1338    final private DefaultContainerConnection mDefContainerConn =
1339            new DefaultContainerConnection();
1340    class DefaultContainerConnection implements ServiceConnection {
1341        public void onServiceConnected(ComponentName name, IBinder service) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1343            final IMediaContainerService imcs = IMediaContainerService.Stub
1344                    .asInterface(Binder.allowBlocking(service));
1345            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1346        }
1347
1348        public void onServiceDisconnected(ComponentName name) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1350        }
1351    }
1352
1353    // Recordkeeping of restore-after-install operations that are currently in flight
1354    // between the Package Manager and the Backup Manager
1355    static class PostInstallData {
1356        public InstallArgs args;
1357        public PackageInstalledInfo res;
1358
1359        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1360            args = _a;
1361            res = _r;
1362        }
1363    }
1364
1365    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1366    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1367
1368    // XML tags for backup/restore of various bits of state
1369    private static final String TAG_PREFERRED_BACKUP = "pa";
1370    private static final String TAG_DEFAULT_APPS = "da";
1371    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1372
1373    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1374    private static final String TAG_ALL_GRANTS = "rt-grants";
1375    private static final String TAG_GRANT = "grant";
1376    private static final String ATTR_PACKAGE_NAME = "pkg";
1377
1378    private static final String TAG_PERMISSION = "perm";
1379    private static final String ATTR_PERMISSION_NAME = "name";
1380    private static final String ATTR_IS_GRANTED = "g";
1381    private static final String ATTR_USER_SET = "set";
1382    private static final String ATTR_USER_FIXED = "fixed";
1383    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1384
1385    // System/policy permission grants are not backed up
1386    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_POLICY_FIXED
1388            | FLAG_PERMISSION_SYSTEM_FIXED
1389            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1390
1391    // And we back up these user-adjusted states
1392    private static final int USER_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_USER_SET
1394            | FLAG_PERMISSION_USER_FIXED
1395            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1396
1397    final @Nullable String mRequiredVerifierPackage;
1398    final @NonNull String mRequiredInstallerPackage;
1399    final @NonNull String mRequiredUninstallerPackage;
1400    final @Nullable String mSetupWizardPackage;
1401    final @Nullable String mStorageManagerPackage;
1402    final @NonNull String mServicesSystemSharedLibraryPackageName;
1403    final @NonNull String mSharedSystemSharedLibraryPackageName;
1404
1405    final boolean mPermissionReviewRequired;
1406
1407    private final PackageUsage mPackageUsage = new PackageUsage();
1408    private final CompilerStats mCompilerStats = new CompilerStats();
1409
1410    class PackageHandler extends Handler {
1411        private boolean mBound = false;
1412        final ArrayList<HandlerParams> mPendingInstalls =
1413            new ArrayList<HandlerParams>();
1414
1415        private boolean connectToService() {
1416            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1417                    " DefaultContainerService");
1418            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1421                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1422                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423                mBound = true;
1424                return true;
1425            }
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            return false;
1428        }
1429
1430        private void disconnectService() {
1431            mContainerService = null;
1432            mBound = false;
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434            mContext.unbindService(mDefContainerConn);
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436        }
1437
1438        PackageHandler(Looper looper) {
1439            super(looper);
1440        }
1441
1442        public void handleMessage(Message msg) {
1443            try {
1444                doHandleMessage(msg);
1445            } finally {
1446                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447            }
1448        }
1449
1450        void doHandleMessage(Message msg) {
1451            switch (msg.what) {
1452                case INIT_COPY: {
1453                    HandlerParams params = (HandlerParams) msg.obj;
1454                    int idx = mPendingInstalls.size();
1455                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1456                    // If a bind was already initiated we dont really
1457                    // need to do anything. The pending install
1458                    // will be processed later on.
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        // If this is the only one pending we might
1463                        // have to bind to the service again.
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            params.serviceError();
1467                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1468                                    System.identityHashCode(mHandler));
1469                            if (params.traceMethod != null) {
1470                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1471                                        params.traceCookie);
1472                            }
1473                            return;
1474                        } else {
1475                            // Once we bind to the service, the first
1476                            // pending request will be processed.
1477                            mPendingInstalls.add(idx, params);
1478                        }
1479                    } else {
1480                        mPendingInstalls.add(idx, params);
1481                        // Already bound to the service. Just make
1482                        // sure we trigger off processing the first request.
1483                        if (idx == 0) {
1484                            mHandler.sendEmptyMessage(MCS_BOUND);
1485                        }
1486                    }
1487                    break;
1488                }
1489                case MCS_BOUND: {
1490                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1491                    if (msg.obj != null) {
1492                        mContainerService = (IMediaContainerService) msg.obj;
1493                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1494                                System.identityHashCode(mHandler));
1495                    }
1496                    if (mContainerService == null) {
1497                        if (!mBound) {
1498                            // Something seriously wrong since we are not bound and we are not
1499                            // waiting for connection. Bail out.
1500                            Slog.e(TAG, "Cannot bind to media container service");
1501                            for (HandlerParams params : mPendingInstalls) {
1502                                // Indicate service bind error
1503                                params.serviceError();
1504                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                        System.identityHashCode(params));
1506                                if (params.traceMethod != null) {
1507                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1508                                            params.traceMethod, params.traceCookie);
1509                                }
1510                                return;
1511                            }
1512                            mPendingInstalls.clear();
1513                        } else {
1514                            Slog.w(TAG, "Waiting to connect to media container service");
1515                        }
1516                    } else if (mPendingInstalls.size() > 0) {
1517                        HandlerParams params = mPendingInstalls.get(0);
1518                        if (params != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                    System.identityHashCode(params));
1521                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1522                            if (params.startCopy()) {
1523                                // We are done...  look for more work or to
1524                                // go idle.
1525                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                        "Checking for more work or unbind...");
1527                                // Delete pending install
1528                                if (mPendingInstalls.size() > 0) {
1529                                    mPendingInstalls.remove(0);
1530                                }
1531                                if (mPendingInstalls.size() == 0) {
1532                                    if (mBound) {
1533                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                                "Posting delayed MCS_UNBIND");
1535                                        removeMessages(MCS_UNBIND);
1536                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1537                                        // Unbind after a little delay, to avoid
1538                                        // continual thrashing.
1539                                        sendMessageDelayed(ubmsg, 10000);
1540                                    }
1541                                } else {
1542                                    // There are more pending requests in queue.
1543                                    // Just post MCS_BOUND message to trigger processing
1544                                    // of next pending install.
1545                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                            "Posting MCS_BOUND for next work");
1547                                    mHandler.sendEmptyMessage(MCS_BOUND);
1548                                }
1549                            }
1550                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1551                        }
1552                    } else {
1553                        // Should never happen ideally.
1554                        Slog.w(TAG, "Empty queue");
1555                    }
1556                    break;
1557                }
1558                case MCS_RECONNECT: {
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1560                    if (mPendingInstalls.size() > 0) {
1561                        if (mBound) {
1562                            disconnectService();
1563                        }
1564                        if (!connectToService()) {
1565                            Slog.e(TAG, "Failed to bind to media container service");
1566                            for (HandlerParams params : mPendingInstalls) {
1567                                // Indicate service bind error
1568                                params.serviceError();
1569                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1570                                        System.identityHashCode(params));
1571                            }
1572                            mPendingInstalls.clear();
1573                        }
1574                    }
1575                    break;
1576                }
1577                case MCS_UNBIND: {
1578                    // If there is no actual work left, then time to unbind.
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1580
1581                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1582                        if (mBound) {
1583                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1584
1585                            disconnectService();
1586                        }
1587                    } else if (mPendingInstalls.size() > 0) {
1588                        // There are more pending requests in queue.
1589                        // Just post MCS_BOUND message to trigger processing
1590                        // of next pending install.
1591                        mHandler.sendEmptyMessage(MCS_BOUND);
1592                    }
1593
1594                    break;
1595                }
1596                case MCS_GIVE_UP: {
1597                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1598                    HandlerParams params = mPendingInstalls.remove(0);
1599                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1600                            System.identityHashCode(params));
1601                    break;
1602                }
1603                case SEND_PENDING_BROADCAST: {
1604                    String packages[];
1605                    ArrayList<String> components[];
1606                    int size = 0;
1607                    int uids[];
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        if (mPendingBroadcasts == null) {
1611                            return;
1612                        }
1613                        size = mPendingBroadcasts.size();
1614                        if (size <= 0) {
1615                            // Nothing to be done. Just return
1616                            return;
1617                        }
1618                        packages = new String[size];
1619                        components = new ArrayList[size];
1620                        uids = new int[size];
1621                        int i = 0;  // filling out the above arrays
1622
1623                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1624                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1625                            Iterator<Map.Entry<String, ArrayList<String>>> it
1626                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1627                                            .entrySet().iterator();
1628                            while (it.hasNext() && i < size) {
1629                                Map.Entry<String, ArrayList<String>> ent = it.next();
1630                                packages[i] = ent.getKey();
1631                                components[i] = ent.getValue();
1632                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1633                                uids[i] = (ps != null)
1634                                        ? UserHandle.getUid(packageUserId, ps.appId)
1635                                        : -1;
1636                                i++;
1637                            }
1638                        }
1639                        size = i;
1640                        mPendingBroadcasts.clear();
1641                    }
1642                    // Send broadcasts
1643                    for (int i = 0; i < size; i++) {
1644                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    break;
1648                }
1649                case START_CLEANING_PACKAGE: {
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1651                    final String packageName = (String)msg.obj;
1652                    final int userId = msg.arg1;
1653                    final boolean andCode = msg.arg2 != 0;
1654                    synchronized (mPackages) {
1655                        if (userId == UserHandle.USER_ALL) {
1656                            int[] users = sUserManager.getUserIds();
1657                            for (int user : users) {
1658                                mSettings.addPackageToCleanLPw(
1659                                        new PackageCleanItem(user, packageName, andCode));
1660                            }
1661                        } else {
1662                            mSettings.addPackageToCleanLPw(
1663                                    new PackageCleanItem(userId, packageName, andCode));
1664                        }
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                    startCleaningPackages();
1668                } break;
1669                case POST_INSTALL: {
1670                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1671
1672                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1673                    final boolean didRestore = (msg.arg2 != 0);
1674                    mRunningInstalls.delete(msg.arg1);
1675
1676                    if (data != null) {
1677                        InstallArgs args = data.args;
1678                        PackageInstalledInfo parentRes = data.res;
1679
1680                        final boolean grantPermissions = (args.installFlags
1681                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1682                        final boolean killApp = (args.installFlags
1683                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1684                        final boolean virtualPreload = ((args.installFlags
1685                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1686                        final String[] grantedPermissions = args.installGrantPermissions;
1687
1688                        // Handle the parent package
1689                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1690                                virtualPreload, grantedPermissions, didRestore,
1691                                args.installerPackageName, args.observer);
1692
1693                        // Handle the child packages
1694                        final int childCount = (parentRes.addedChildPackages != null)
1695                                ? parentRes.addedChildPackages.size() : 0;
1696                        for (int i = 0; i < childCount; i++) {
1697                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1698                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1699                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1700                                    args.installerPackageName, args.observer);
1701                        }
1702
1703                        // Log tracing if needed
1704                        if (args.traceMethod != null) {
1705                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1706                                    args.traceCookie);
1707                        }
1708                    } else {
1709                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1710                    }
1711
1712                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1713                } break;
1714                case UPDATED_MEDIA_STATUS: {
1715                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1716                    boolean reportStatus = msg.arg1 == 1;
1717                    boolean doGc = msg.arg2 == 1;
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1719                    if (doGc) {
1720                        // Force a gc to clear up stale containers.
1721                        Runtime.getRuntime().gc();
1722                    }
1723                    if (msg.obj != null) {
1724                        @SuppressWarnings("unchecked")
1725                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1726                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1727                        // Unload containers
1728                        unloadAllContainers(args);
1729                    }
1730                    if (reportStatus) {
1731                        try {
1732                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1733                                    "Invoking StorageManagerService call back");
1734                            PackageHelper.getStorageManager().finishMediaUpdate();
1735                        } catch (RemoteException e) {
1736                            Log.e(TAG, "StorageManagerService not running?");
1737                        }
1738                    }
1739                } break;
1740                case WRITE_SETTINGS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_SETTINGS);
1744                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1745                        mSettings.writeLPr();
1746                        mDirtyUsers.clear();
1747                    }
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1749                } break;
1750                case WRITE_PACKAGE_RESTRICTIONS: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1754                        for (int userId : mDirtyUsers) {
1755                            mSettings.writePackageRestrictionsLPr(userId);
1756                        }
1757                        mDirtyUsers.clear();
1758                    }
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1760                } break;
1761                case WRITE_PACKAGE_LIST: {
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1763                    synchronized (mPackages) {
1764                        removeMessages(WRITE_PACKAGE_LIST);
1765                        mSettings.writePackageListLPr(msg.arg1);
1766                    }
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1768                } break;
1769                case CHECK_PENDING_VERIFICATION: {
1770                    final int verificationId = msg.arg1;
1771                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1772
1773                    if ((state != null) && !state.timeoutExtended()) {
1774                        final InstallArgs args = state.getInstallArgs();
1775                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1776
1777                        Slog.i(TAG, "Verification timed out for " + originUri);
1778                        mPendingVerification.remove(verificationId);
1779
1780                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1781
1782                        final UserHandle user = args.getUser();
1783                        if (getDefaultVerificationResponse(user)
1784                                == PackageManager.VERIFICATION_ALLOW) {
1785                            Slog.i(TAG, "Continuing with installation of " + originUri);
1786                            state.setVerifierResponse(Binder.getCallingUid(),
1787                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1788                            broadcastPackageVerified(verificationId, originUri,
1789                                    PackageManager.VERIFICATION_ALLOW, user);
1790                            try {
1791                                ret = args.copyApk(mContainerService, true);
1792                            } catch (RemoteException e) {
1793                                Slog.e(TAG, "Could not contact the ContainerService");
1794                            }
1795                        } else {
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    PackageManager.VERIFICATION_REJECT, user);
1798                        }
1799
1800                        Trace.asyncTraceEnd(
1801                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1802
1803                        processPendingInstall(args, ret);
1804                        mHandler.sendEmptyMessage(MCS_UNBIND);
1805                    }
1806                    break;
1807                }
1808                case PACKAGE_VERIFIED: {
1809                    final int verificationId = msg.arg1;
1810
1811                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1812                    if (state == null) {
1813                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1814                        break;
1815                    }
1816
1817                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1818
1819                    state.setVerifierResponse(response.callerUid, response.code);
1820
1821                    if (state.isVerificationComplete()) {
1822                        mPendingVerification.remove(verificationId);
1823
1824                        final InstallArgs args = state.getInstallArgs();
1825                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1826
1827                        int ret;
1828                        if (state.isInstallAllowed()) {
1829                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1830                            broadcastPackageVerified(verificationId, originUri,
1831                                    response.code, state.getInstallArgs().getUser());
1832                            try {
1833                                ret = args.copyApk(mContainerService, true);
1834                            } catch (RemoteException e) {
1835                                Slog.e(TAG, "Could not contact the ContainerService");
1836                            }
1837                        } else {
1838                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1839                        }
1840
1841                        Trace.asyncTraceEnd(
1842                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1843
1844                        processPendingInstall(args, ret);
1845                        mHandler.sendEmptyMessage(MCS_UNBIND);
1846                    }
1847
1848                    break;
1849                }
1850                case START_INTENT_FILTER_VERIFICATIONS: {
1851                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1852                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1853                            params.replacing, params.pkg);
1854                    break;
1855                }
1856                case INTENT_FILTER_VERIFIED: {
1857                    final int verificationId = msg.arg1;
1858
1859                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1860                            verificationId);
1861                    if (state == null) {
1862                        Slog.w(TAG, "Invalid IntentFilter verification token "
1863                                + verificationId + " received");
1864                        break;
1865                    }
1866
1867                    final int userId = state.getUserId();
1868
1869                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                            "Processing IntentFilter verification with token:"
1871                            + verificationId + " and userId:" + userId);
1872
1873                    final IntentFilterVerificationResponse response =
1874                            (IntentFilterVerificationResponse) msg.obj;
1875
1876                    state.setVerifierResponse(response.callerUid, response.code);
1877
1878                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1879                            "IntentFilter verification with token:" + verificationId
1880                            + " and userId:" + userId
1881                            + " is settings verifier response with response code:"
1882                            + response.code);
1883
1884                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1885                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1886                                + response.getFailedDomainsString());
1887                    }
1888
1889                    if (state.isVerificationComplete()) {
1890                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1891                    } else {
1892                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1893                                "IntentFilter verification with token:" + verificationId
1894                                + " was not said to be complete");
1895                    }
1896
1897                    break;
1898                }
1899                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1900                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1901                            mInstantAppResolverConnection,
1902                            (InstantAppRequest) msg.obj,
1903                            mInstantAppInstallerActivity,
1904                            mHandler);
1905                }
1906            }
1907        }
1908    }
1909
1910    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1911            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1912            boolean launchedForRestore, String installerPackage,
1913            IPackageInstallObserver2 installObserver) {
1914        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1915            // Send the removed broadcasts
1916            if (res.removedInfo != null) {
1917                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1918            }
1919
1920            // Now that we successfully installed the package, grant runtime
1921            // permissions if requested before broadcasting the install. Also
1922            // for legacy apps in permission review mode we clear the permission
1923            // review flag which is used to emulate runtime permissions for
1924            // legacy apps.
1925            if (grantPermissions) {
1926                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1927            }
1928
1929            final boolean update = res.removedInfo != null
1930                    && res.removedInfo.removedPackage != null;
1931            final String origInstallerPackageName = res.removedInfo != null
1932                    ? res.removedInfo.installerPackageName : null;
1933
1934            // If this is the first time we have child packages for a disabled privileged
1935            // app that had no children, we grant requested runtime permissions to the new
1936            // children if the parent on the system image had them already granted.
1937            if (res.pkg.parentPackage != null) {
1938                synchronized (mPackages) {
1939                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1940                }
1941            }
1942
1943            synchronized (mPackages) {
1944                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1945            }
1946
1947            final String packageName = res.pkg.applicationInfo.packageName;
1948
1949            // Determine the set of users who are adding this package for
1950            // the first time vs. those who are seeing an update.
1951            int[] firstUsers = EMPTY_INT_ARRAY;
1952            int[] updateUsers = EMPTY_INT_ARRAY;
1953            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1954            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1955            for (int newUser : res.newUsers) {
1956                if (ps.getInstantApp(newUser)) {
1957                    continue;
1958                }
1959                if (allNewUsers) {
1960                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1961                    continue;
1962                }
1963                boolean isNew = true;
1964                for (int origUser : res.origUsers) {
1965                    if (origUser == newUser) {
1966                        isNew = false;
1967                        break;
1968                    }
1969                }
1970                if (isNew) {
1971                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1972                } else {
1973                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1974                }
1975            }
1976
1977            // Send installed broadcasts if the package is not a static shared lib.
1978            if (res.pkg.staticSharedLibName == null) {
1979                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1980
1981                // Send added for users that see the package for the first time
1982                // sendPackageAddedForNewUsers also deals with system apps
1983                int appId = UserHandle.getAppId(res.uid);
1984                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1985                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1986                        virtualPreload /*startReceiver*/, appId, firstUsers);
1987
1988                // Send added for users that don't see the package for the first time
1989                Bundle extras = new Bundle(1);
1990                extras.putInt(Intent.EXTRA_UID, res.uid);
1991                if (update) {
1992                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1993                }
1994                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                        extras, 0 /*flags*/,
1996                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1997                if (origInstallerPackageName != null) {
1998                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1999                            extras, 0 /*flags*/,
2000                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2001                }
2002
2003                // Send replaced for users that don't see the package for the first time
2004                if (update) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2006                            packageName, extras, 0 /*flags*/,
2007                            null /*targetPackage*/, null /*finishedReceiver*/,
2008                            updateUsers);
2009                    if (origInstallerPackageName != null) {
2010                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2011                                extras, 0 /*flags*/,
2012                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2013                    }
2014                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2015                            null /*package*/, null /*extras*/, 0 /*flags*/,
2016                            packageName /*targetPackage*/,
2017                            null /*finishedReceiver*/, updateUsers);
2018                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2019                    // First-install and we did a restore, so we're responsible for the
2020                    // first-launch broadcast.
2021                    if (DEBUG_BACKUP) {
2022                        Slog.i(TAG, "Post-restore of " + packageName
2023                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2024                    }
2025                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2026                }
2027
2028                // Send broadcast package appeared if forward locked/external for all users
2029                // treat asec-hosted packages like removable media on upgrade
2030                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2031                    if (DEBUG_INSTALL) {
2032                        Slog.i(TAG, "upgrading pkg " + res.pkg
2033                                + " is ASEC-hosted -> AVAILABLE");
2034                    }
2035                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2036                    ArrayList<String> pkgList = new ArrayList<>(1);
2037                    pkgList.add(packageName);
2038                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2039                }
2040            }
2041
2042            // Work that needs to happen on first install within each user
2043            if (firstUsers != null && firstUsers.length > 0) {
2044                synchronized (mPackages) {
2045                    for (int userId : firstUsers) {
2046                        // If this app is a browser and it's newly-installed for some
2047                        // users, clear any default-browser state in those users. The
2048                        // app's nature doesn't depend on the user, so we can just check
2049                        // its browser nature in any user and generalize.
2050                        if (packageIsBrowser(packageName, userId)) {
2051                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2052                        }
2053
2054                        // We may also need to apply pending (restored) runtime
2055                        // permission grants within these users.
2056                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2057                    }
2058                }
2059            }
2060
2061            // Log current value of "unknown sources" setting
2062            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2063                    getUnknownSourcesSettings());
2064
2065            // Remove the replaced package's older resources safely now
2066            // We delete after a gc for applications  on sdcard.
2067            if (res.removedInfo != null && res.removedInfo.args != null) {
2068                Runtime.getRuntime().gc();
2069                synchronized (mInstallLock) {
2070                    res.removedInfo.args.doPostDeleteLI(true);
2071                }
2072            } else {
2073                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2074                // and not block here.
2075                VMRuntime.getRuntime().requestConcurrentGC();
2076            }
2077
2078            // Notify DexManager that the package was installed for new users.
2079            // The updated users should already be indexed and the package code paths
2080            // should not change.
2081            // Don't notify the manager for ephemeral apps as they are not expected to
2082            // survive long enough to benefit of background optimizations.
2083            for (int userId : firstUsers) {
2084                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2085                // There's a race currently where some install events may interleave with an uninstall.
2086                // This can lead to package info being null (b/36642664).
2087                if (info != null) {
2088                    mDexManager.notifyPackageInstalled(info, userId);
2089                }
2090            }
2091        }
2092
2093        // If someone is watching installs - notify them
2094        if (installObserver != null) {
2095            try {
2096                Bundle extras = extrasForInstallResult(res);
2097                installObserver.onPackageInstalled(res.name, res.returnCode,
2098                        res.returnMsg, extras);
2099            } catch (RemoteException e) {
2100                Slog.i(TAG, "Observer no longer exists.");
2101            }
2102        }
2103    }
2104
2105    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2106            PackageParser.Package pkg) {
2107        if (pkg.parentPackage == null) {
2108            return;
2109        }
2110        if (pkg.requestedPermissions == null) {
2111            return;
2112        }
2113        final PackageSetting disabledSysParentPs = mSettings
2114                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2115        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2116                || !disabledSysParentPs.isPrivileged()
2117                || (disabledSysParentPs.childPackageNames != null
2118                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2119            return;
2120        }
2121        final int[] allUserIds = sUserManager.getUserIds();
2122        final int permCount = pkg.requestedPermissions.size();
2123        for (int i = 0; i < permCount; i++) {
2124            String permission = pkg.requestedPermissions.get(i);
2125            BasePermission bp = mSettings.mPermissions.get(permission);
2126            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2127                continue;
2128            }
2129            for (int userId : allUserIds) {
2130                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2131                        permission, userId)) {
2132                    grantRuntimePermission(pkg.packageName, permission, userId);
2133                }
2134            }
2135        }
2136    }
2137
2138    private StorageEventListener mStorageListener = new StorageEventListener() {
2139        @Override
2140        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2141            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2142                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2143                    final String volumeUuid = vol.getFsUuid();
2144
2145                    // Clean up any users or apps that were removed or recreated
2146                    // while this volume was missing
2147                    sUserManager.reconcileUsers(volumeUuid);
2148                    reconcileApps(volumeUuid);
2149
2150                    // Clean up any install sessions that expired or were
2151                    // cancelled while this volume was missing
2152                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2153
2154                    loadPrivatePackages(vol);
2155
2156                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2157                    unloadPrivatePackages(vol);
2158                }
2159            }
2160
2161            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2162                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2163                    updateExternalMediaStatus(true, false);
2164                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2165                    updateExternalMediaStatus(false, false);
2166                }
2167            }
2168        }
2169
2170        @Override
2171        public void onVolumeForgotten(String fsUuid) {
2172            if (TextUtils.isEmpty(fsUuid)) {
2173                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2174                return;
2175            }
2176
2177            // Remove any apps installed on the forgotten volume
2178            synchronized (mPackages) {
2179                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2180                for (PackageSetting ps : packages) {
2181                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2182                    deletePackageVersioned(new VersionedPackage(ps.name,
2183                            PackageManager.VERSION_CODE_HIGHEST),
2184                            new LegacyPackageDeleteObserver(null).getBinder(),
2185                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2186                    // Try very hard to release any references to this package
2187                    // so we don't risk the system server being killed due to
2188                    // open FDs
2189                    AttributeCache.instance().removePackage(ps.name);
2190                }
2191
2192                mSettings.onVolumeForgotten(fsUuid);
2193                mSettings.writeLPr();
2194            }
2195        }
2196    };
2197
2198    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2199            String[] grantedPermissions) {
2200        for (int userId : userIds) {
2201            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2202        }
2203    }
2204
2205    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2206            String[] grantedPermissions) {
2207        PackageSetting ps = (PackageSetting) pkg.mExtras;
2208        if (ps == null) {
2209            return;
2210        }
2211
2212        PermissionsState permissionsState = ps.getPermissionsState();
2213
2214        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2215                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2216
2217        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2218                >= Build.VERSION_CODES.M;
2219
2220        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2221
2222        for (String permission : pkg.requestedPermissions) {
2223            final BasePermission bp;
2224            synchronized (mPackages) {
2225                bp = mSettings.mPermissions.get(permission);
2226            }
2227            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2228                    && (!instantApp || bp.isInstant())
2229                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2230                    && (grantedPermissions == null
2231                           || ArrayUtils.contains(grantedPermissions, permission))) {
2232                final int flags = permissionsState.getPermissionFlags(permission, userId);
2233                if (supportsRuntimePermissions) {
2234                    // Installer cannot change immutable permissions.
2235                    if ((flags & immutableFlags) == 0) {
2236                        grantRuntimePermission(pkg.packageName, permission, userId);
2237                    }
2238                } else if (mPermissionReviewRequired) {
2239                    // In permission review mode we clear the review flag when we
2240                    // are asked to install the app with all permissions granted.
2241                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2242                        updatePermissionFlags(permission, pkg.packageName,
2243                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2244                    }
2245                }
2246            }
2247        }
2248    }
2249
2250    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2251        Bundle extras = null;
2252        switch (res.returnCode) {
2253            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2254                extras = new Bundle();
2255                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2256                        res.origPermission);
2257                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2258                        res.origPackage);
2259                break;
2260            }
2261            case PackageManager.INSTALL_SUCCEEDED: {
2262                extras = new Bundle();
2263                extras.putBoolean(Intent.EXTRA_REPLACING,
2264                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2265                break;
2266            }
2267        }
2268        return extras;
2269    }
2270
2271    void scheduleWriteSettingsLocked() {
2272        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2273            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2274        }
2275    }
2276
2277    void scheduleWritePackageListLocked(int userId) {
2278        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2279            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2280            msg.arg1 = userId;
2281            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2282        }
2283    }
2284
2285    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2286        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2287        scheduleWritePackageRestrictionsLocked(userId);
2288    }
2289
2290    void scheduleWritePackageRestrictionsLocked(int userId) {
2291        final int[] userIds = (userId == UserHandle.USER_ALL)
2292                ? sUserManager.getUserIds() : new int[]{userId};
2293        for (int nextUserId : userIds) {
2294            if (!sUserManager.exists(nextUserId)) return;
2295            mDirtyUsers.add(nextUserId);
2296            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2297                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2298            }
2299        }
2300    }
2301
2302    public static PackageManagerService main(Context context, Installer installer,
2303            boolean factoryTest, boolean onlyCore) {
2304        // Self-check for initial settings.
2305        PackageManagerServiceCompilerMapping.checkProperties();
2306
2307        PackageManagerService m = new PackageManagerService(context, installer,
2308                factoryTest, onlyCore);
2309        m.enableSystemUserPackages();
2310        ServiceManager.addService("package", m);
2311        final PackageManagerNative pmn = m.new PackageManagerNative();
2312        ServiceManager.addService("package_native", pmn);
2313        return m;
2314    }
2315
2316    private void enableSystemUserPackages() {
2317        if (!UserManager.isSplitSystemUser()) {
2318            return;
2319        }
2320        // For system user, enable apps based on the following conditions:
2321        // - app is whitelisted or belong to one of these groups:
2322        //   -- system app which has no launcher icons
2323        //   -- system app which has INTERACT_ACROSS_USERS permission
2324        //   -- system IME app
2325        // - app is not in the blacklist
2326        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2327        Set<String> enableApps = new ArraySet<>();
2328        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2329                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2330                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2331        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2332        enableApps.addAll(wlApps);
2333        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2334                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2335        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2336        enableApps.removeAll(blApps);
2337        Log.i(TAG, "Applications installed for system user: " + enableApps);
2338        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2339                UserHandle.SYSTEM);
2340        final int allAppsSize = allAps.size();
2341        synchronized (mPackages) {
2342            for (int i = 0; i < allAppsSize; i++) {
2343                String pName = allAps.get(i);
2344                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2345                // Should not happen, but we shouldn't be failing if it does
2346                if (pkgSetting == null) {
2347                    continue;
2348                }
2349                boolean install = enableApps.contains(pName);
2350                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2351                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2352                            + " for system user");
2353                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2354                }
2355            }
2356            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2357        }
2358    }
2359
2360    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2361        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2362                Context.DISPLAY_SERVICE);
2363        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2364    }
2365
2366    /**
2367     * Requests that files preopted on a secondary system partition be copied to the data partition
2368     * if possible.  Note that the actual copying of the files is accomplished by init for security
2369     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2370     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2371     */
2372    private static void requestCopyPreoptedFiles() {
2373        final int WAIT_TIME_MS = 100;
2374        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2375        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2376            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2377            // We will wait for up to 100 seconds.
2378            final long timeStart = SystemClock.uptimeMillis();
2379            final long timeEnd = timeStart + 100 * 1000;
2380            long timeNow = timeStart;
2381            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2382                try {
2383                    Thread.sleep(WAIT_TIME_MS);
2384                } catch (InterruptedException e) {
2385                    // Do nothing
2386                }
2387                timeNow = SystemClock.uptimeMillis();
2388                if (timeNow > timeEnd) {
2389                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2390                    Slog.wtf(TAG, "cppreopt did not finish!");
2391                    break;
2392                }
2393            }
2394
2395            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2396        }
2397    }
2398
2399    public PackageManagerService(Context context, Installer installer,
2400            boolean factoryTest, boolean onlyCore) {
2401        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2403        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2404                SystemClock.uptimeMillis());
2405
2406        if (mSdkVersion <= 0) {
2407            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2408        }
2409
2410        mContext = context;
2411
2412        mPermissionReviewRequired = context.getResources().getBoolean(
2413                R.bool.config_permissionReviewRequired);
2414
2415        mFactoryTest = factoryTest;
2416        mOnlyCore = onlyCore;
2417        mMetrics = new DisplayMetrics();
2418        mSettings = new Settings(mPackages);
2419        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431
2432        String separateProcesses = SystemProperties.get("debug.separate_processes");
2433        if (separateProcesses != null && separateProcesses.length() > 0) {
2434            if ("*".equals(separateProcesses)) {
2435                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2436                mSeparateProcesses = null;
2437                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2438            } else {
2439                mDefParseFlags = 0;
2440                mSeparateProcesses = separateProcesses.split(",");
2441                Slog.w(TAG, "Running with debug.separate_processes: "
2442                        + separateProcesses);
2443            }
2444        } else {
2445            mDefParseFlags = 0;
2446            mSeparateProcesses = null;
2447        }
2448
2449        mInstaller = installer;
2450        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2451                "*dexopt*");
2452        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2453        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2454
2455        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2456                FgThread.get().getLooper());
2457
2458        getDefaultDisplayMetrics(context, mMetrics);
2459
2460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2461        SystemConfig systemConfig = SystemConfig.getInstance();
2462        mGlobalGids = systemConfig.getGlobalGids();
2463        mSystemPermissions = systemConfig.getSystemPermissions();
2464        mAvailableFeatures = systemConfig.getAvailableFeatures();
2465        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2466
2467        mProtectedPackages = new ProtectedPackages(mContext);
2468
2469        synchronized (mInstallLock) {
2470        // writer
2471        synchronized (mPackages) {
2472            mHandlerThread = new ServiceThread(TAG,
2473                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2474            mHandlerThread.start();
2475            mHandler = new PackageHandler(mHandlerThread.getLooper());
2476            mProcessLoggingHandler = new ProcessLoggingHandler();
2477            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2478
2479            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2480            mInstantAppRegistry = new InstantAppRegistry(this);
2481
2482            File dataDir = Environment.getDataDirectory();
2483            mAppInstallDir = new File(dataDir, "app");
2484            mAppLib32InstallDir = new File(dataDir, "app-lib");
2485            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2486            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2487            sUserManager = new UserManagerService(context, this,
2488                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2489
2490            // Propagate permission configuration in to package manager.
2491            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2492                    = systemConfig.getPermissions();
2493            for (int i=0; i<permConfig.size(); i++) {
2494                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2495                BasePermission bp = mSettings.mPermissions.get(perm.name);
2496                if (bp == null) {
2497                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2498                    mSettings.mPermissions.put(perm.name, bp);
2499                }
2500                if (perm.gids != null) {
2501                    bp.setGids(perm.gids, perm.perUser);
2502                }
2503            }
2504
2505            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2506            final int builtInLibCount = libConfig.size();
2507            for (int i = 0; i < builtInLibCount; i++) {
2508                String name = libConfig.keyAt(i);
2509                String path = libConfig.valueAt(i);
2510                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2511                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2512            }
2513
2514            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2515
2516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2517            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520            // Clean up orphaned packages for which the code path doesn't exist
2521            // and they are an update to a system app - caused by bug/32321269
2522            final int packageSettingCount = mSettings.mPackages.size();
2523            for (int i = packageSettingCount - 1; i >= 0; i--) {
2524                PackageSetting ps = mSettings.mPackages.valueAt(i);
2525                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2526                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2527                    mSettings.mPackages.removeAt(i);
2528                    mSettings.enableSystemPackageLPw(ps.name);
2529                }
2530            }
2531
2532            if (mFirstBoot) {
2533                requestCopyPreoptedFiles();
2534            }
2535
2536            String customResolverActivity = Resources.getSystem().getString(
2537                    R.string.config_customResolverActivity);
2538            if (TextUtils.isEmpty(customResolverActivity)) {
2539                customResolverActivity = null;
2540            } else {
2541                mCustomResolverComponentName = ComponentName.unflattenFromString(
2542                        customResolverActivity);
2543            }
2544
2545            long startTime = SystemClock.uptimeMillis();
2546
2547            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2548                    startTime);
2549
2550            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2551            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2552
2553            if (bootClassPath == null) {
2554                Slog.w(TAG, "No BOOTCLASSPATH found!");
2555            }
2556
2557            if (systemServerClassPath == null) {
2558                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2559            }
2560
2561            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2562
2563            final VersionInfo ver = mSettings.getInternalVersion();
2564            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2565            if (mIsUpgrade) {
2566                logCriticalInfo(Log.INFO,
2567                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2568            }
2569
2570            // when upgrading from pre-M, promote system app permissions from install to runtime
2571            mPromoteSystemApps =
2572                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2573
2574            // When upgrading from pre-N, we need to handle package extraction like first boot,
2575            // as there is no profiling data available.
2576            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2577
2578            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2579
2580            // save off the names of pre-existing system packages prior to scanning; we don't
2581            // want to automatically grant runtime permissions for new system apps
2582            if (mPromoteSystemApps) {
2583                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2584                while (pkgSettingIter.hasNext()) {
2585                    PackageSetting ps = pkgSettingIter.next();
2586                    if (isSystemApp(ps)) {
2587                        mExistingSystemPackages.add(ps.name);
2588                    }
2589                }
2590            }
2591
2592            mCacheDir = preparePackageParserCache(mIsUpgrade);
2593
2594            // Set flag to monitor and not change apk file paths when
2595            // scanning install directories.
2596            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2597
2598            if (mIsUpgrade || mFirstBoot) {
2599                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2600            }
2601
2602            // Collect vendor overlay packages. (Do this before scanning any apps.)
2603            // For security and version matching reason, only consider
2604            // overlay packages if they reside in the right directory.
2605            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir, mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_IS_PRIVILEGED,
2617                    scanFlags | SCAN_NO_DEX, 0);
2618
2619            // Collected privileged system packages.
2620            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2621            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2625
2626            // Collect ordinary system packages.
2627            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2628            scanDirTracedLI(systemAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2631
2632            // Collect all vendor packages.
2633            File vendorAppDir = new File("/vendor/app");
2634            try {
2635                vendorAppDir = vendorAppDir.getCanonicalFile();
2636            } catch (IOException e) {
2637                // failed to look up canonical path, continue with original one
2638            }
2639            scanDirTracedLI(vendorAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Collect all OEM packages.
2644            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2645            scanDirTracedLI(oemAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Prune any system packages that no longer exist.
2650            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2651            // Stub packages must either be replaced with full versions in the /data
2652            // partition or be disabled.
2653            final List<String> stubSystemApps = new ArrayList<>();
2654            if (!mOnlyCore) {
2655                // do this first before mucking with mPackages for the "expecting better" case
2656                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2657                while (pkgIterator.hasNext()) {
2658                    final PackageParser.Package pkg = pkgIterator.next();
2659                    if (pkg.isStub) {
2660                        stubSystemApps.add(pkg.packageName);
2661                    }
2662                }
2663
2664                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2665                while (psit.hasNext()) {
2666                    PackageSetting ps = psit.next();
2667
2668                    /*
2669                     * If this is not a system app, it can't be a
2670                     * disable system app.
2671                     */
2672                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2673                        continue;
2674                    }
2675
2676                    /*
2677                     * If the package is scanned, it's not erased.
2678                     */
2679                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2680                    if (scannedPkg != null) {
2681                        /*
2682                         * If the system app is both scanned and in the
2683                         * disabled packages list, then it must have been
2684                         * added via OTA. Remove it from the currently
2685                         * scanned package so the previously user-installed
2686                         * application can be scanned.
2687                         */
2688                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2689                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2690                                    + ps.name + "; removing system app.  Last known codePath="
2691                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2692                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2693                                    + scannedPkg.mVersionCode);
2694                            removePackageLI(scannedPkg, true);
2695                            mExpectingBetter.put(ps.name, ps.codePath);
2696                        }
2697
2698                        continue;
2699                    }
2700
2701                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2702                        psit.remove();
2703                        logCriticalInfo(Log.WARN, "System package " + ps.name
2704                                + " no longer exists; it's data will be wiped");
2705                        // Actual deletion of code and data will be handled by later
2706                        // reconciliation step
2707                    } else {
2708                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2709                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2710                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2711                        }
2712                    }
2713                }
2714            }
2715
2716            //look for any incomplete package installations
2717            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2718            for (int i = 0; i < deletePkgsList.size(); i++) {
2719                // Actual deletion of code and data will be handled by later
2720                // reconciliation step
2721                final String packageName = deletePkgsList.get(i).name;
2722                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2723                synchronized (mPackages) {
2724                    mSettings.removePackageLPw(packageName);
2725                }
2726            }
2727
2728            //delete tmp files
2729            deleteTempPackageFiles();
2730
2731            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2732
2733            // Remove any shared userIDs that have no associated packages
2734            mSettings.pruneSharedUsersLPw();
2735            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2736            final int systemPackagesCount = mPackages.size();
2737            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2738                    + " ms, packageCount: " + systemPackagesCount
2739                    + " , timePerPackage: "
2740                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2741                    + " , cached: " + cachedSystemApps);
2742            if (mIsUpgrade && systemPackagesCount > 0) {
2743                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2744                        ((int) systemScanTime) / systemPackagesCount);
2745            }
2746            if (!mOnlyCore) {
2747                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2748                        SystemClock.uptimeMillis());
2749                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2750
2751                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2752                        | PackageParser.PARSE_FORWARD_LOCK,
2753                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2754
2755                // Remove disable package settings for updated system apps that were
2756                // removed via an OTA. If the update is no longer present, remove the
2757                // app completely. Otherwise, revoke their system privileges.
2758                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2759                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2760                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2761
2762                    final String msg;
2763                    if (deletedPkg == null) {
2764                        // should have found an update, but, we didn't; remove everything
2765                        msg = "Updated system package " + deletedAppName
2766                                + " no longer exists; removing its data";
2767                        // Actual deletion of code and data will be handled by later
2768                        // reconciliation step
2769                    } else {
2770                        // found an update; revoke system privileges
2771                        msg = "Updated system package + " + deletedAppName
2772                                + " no longer exists; revoking system privileges";
2773
2774                        // Don't do anything if a stub is removed from the system image. If
2775                        // we were to remove the uncompressed version from the /data partition,
2776                        // this is where it'd be done.
2777
2778                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2779                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2780                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2781                    }
2782                    logCriticalInfo(Log.WARN, msg);
2783                }
2784
2785                /*
2786                 * Make sure all system apps that we expected to appear on
2787                 * the userdata partition actually showed up. If they never
2788                 * appeared, crawl back and revive the system version.
2789                 */
2790                for (int i = 0; i < mExpectingBetter.size(); i++) {
2791                    final String packageName = mExpectingBetter.keyAt(i);
2792                    if (!mPackages.containsKey(packageName)) {
2793                        final File scanFile = mExpectingBetter.valueAt(i);
2794
2795                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2796                                + " but never showed up; reverting to system");
2797
2798                        int reparseFlags = mDefParseFlags;
2799                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2800                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2801                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2802                                    | PackageParser.PARSE_IS_PRIVILEGED;
2803                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2806                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2807                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2808                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2809                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else {
2813                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2814                            continue;
2815                        }
2816
2817                        mSettings.enableSystemPackageLPw(packageName);
2818
2819                        try {
2820                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2821                        } catch (PackageManagerException e) {
2822                            Slog.e(TAG, "Failed to parse original system package: "
2823                                    + e.getMessage());
2824                        }
2825                    }
2826                }
2827
2828                // Uncompress and install any stubbed system applications.
2829                // This must be done last to ensure all stubs are replaced or disabled.
2830                decompressSystemApplications(stubSystemApps, scanFlags);
2831
2832                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2833                                - cachedSystemApps;
2834
2835                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2836                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2837                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2838                        + " ms, packageCount: " + dataPackagesCount
2839                        + " , timePerPackage: "
2840                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2841                        + " , cached: " + cachedNonSystemApps);
2842                if (mIsUpgrade && dataPackagesCount > 0) {
2843                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2844                            ((int) dataScanTime) / dataPackagesCount);
2845                }
2846            }
2847            mExpectingBetter.clear();
2848
2849            // Resolve the storage manager.
2850            mStorageManagerPackage = getStorageManagerPackageName();
2851
2852            // Resolve protected action filters. Only the setup wizard is allowed to
2853            // have a high priority filter for these actions.
2854            mSetupWizardPackage = getSetupWizardPackageName();
2855            if (mProtectedFilters.size() > 0) {
2856                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2857                    Slog.i(TAG, "No setup wizard;"
2858                        + " All protected intents capped to priority 0");
2859                }
2860                for (ActivityIntentInfo filter : mProtectedFilters) {
2861                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2862                        if (DEBUG_FILTERS) {
2863                            Slog.i(TAG, "Found setup wizard;"
2864                                + " allow priority " + filter.getPriority() + ";"
2865                                + " package: " + filter.activity.info.packageName
2866                                + " activity: " + filter.activity.className
2867                                + " priority: " + filter.getPriority());
2868                        }
2869                        // skip setup wizard; allow it to keep the high priority filter
2870                        continue;
2871                    }
2872                    if (DEBUG_FILTERS) {
2873                        Slog.i(TAG, "Protected action; cap priority to 0;"
2874                                + " package: " + filter.activity.info.packageName
2875                                + " activity: " + filter.activity.className
2876                                + " origPrio: " + filter.getPriority());
2877                    }
2878                    filter.setPriority(0);
2879                }
2880            }
2881            mDeferProtectedFilters = false;
2882            mProtectedFilters.clear();
2883
2884            // Now that we know all of the shared libraries, update all clients to have
2885            // the correct library paths.
2886            updateAllSharedLibrariesLPw(null);
2887
2888            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2889                // NOTE: We ignore potential failures here during a system scan (like
2890                // the rest of the commands above) because there's precious little we
2891                // can do about it. A settings error is reported, though.
2892                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2893            }
2894
2895            // Now that we know all the packages we are keeping,
2896            // read and update their last usage times.
2897            mPackageUsage.read(mPackages);
2898            mCompilerStats.read();
2899
2900            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2901                    SystemClock.uptimeMillis());
2902            Slog.i(TAG, "Time to scan packages: "
2903                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2904                    + " seconds");
2905
2906            // If the platform SDK has changed since the last time we booted,
2907            // we need to re-grant app permission to catch any new ones that
2908            // appear.  This is really a hack, and means that apps can in some
2909            // cases get permissions that the user didn't initially explicitly
2910            // allow...  it would be nice to have some better way to handle
2911            // this situation.
2912            int updateFlags = UPDATE_PERMISSIONS_ALL;
2913            if (ver.sdkVersion != mSdkVersion) {
2914                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2915                        + mSdkVersion + "; regranting permissions for internal storage");
2916                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2917            }
2918            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2919            ver.sdkVersion = mSdkVersion;
2920
2921            // If this is the first boot or an update from pre-M, and it is a normal
2922            // boot, then we need to initialize the default preferred apps across
2923            // all defined users.
2924            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2925                for (UserInfo user : sUserManager.getUsers(true)) {
2926                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2927                    applyFactoryDefaultBrowserLPw(user.id);
2928                    primeDomainVerificationsLPw(user.id);
2929                }
2930            }
2931
2932            // Prepare storage for system user really early during boot,
2933            // since core system apps like SettingsProvider and SystemUI
2934            // can't wait for user to start
2935            final int storageFlags;
2936            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2937                storageFlags = StorageManager.FLAG_STORAGE_DE;
2938            } else {
2939                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2940            }
2941            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2942                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2943                    true /* onlyCoreApps */);
2944            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2945                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2946                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2947                traceLog.traceBegin("AppDataFixup");
2948                try {
2949                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2950                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2951                } catch (InstallerException e) {
2952                    Slog.w(TAG, "Trouble fixing GIDs", e);
2953                }
2954                traceLog.traceEnd();
2955
2956                traceLog.traceBegin("AppDataPrepare");
2957                if (deferPackages == null || deferPackages.isEmpty()) {
2958                    return;
2959                }
2960                int count = 0;
2961                for (String pkgName : deferPackages) {
2962                    PackageParser.Package pkg = null;
2963                    synchronized (mPackages) {
2964                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2965                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2966                            pkg = ps.pkg;
2967                        }
2968                    }
2969                    if (pkg != null) {
2970                        synchronized (mInstallLock) {
2971                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2972                                    true /* maybeMigrateAppData */);
2973                        }
2974                        count++;
2975                    }
2976                }
2977                traceLog.traceEnd();
2978                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2979            }, "prepareAppData");
2980
2981            // If this is first boot after an OTA, and a normal boot, then
2982            // we need to clear code cache directories.
2983            // Note that we do *not* clear the application profiles. These remain valid
2984            // across OTAs and are used to drive profile verification (post OTA) and
2985            // profile compilation (without waiting to collect a fresh set of profiles).
2986            if (mIsUpgrade && !onlyCore) {
2987                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2988                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2989                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2990                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2991                        // No apps are running this early, so no need to freeze
2992                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2993                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2994                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2995                    }
2996                }
2997                ver.fingerprint = Build.FINGERPRINT;
2998            }
2999
3000            checkDefaultBrowser();
3001
3002            // clear only after permissions and other defaults have been updated
3003            mExistingSystemPackages.clear();
3004            mPromoteSystemApps = false;
3005
3006            // All the changes are done during package scanning.
3007            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3008
3009            // can downgrade to reader
3010            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3011            mSettings.writeLPr();
3012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3013            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3014                    SystemClock.uptimeMillis());
3015
3016            if (!mOnlyCore) {
3017                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3018                mRequiredInstallerPackage = getRequiredInstallerLPr();
3019                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3020                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3021                if (mIntentFilterVerifierComponent != null) {
3022                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3023                            mIntentFilterVerifierComponent);
3024                } else {
3025                    mIntentFilterVerifier = null;
3026                }
3027                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3028                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3029                        SharedLibraryInfo.VERSION_UNDEFINED);
3030                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3031                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3032                        SharedLibraryInfo.VERSION_UNDEFINED);
3033            } else {
3034                mRequiredVerifierPackage = null;
3035                mRequiredInstallerPackage = null;
3036                mRequiredUninstallerPackage = null;
3037                mIntentFilterVerifierComponent = null;
3038                mIntentFilterVerifier = null;
3039                mServicesSystemSharedLibraryPackageName = null;
3040                mSharedSystemSharedLibraryPackageName = null;
3041            }
3042
3043            mInstallerService = new PackageInstallerService(context, this);
3044            final Pair<ComponentName, String> instantAppResolverComponent =
3045                    getInstantAppResolverLPr();
3046            if (instantAppResolverComponent != null) {
3047                if (DEBUG_EPHEMERAL) {
3048                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3049                }
3050                mInstantAppResolverConnection = new EphemeralResolverConnection(
3051                        mContext, instantAppResolverComponent.first,
3052                        instantAppResolverComponent.second);
3053                mInstantAppResolverSettingsComponent =
3054                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3055            } else {
3056                mInstantAppResolverConnection = null;
3057                mInstantAppResolverSettingsComponent = null;
3058            }
3059            updateInstantAppInstallerLocked(null);
3060
3061            // Read and update the usage of dex files.
3062            // Do this at the end of PM init so that all the packages have their
3063            // data directory reconciled.
3064            // At this point we know the code paths of the packages, so we can validate
3065            // the disk file and build the internal cache.
3066            // The usage file is expected to be small so loading and verifying it
3067            // should take a fairly small time compare to the other activities (e.g. package
3068            // scanning).
3069            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3070            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3071            for (int userId : currentUserIds) {
3072                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3073            }
3074            mDexManager.load(userPackages);
3075            if (mIsUpgrade) {
3076                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3077                        (int) (SystemClock.uptimeMillis() - startTime));
3078            }
3079        } // synchronized (mPackages)
3080        } // synchronized (mInstallLock)
3081
3082        // Now after opening every single application zip, make sure they
3083        // are all flushed.  Not really needed, but keeps things nice and
3084        // tidy.
3085        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3086        Runtime.getRuntime().gc();
3087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3088
3089        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3090        FallbackCategoryProvider.loadFallbacks();
3091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3092
3093        // The initial scanning above does many calls into installd while
3094        // holding the mPackages lock, but we're mostly interested in yelling
3095        // once we have a booted system.
3096        mInstaller.setWarnIfHeld(mPackages);
3097
3098        // Expose private service for system components to use.
3099        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101    }
3102
3103    /**
3104     * Uncompress and install stub applications.
3105     * <p>In order to save space on the system partition, some applications are shipped in a
3106     * compressed form. In addition the compressed bits for the full application, the
3107     * system image contains a tiny stub comprised of only the Android manifest.
3108     * <p>During the first boot, attempt to uncompress and install the full application. If
3109     * the application can't be installed for any reason, disable the stub and prevent
3110     * uncompressing the full application during future boots.
3111     * <p>In order to forcefully attempt an installation of a full application, go to app
3112     * settings and enable the application.
3113     */
3114    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3115        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3116            final String pkgName = stubSystemApps.get(i);
3117            // skip if the system package is already disabled
3118            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3119                stubSystemApps.remove(i);
3120                continue;
3121            }
3122            // skip if the package isn't installed (?!); this should never happen
3123            final PackageParser.Package pkg = mPackages.get(pkgName);
3124            if (pkg == null) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package has been disabled by the user
3129            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3130            if (ps != null) {
3131                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3132                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3133                    stubSystemApps.remove(i);
3134                    continue;
3135                }
3136            }
3137
3138            if (DEBUG_COMPRESSION) {
3139                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3140            }
3141
3142            // uncompress the binary to its eventual destination on /data
3143            final File scanFile = decompressPackage(pkg);
3144            if (scanFile == null) {
3145                continue;
3146            }
3147
3148            // install the package to replace the stub on /system
3149            try {
3150                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3151                removePackageLI(pkg, true /*chatty*/);
3152                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3153                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3154                        UserHandle.USER_SYSTEM, "android");
3155                stubSystemApps.remove(i);
3156                continue;
3157            } catch (PackageManagerException e) {
3158                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3159            }
3160
3161            // any failed attempt to install the package will be cleaned up later
3162        }
3163
3164        // disable any stub still left; these failed to install the full application
3165        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3166            final String pkgName = stubSystemApps.get(i);
3167            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3168            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3169                    UserHandle.USER_SYSTEM, "android");
3170            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3171        }
3172    }
3173
3174    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3175        if (DEBUG_COMPRESSION) {
3176            Slog.i(TAG, "Decompress file"
3177                    + "; src: " + srcFile.getAbsolutePath()
3178                    + ", dst: " + dstFile.getAbsolutePath());
3179        }
3180        try (
3181                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3182                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3183        ) {
3184            Streams.copy(fileIn, fileOut);
3185            Os.chmod(dstFile.getAbsolutePath(), 0644);
3186            return PackageManager.INSTALL_SUCCEEDED;
3187        } catch (IOException e) {
3188            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3189                    + "; src: " + srcFile.getAbsolutePath()
3190                    + ", dst: " + dstFile.getAbsolutePath());
3191        }
3192        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3193    }
3194
3195    private File[] getCompressedFiles(String codePath) {
3196        final File stubCodePath = new File(codePath);
3197        final String stubName = stubCodePath.getName();
3198
3199        // The layout of a compressed package on a given partition is as follows :
3200        //
3201        // Compressed artifacts:
3202        //
3203        // /partition/ModuleName/foo.gz
3204        // /partation/ModuleName/bar.gz
3205        //
3206        // Stub artifact:
3207        //
3208        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3209        //
3210        // In other words, stub is on the same partition as the compressed artifacts
3211        // and in a directory that's suffixed with "-Stub".
3212        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3213        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3214            return null;
3215        }
3216
3217        final File stubParentDir = stubCodePath.getParentFile();
3218        if (stubParentDir == null) {
3219            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3220            return null;
3221        }
3222
3223        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3224        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3225            @Override
3226            public boolean accept(File dir, String name) {
3227                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3228            }
3229        });
3230
3231        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3232            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3233        }
3234
3235        return files;
3236    }
3237
3238    private boolean compressedFileExists(String codePath) {
3239        final File[] compressedFiles = getCompressedFiles(codePath);
3240        return compressedFiles != null && compressedFiles.length > 0;
3241    }
3242
3243    /**
3244     * Decompresses the given package on the system image onto
3245     * the /data partition.
3246     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3247     */
3248    private File decompressPackage(PackageParser.Package pkg) {
3249        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3250        if (compressedFiles == null || compressedFiles.length == 0) {
3251            if (DEBUG_COMPRESSION) {
3252                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3253            }
3254            return null;
3255        }
3256        final File dstCodePath =
3257                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3258        int ret = PackageManager.INSTALL_SUCCEEDED;
3259        try {
3260            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3261            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3262            for (File srcFile : compressedFiles) {
3263                final String srcFileName = srcFile.getName();
3264                final String dstFileName = srcFileName.substring(
3265                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3266                final File dstFile = new File(dstCodePath, dstFileName);
3267                ret = decompressFile(srcFile, dstFile);
3268                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3269                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3270                            + "; pkg: " + pkg.packageName
3271                            + ", file: " + dstFileName);
3272                    break;
3273                }
3274            }
3275        } catch (ErrnoException e) {
3276            logCriticalInfo(Log.ERROR, "Failed to decompress"
3277                    + "; pkg: " + pkg.packageName
3278                    + ", err: " + e.errno);
3279        }
3280        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3281            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3282            NativeLibraryHelper.Handle handle = null;
3283            try {
3284                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3285                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3286                        null /*abiOverride*/);
3287            } catch (IOException e) {
3288                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3289                        + "; pkg: " + pkg.packageName);
3290                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3291            } finally {
3292                IoUtils.closeQuietly(handle);
3293            }
3294        }
3295        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3296            if (dstCodePath == null || !dstCodePath.exists()) {
3297                return null;
3298            }
3299            removeCodePathLI(dstCodePath);
3300            return null;
3301        }
3302        return dstCodePath;
3303    }
3304
3305    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3306        // we're only interested in updating the installer appliction when 1) it's not
3307        // already set or 2) the modified package is the installer
3308        if (mInstantAppInstallerActivity != null
3309                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3310                        .equals(modifiedPackage)) {
3311            return;
3312        }
3313        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3314    }
3315
3316    private static File preparePackageParserCache(boolean isUpgrade) {
3317        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3318            return null;
3319        }
3320
3321        // Disable package parsing on eng builds to allow for faster incremental development.
3322        if (Build.IS_ENG) {
3323            return null;
3324        }
3325
3326        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3327            Slog.i(TAG, "Disabling package parser cache due to system property.");
3328            return null;
3329        }
3330
3331        // The base directory for the package parser cache lives under /data/system/.
3332        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3333                "package_cache");
3334        if (cacheBaseDir == null) {
3335            return null;
3336        }
3337
3338        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3339        // This also serves to "GC" unused entries when the package cache version changes (which
3340        // can only happen during upgrades).
3341        if (isUpgrade) {
3342            FileUtils.deleteContents(cacheBaseDir);
3343        }
3344
3345
3346        // Return the versioned package cache directory. This is something like
3347        // "/data/system/package_cache/1"
3348        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3349
3350        // The following is a workaround to aid development on non-numbered userdebug
3351        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3352        // the system partition is newer.
3353        //
3354        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3355        // that starts with "eng." to signify that this is an engineering build and not
3356        // destined for release.
3357        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3358            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3359
3360            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3361            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3362            // in general and should not be used for production changes. In this specific case,
3363            // we know that they will work.
3364            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3365            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3366                FileUtils.deleteContents(cacheBaseDir);
3367                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3368            }
3369        }
3370
3371        return cacheDir;
3372    }
3373
3374    @Override
3375    public boolean isFirstBoot() {
3376        // allow instant applications
3377        return mFirstBoot;
3378    }
3379
3380    @Override
3381    public boolean isOnlyCoreApps() {
3382        // allow instant applications
3383        return mOnlyCore;
3384    }
3385
3386    @Override
3387    public boolean isUpgrade() {
3388        // allow instant applications
3389        return mIsUpgrade;
3390    }
3391
3392    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3393        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3394
3395        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3396                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3397                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3398        if (matches.size() == 1) {
3399            return matches.get(0).getComponentInfo().packageName;
3400        } else if (matches.size() == 0) {
3401            Log.e(TAG, "There should probably be a verifier, but, none were found");
3402            return null;
3403        }
3404        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3405    }
3406
3407    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3408        synchronized (mPackages) {
3409            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3410            if (libraryEntry == null) {
3411                throw new IllegalStateException("Missing required shared library:" + name);
3412            }
3413            return libraryEntry.apk;
3414        }
3415    }
3416
3417    private @NonNull String getRequiredInstallerLPr() {
3418        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3419        intent.addCategory(Intent.CATEGORY_DEFAULT);
3420        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3421
3422        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM);
3425        if (matches.size() == 1) {
3426            ResolveInfo resolveInfo = matches.get(0);
3427            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3428                throw new RuntimeException("The installer must be a privileged app");
3429            }
3430            return matches.get(0).getComponentInfo().packageName;
3431        } else {
3432            throw new RuntimeException("There must be exactly one installer; found " + matches);
3433        }
3434    }
3435
3436    private @NonNull String getRequiredUninstallerLPr() {
3437        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3438        intent.addCategory(Intent.CATEGORY_DEFAULT);
3439        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3440
3441        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3442                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3443                UserHandle.USER_SYSTEM);
3444        if (resolveInfo == null ||
3445                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3446            throw new RuntimeException("There must be exactly one uninstaller; found "
3447                    + resolveInfo);
3448        }
3449        return resolveInfo.getComponentInfo().packageName;
3450    }
3451
3452    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3453        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3454
3455        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3456                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3457                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3458        ResolveInfo best = null;
3459        final int N = matches.size();
3460        for (int i = 0; i < N; i++) {
3461            final ResolveInfo cur = matches.get(i);
3462            final String packageName = cur.getComponentInfo().packageName;
3463            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3464                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3465                continue;
3466            }
3467
3468            if (best == null || cur.priority > best.priority) {
3469                best = cur;
3470            }
3471        }
3472
3473        if (best != null) {
3474            return best.getComponentInfo().getComponentName();
3475        }
3476        Slog.w(TAG, "Intent filter verifier not found");
3477        return null;
3478    }
3479
3480    @Override
3481    public @Nullable ComponentName getInstantAppResolverComponent() {
3482        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3483            return null;
3484        }
3485        synchronized (mPackages) {
3486            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3487            if (instantAppResolver == null) {
3488                return null;
3489            }
3490            return instantAppResolver.first;
3491        }
3492    }
3493
3494    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3495        final String[] packageArray =
3496                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3497        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3498            if (DEBUG_EPHEMERAL) {
3499                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3500            }
3501            return null;
3502        }
3503
3504        final int callingUid = Binder.getCallingUid();
3505        final int resolveFlags =
3506                MATCH_DIRECT_BOOT_AWARE
3507                | MATCH_DIRECT_BOOT_UNAWARE
3508                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3509        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3510        final Intent resolverIntent = new Intent(actionName);
3511        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3512                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3513        // temporarily look for the old action
3514        if (resolvers.size() == 0) {
3515            if (DEBUG_EPHEMERAL) {
3516                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3517            }
3518            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3519            resolverIntent.setAction(actionName);
3520            resolvers = queryIntentServicesInternal(resolverIntent, null,
3521                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3522        }
3523        final int N = resolvers.size();
3524        if (N == 0) {
3525            if (DEBUG_EPHEMERAL) {
3526                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3527            }
3528            return null;
3529        }
3530
3531        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3532        for (int i = 0; i < N; i++) {
3533            final ResolveInfo info = resolvers.get(i);
3534
3535            if (info.serviceInfo == null) {
3536                continue;
3537            }
3538
3539            final String packageName = info.serviceInfo.packageName;
3540            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3541                if (DEBUG_EPHEMERAL) {
3542                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3543                            + " pkg: " + packageName + ", info:" + info);
3544                }
3545                continue;
3546            }
3547
3548            if (DEBUG_EPHEMERAL) {
3549                Slog.v(TAG, "Ephemeral resolver found;"
3550                        + " pkg: " + packageName + ", info:" + info);
3551            }
3552            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3553        }
3554        if (DEBUG_EPHEMERAL) {
3555            Slog.v(TAG, "Ephemeral resolver NOT found");
3556        }
3557        return null;
3558    }
3559
3560    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3561        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3562        intent.addCategory(Intent.CATEGORY_DEFAULT);
3563        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3564
3565        final int resolveFlags =
3566                MATCH_DIRECT_BOOT_AWARE
3567                | MATCH_DIRECT_BOOT_UNAWARE
3568                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3569        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3570                resolveFlags, UserHandle.USER_SYSTEM);
3571        // temporarily look for the old action
3572        if (matches.isEmpty()) {
3573            if (DEBUG_EPHEMERAL) {
3574                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3575            }
3576            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3577            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3578                    resolveFlags, UserHandle.USER_SYSTEM);
3579        }
3580        Iterator<ResolveInfo> iter = matches.iterator();
3581        while (iter.hasNext()) {
3582            final ResolveInfo rInfo = iter.next();
3583            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3584            if (ps != null) {
3585                final PermissionsState permissionsState = ps.getPermissionsState();
3586                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3587                    continue;
3588                }
3589            }
3590            iter.remove();
3591        }
3592        if (matches.size() == 0) {
3593            return null;
3594        } else if (matches.size() == 1) {
3595            return (ActivityInfo) matches.get(0).getComponentInfo();
3596        } else {
3597            throw new RuntimeException(
3598                    "There must be at most one ephemeral installer; found " + matches);
3599        }
3600    }
3601
3602    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3603            @NonNull ComponentName resolver) {
3604        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3605                .addCategory(Intent.CATEGORY_DEFAULT)
3606                .setPackage(resolver.getPackageName());
3607        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3608        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3609                UserHandle.USER_SYSTEM);
3610        // temporarily look for the old action
3611        if (matches.isEmpty()) {
3612            if (DEBUG_EPHEMERAL) {
3613                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3614            }
3615            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3616            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3617                    UserHandle.USER_SYSTEM);
3618        }
3619        if (matches.isEmpty()) {
3620            return null;
3621        }
3622        return matches.get(0).getComponentInfo().getComponentName();
3623    }
3624
3625    private void primeDomainVerificationsLPw(int userId) {
3626        if (DEBUG_DOMAIN_VERIFICATION) {
3627            Slog.d(TAG, "Priming domain verifications in user " + userId);
3628        }
3629
3630        SystemConfig systemConfig = SystemConfig.getInstance();
3631        ArraySet<String> packages = systemConfig.getLinkedApps();
3632
3633        for (String packageName : packages) {
3634            PackageParser.Package pkg = mPackages.get(packageName);
3635            if (pkg != null) {
3636                if (!pkg.isSystemApp()) {
3637                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3638                    continue;
3639                }
3640
3641                ArraySet<String> domains = null;
3642                for (PackageParser.Activity a : pkg.activities) {
3643                    for (ActivityIntentInfo filter : a.intents) {
3644                        if (hasValidDomains(filter)) {
3645                            if (domains == null) {
3646                                domains = new ArraySet<String>();
3647                            }
3648                            domains.addAll(filter.getHostsList());
3649                        }
3650                    }
3651                }
3652
3653                if (domains != null && domains.size() > 0) {
3654                    if (DEBUG_DOMAIN_VERIFICATION) {
3655                        Slog.v(TAG, "      + " + packageName);
3656                    }
3657                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3658                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3659                    // and then 'always' in the per-user state actually used for intent resolution.
3660                    final IntentFilterVerificationInfo ivi;
3661                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3662                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3663                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3664                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3665                } else {
3666                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3667                            + "' does not handle web links");
3668                }
3669            } else {
3670                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3671            }
3672        }
3673
3674        scheduleWritePackageRestrictionsLocked(userId);
3675        scheduleWriteSettingsLocked();
3676    }
3677
3678    private void applyFactoryDefaultBrowserLPw(int userId) {
3679        // The default browser app's package name is stored in a string resource,
3680        // with a product-specific overlay used for vendor customization.
3681        String browserPkg = mContext.getResources().getString(
3682                com.android.internal.R.string.default_browser);
3683        if (!TextUtils.isEmpty(browserPkg)) {
3684            // non-empty string => required to be a known package
3685            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3686            if (ps == null) {
3687                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3688                browserPkg = null;
3689            } else {
3690                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3691            }
3692        }
3693
3694        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3695        // default.  If there's more than one, just leave everything alone.
3696        if (browserPkg == null) {
3697            calculateDefaultBrowserLPw(userId);
3698        }
3699    }
3700
3701    private void calculateDefaultBrowserLPw(int userId) {
3702        List<String> allBrowsers = resolveAllBrowserApps(userId);
3703        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3704        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3705    }
3706
3707    private List<String> resolveAllBrowserApps(int userId) {
3708        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3709        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3710                PackageManager.MATCH_ALL, userId);
3711
3712        final int count = list.size();
3713        List<String> result = new ArrayList<String>(count);
3714        for (int i=0; i<count; i++) {
3715            ResolveInfo info = list.get(i);
3716            if (info.activityInfo == null
3717                    || !info.handleAllWebDataURI
3718                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3719                    || result.contains(info.activityInfo.packageName)) {
3720                continue;
3721            }
3722            result.add(info.activityInfo.packageName);
3723        }
3724
3725        return result;
3726    }
3727
3728    private boolean packageIsBrowser(String packageName, int userId) {
3729        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3730                PackageManager.MATCH_ALL, userId);
3731        final int N = list.size();
3732        for (int i = 0; i < N; i++) {
3733            ResolveInfo info = list.get(i);
3734            if (packageName.equals(info.activityInfo.packageName)) {
3735                return true;
3736            }
3737        }
3738        return false;
3739    }
3740
3741    private void checkDefaultBrowser() {
3742        final int myUserId = UserHandle.myUserId();
3743        final String packageName = getDefaultBrowserPackageName(myUserId);
3744        if (packageName != null) {
3745            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3746            if (info == null) {
3747                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3748                synchronized (mPackages) {
3749                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3750                }
3751            }
3752        }
3753    }
3754
3755    @Override
3756    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3757            throws RemoteException {
3758        try {
3759            return super.onTransact(code, data, reply, flags);
3760        } catch (RuntimeException e) {
3761            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3762                Slog.wtf(TAG, "Package Manager Crash", e);
3763            }
3764            throw e;
3765        }
3766    }
3767
3768    static int[] appendInts(int[] cur, int[] add) {
3769        if (add == null) return cur;
3770        if (cur == null) return add;
3771        final int N = add.length;
3772        for (int i=0; i<N; i++) {
3773            cur = appendInt(cur, add[i]);
3774        }
3775        return cur;
3776    }
3777
3778    /**
3779     * Returns whether or not a full application can see an instant application.
3780     * <p>
3781     * Currently, there are three cases in which this can occur:
3782     * <ol>
3783     * <li>The calling application is a "special" process. The special
3784     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3785     *     and {@code 0}</li>
3786     * <li>The calling application has the permission
3787     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3788     * <li>The calling application is the default launcher on the
3789     *     system partition.</li>
3790     * </ol>
3791     */
3792    private boolean canViewInstantApps(int callingUid, int userId) {
3793        if (callingUid == Process.SYSTEM_UID
3794                || callingUid == Process.SHELL_UID
3795                || callingUid == Process.ROOT_UID) {
3796            return true;
3797        }
3798        if (mContext.checkCallingOrSelfPermission(
3799                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3800            return true;
3801        }
3802        if (mContext.checkCallingOrSelfPermission(
3803                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3804            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3805            if (homeComponent != null
3806                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3807                return true;
3808            }
3809        }
3810        return false;
3811    }
3812
3813    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        if (ps == null) {
3816            return null;
3817        }
3818        PackageParser.Package p = ps.pkg;
3819        if (p == null) {
3820            return null;
3821        }
3822        final int callingUid = Binder.getCallingUid();
3823        // Filter out ephemeral app metadata:
3824        //   * The system/shell/root can see metadata for any app
3825        //   * An installed app can see metadata for 1) other installed apps
3826        //     and 2) ephemeral apps that have explicitly interacted with it
3827        //   * Ephemeral apps can only see their own data and exposed installed apps
3828        //   * Holding a signature permission allows seeing instant apps
3829        if (filterAppAccessLPr(ps, callingUid, userId)) {
3830            return null;
3831        }
3832
3833        final PermissionsState permissionsState = ps.getPermissionsState();
3834
3835        // Compute GIDs only if requested
3836        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3837                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3838        // Compute granted permissions only if package has requested permissions
3839        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3840                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3841        final PackageUserState state = ps.readUserState(userId);
3842
3843        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3844                && ps.isSystem()) {
3845            flags |= MATCH_ANY_USER;
3846        }
3847
3848        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3849                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3850
3851        if (packageInfo == null) {
3852            return null;
3853        }
3854
3855        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3856                resolveExternalPackageNameLPr(p);
3857
3858        return packageInfo;
3859    }
3860
3861    @Override
3862    public void checkPackageStartable(String packageName, int userId) {
3863        final int callingUid = Binder.getCallingUid();
3864        if (getInstantAppPackageName(callingUid) != null) {
3865            throw new SecurityException("Instant applications don't have access to this method");
3866        }
3867        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3868        synchronized (mPackages) {
3869            final PackageSetting ps = mSettings.mPackages.get(packageName);
3870            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3871                throw new SecurityException("Package " + packageName + " was not found!");
3872            }
3873
3874            if (!ps.getInstalled(userId)) {
3875                throw new SecurityException(
3876                        "Package " + packageName + " was not installed for user " + userId + "!");
3877            }
3878
3879            if (mSafeMode && !ps.isSystem()) {
3880                throw new SecurityException("Package " + packageName + " not a system app!");
3881            }
3882
3883            if (mFrozenPackages.contains(packageName)) {
3884                throw new SecurityException("Package " + packageName + " is currently frozen!");
3885            }
3886
3887            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3888                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3889                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3890            }
3891        }
3892    }
3893
3894    @Override
3895    public boolean isPackageAvailable(String packageName, int userId) {
3896        if (!sUserManager.exists(userId)) return false;
3897        final int callingUid = Binder.getCallingUid();
3898        enforceCrossUserPermission(callingUid, userId,
3899                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3900        synchronized (mPackages) {
3901            PackageParser.Package p = mPackages.get(packageName);
3902            if (p != null) {
3903                final PackageSetting ps = (PackageSetting) p.mExtras;
3904                if (filterAppAccessLPr(ps, callingUid, userId)) {
3905                    return false;
3906                }
3907                if (ps != null) {
3908                    final PackageUserState state = ps.readUserState(userId);
3909                    if (state != null) {
3910                        return PackageParser.isAvailable(state);
3911                    }
3912                }
3913            }
3914        }
3915        return false;
3916    }
3917
3918    @Override
3919    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3920        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3921                flags, Binder.getCallingUid(), userId);
3922    }
3923
3924    @Override
3925    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3926            int flags, int userId) {
3927        return getPackageInfoInternal(versionedPackage.getPackageName(),
3928                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3929    }
3930
3931    /**
3932     * Important: The provided filterCallingUid is used exclusively to filter out packages
3933     * that can be seen based on user state. It's typically the original caller uid prior
3934     * to clearing. Because it can only be provided by trusted code, it's value can be
3935     * trusted and will be used as-is; unlike userId which will be validated by this method.
3936     */
3937    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3938            int flags, int filterCallingUid, int userId) {
3939        if (!sUserManager.exists(userId)) return null;
3940        flags = updateFlagsForPackage(flags, userId, packageName);
3941        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3942                false /* requireFullPermission */, false /* checkShell */, "get package info");
3943
3944        // reader
3945        synchronized (mPackages) {
3946            // Normalize package name to handle renamed packages and static libs
3947            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3948
3949            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3950            if (matchFactoryOnly) {
3951                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3952                if (ps != null) {
3953                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3954                        return null;
3955                    }
3956                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3957                        return null;
3958                    }
3959                    return generatePackageInfo(ps, flags, userId);
3960                }
3961            }
3962
3963            PackageParser.Package p = mPackages.get(packageName);
3964            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3965                return null;
3966            }
3967            if (DEBUG_PACKAGE_INFO)
3968                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3969            if (p != null) {
3970                final PackageSetting ps = (PackageSetting) p.mExtras;
3971                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3972                    return null;
3973                }
3974                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3975                    return null;
3976                }
3977                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3978            }
3979            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps == null) return null;
3982                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3983                    return null;
3984                }
3985                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3986                    return null;
3987                }
3988                return generatePackageInfo(ps, flags, userId);
3989            }
3990        }
3991        return null;
3992    }
3993
3994    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3995        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3996            return true;
3997        }
3998        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3999            return true;
4000        }
4001        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4002            return true;
4003        }
4004        return false;
4005    }
4006
4007    private boolean isComponentVisibleToInstantApp(
4008            @Nullable ComponentName component, @ComponentType int type) {
4009        if (type == TYPE_ACTIVITY) {
4010            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4011            return activity != null
4012                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4013                    : false;
4014        } else if (type == TYPE_RECEIVER) {
4015            final PackageParser.Activity activity = mReceivers.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_SERVICE) {
4020            final PackageParser.Service service = mServices.mServices.get(component);
4021            return service != null
4022                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4023                    : false;
4024        } else if (type == TYPE_PROVIDER) {
4025            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4026            return provider != null
4027                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4028                    : false;
4029        } else if (type == TYPE_UNKNOWN) {
4030            return isComponentVisibleToInstantApp(component);
4031        }
4032        return false;
4033    }
4034
4035    /**
4036     * Returns whether or not access to the application should be filtered.
4037     * <p>
4038     * Access may be limited based upon whether the calling or target applications
4039     * are instant applications.
4040     *
4041     * @see #canAccessInstantApps(int)
4042     */
4043    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4044            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4045        // if we're in an isolated process, get the real calling UID
4046        if (Process.isIsolated(callingUid)) {
4047            callingUid = mIsolatedOwners.get(callingUid);
4048        }
4049        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4050        final boolean callerIsInstantApp = instantAppPkgName != null;
4051        if (ps == null) {
4052            if (callerIsInstantApp) {
4053                // pretend the application exists, but, needs to be filtered
4054                return true;
4055            }
4056            return false;
4057        }
4058        // if the target and caller are the same application, don't filter
4059        if (isCallerSameApp(ps.name, callingUid)) {
4060            return false;
4061        }
4062        if (callerIsInstantApp) {
4063            // request for a specific component; if it hasn't been explicitly exposed, filter
4064            if (component != null) {
4065                return !isComponentVisibleToInstantApp(component, componentType);
4066            }
4067            // request for application; if no components have been explicitly exposed, filter
4068            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4069        }
4070        if (ps.getInstantApp(userId)) {
4071            // caller can see all components of all instant applications, don't filter
4072            if (canViewInstantApps(callingUid, userId)) {
4073                return false;
4074            }
4075            // request for a specific instant application component, filter
4076            if (component != null) {
4077                return true;
4078            }
4079            // request for an instant application; if the caller hasn't been granted access, filter
4080            return !mInstantAppRegistry.isInstantAccessGranted(
4081                    userId, UserHandle.getAppId(callingUid), ps.appId);
4082        }
4083        return false;
4084    }
4085
4086    /**
4087     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4088     */
4089    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4090        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4091    }
4092
4093    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4094            int flags) {
4095        // Callers can access only the libs they depend on, otherwise they need to explicitly
4096        // ask for the shared libraries given the caller is allowed to access all static libs.
4097        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4098            // System/shell/root get to see all static libs
4099            final int appId = UserHandle.getAppId(uid);
4100            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4101                    || appId == Process.ROOT_UID) {
4102                return false;
4103            }
4104        }
4105
4106        // No package means no static lib as it is always on internal storage
4107        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4108            return false;
4109        }
4110
4111        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4112                ps.pkg.staticSharedLibVersion);
4113        if (libEntry == null) {
4114            return false;
4115        }
4116
4117        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4118        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4119        if (uidPackageNames == null) {
4120            return true;
4121        }
4122
4123        for (String uidPackageName : uidPackageNames) {
4124            if (ps.name.equals(uidPackageName)) {
4125                return false;
4126            }
4127            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4128            if (uidPs != null) {
4129                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4130                        libEntry.info.getName());
4131                if (index < 0) {
4132                    continue;
4133                }
4134                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4135                    return false;
4136                }
4137            }
4138        }
4139        return true;
4140    }
4141
4142    @Override
4143    public String[] currentToCanonicalPackageNames(String[] names) {
4144        final int callingUid = Binder.getCallingUid();
4145        if (getInstantAppPackageName(callingUid) != null) {
4146            return names;
4147        }
4148        final String[] out = new String[names.length];
4149        // reader
4150        synchronized (mPackages) {
4151            final int callingUserId = UserHandle.getUserId(callingUid);
4152            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4153            for (int i=names.length-1; i>=0; i--) {
4154                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4155                boolean translateName = false;
4156                if (ps != null && ps.realName != null) {
4157                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4158                    translateName = !targetIsInstantApp
4159                            || canViewInstantApps
4160                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4161                                    UserHandle.getAppId(callingUid), ps.appId);
4162                }
4163                out[i] = translateName ? ps.realName : names[i];
4164            }
4165        }
4166        return out;
4167    }
4168
4169    @Override
4170    public String[] canonicalToCurrentPackageNames(String[] names) {
4171        final int callingUid = Binder.getCallingUid();
4172        if (getInstantAppPackageName(callingUid) != null) {
4173            return names;
4174        }
4175        final String[] out = new String[names.length];
4176        // reader
4177        synchronized (mPackages) {
4178            final int callingUserId = UserHandle.getUserId(callingUid);
4179            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4180            for (int i=names.length-1; i>=0; i--) {
4181                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4182                boolean translateName = false;
4183                if (cur != null) {
4184                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4185                    final boolean targetIsInstantApp =
4186                            ps != null && ps.getInstantApp(callingUserId);
4187                    translateName = !targetIsInstantApp
4188                            || canViewInstantApps
4189                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4190                                    UserHandle.getAppId(callingUid), ps.appId);
4191                }
4192                out[i] = translateName ? cur : names[i];
4193            }
4194        }
4195        return out;
4196    }
4197
4198    @Override
4199    public int getPackageUid(String packageName, int flags, int userId) {
4200        if (!sUserManager.exists(userId)) return -1;
4201        final int callingUid = Binder.getCallingUid();
4202        flags = updateFlagsForPackage(flags, userId, packageName);
4203        enforceCrossUserPermission(callingUid, userId,
4204                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4205
4206        // reader
4207        synchronized (mPackages) {
4208            final PackageParser.Package p = mPackages.get(packageName);
4209            if (p != null && p.isMatch(flags)) {
4210                PackageSetting ps = (PackageSetting) p.mExtras;
4211                if (filterAppAccessLPr(ps, callingUid, userId)) {
4212                    return -1;
4213                }
4214                return UserHandle.getUid(userId, p.applicationInfo.uid);
4215            }
4216            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4217                final PackageSetting ps = mSettings.mPackages.get(packageName);
4218                if (ps != null && ps.isMatch(flags)
4219                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4220                    return UserHandle.getUid(userId, ps.appId);
4221                }
4222            }
4223        }
4224
4225        return -1;
4226    }
4227
4228    @Override
4229    public int[] getPackageGids(String packageName, int flags, int userId) {
4230        if (!sUserManager.exists(userId)) return null;
4231        final int callingUid = Binder.getCallingUid();
4232        flags = updateFlagsForPackage(flags, userId, packageName);
4233        enforceCrossUserPermission(callingUid, userId,
4234                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4235
4236        // reader
4237        synchronized (mPackages) {
4238            final PackageParser.Package p = mPackages.get(packageName);
4239            if (p != null && p.isMatch(flags)) {
4240                PackageSetting ps = (PackageSetting) p.mExtras;
4241                if (filterAppAccessLPr(ps, callingUid, userId)) {
4242                    return null;
4243                }
4244                // TODO: Shouldn't this be checking for package installed state for userId and
4245                // return null?
4246                return ps.getPermissionsState().computeGids(userId);
4247            }
4248            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4249                final PackageSetting ps = mSettings.mPackages.get(packageName);
4250                if (ps != null && ps.isMatch(flags)
4251                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4252                    return ps.getPermissionsState().computeGids(userId);
4253                }
4254            }
4255        }
4256
4257        return null;
4258    }
4259
4260    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4261        if (bp.perm != null) {
4262            return PackageParser.generatePermissionInfo(bp.perm, flags);
4263        }
4264        PermissionInfo pi = new PermissionInfo();
4265        pi.name = bp.name;
4266        pi.packageName = bp.sourcePackage;
4267        pi.nonLocalizedLabel = bp.name;
4268        pi.protectionLevel = bp.protectionLevel;
4269        return pi;
4270    }
4271
4272    @Override
4273    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4274        final int callingUid = Binder.getCallingUid();
4275        if (getInstantAppPackageName(callingUid) != null) {
4276            return null;
4277        }
4278        // reader
4279        synchronized (mPackages) {
4280            final BasePermission p = mSettings.mPermissions.get(name);
4281            if (p == null) {
4282                return null;
4283            }
4284            // If the caller is an app that targets pre 26 SDK drop protection flags.
4285            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4286            if (permissionInfo != null) {
4287                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4288                        permissionInfo.protectionLevel, packageName, callingUid);
4289                if (permissionInfo.protectionLevel != protectionLevel) {
4290                    // If we return different protection level, don't use the cached info
4291                    if (p.perm != null && p.perm.info == permissionInfo) {
4292                        permissionInfo = new PermissionInfo(permissionInfo);
4293                    }
4294                    permissionInfo.protectionLevel = protectionLevel;
4295                }
4296            }
4297            return permissionInfo;
4298        }
4299    }
4300
4301    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4302            String packageName, int uid) {
4303        // Signature permission flags area always reported
4304        final int protectionLevelMasked = protectionLevel
4305                & (PermissionInfo.PROTECTION_NORMAL
4306                | PermissionInfo.PROTECTION_DANGEROUS
4307                | PermissionInfo.PROTECTION_SIGNATURE);
4308        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4309            return protectionLevel;
4310        }
4311
4312        // System sees all flags.
4313        final int appId = UserHandle.getAppId(uid);
4314        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4315                || appId == Process.SHELL_UID) {
4316            return protectionLevel;
4317        }
4318
4319        // Normalize package name to handle renamed packages and static libs
4320        packageName = resolveInternalPackageNameLPr(packageName,
4321                PackageManager.VERSION_CODE_HIGHEST);
4322
4323        // Apps that target O see flags for all protection levels.
4324        final PackageSetting ps = mSettings.mPackages.get(packageName);
4325        if (ps == null) {
4326            return protectionLevel;
4327        }
4328        if (ps.appId != appId) {
4329            return protectionLevel;
4330        }
4331
4332        final PackageParser.Package pkg = mPackages.get(packageName);
4333        if (pkg == null) {
4334            return protectionLevel;
4335        }
4336        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4337            return protectionLevelMasked;
4338        }
4339
4340        return protectionLevel;
4341    }
4342
4343    @Override
4344    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4345            int flags) {
4346        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4347            return null;
4348        }
4349        // reader
4350        synchronized (mPackages) {
4351            if (group != null && !mPermissionGroups.containsKey(group)) {
4352                // This is thrown as NameNotFoundException
4353                return null;
4354            }
4355
4356            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4357            for (BasePermission p : mSettings.mPermissions.values()) {
4358                if (group == null) {
4359                    if (p.perm == null || p.perm.info.group == null) {
4360                        out.add(generatePermissionInfo(p, flags));
4361                    }
4362                } else {
4363                    if (p.perm != null && group.equals(p.perm.info.group)) {
4364                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4365                    }
4366                }
4367            }
4368            return new ParceledListSlice<>(out);
4369        }
4370    }
4371
4372    @Override
4373    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4374        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4375            return null;
4376        }
4377        // reader
4378        synchronized (mPackages) {
4379            return PackageParser.generatePermissionGroupInfo(
4380                    mPermissionGroups.get(name), flags);
4381        }
4382    }
4383
4384    @Override
4385    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4387            return ParceledListSlice.emptyList();
4388        }
4389        // reader
4390        synchronized (mPackages) {
4391            final int N = mPermissionGroups.size();
4392            ArrayList<PermissionGroupInfo> out
4393                    = new ArrayList<PermissionGroupInfo>(N);
4394            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4395                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4396            }
4397            return new ParceledListSlice<>(out);
4398        }
4399    }
4400
4401    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4402            int filterCallingUid, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        PackageSetting ps = mSettings.mPackages.get(packageName);
4405        if (ps != null) {
4406            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4407                return null;
4408            }
4409            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4410                return null;
4411            }
4412            if (ps.pkg == null) {
4413                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4414                if (pInfo != null) {
4415                    return pInfo.applicationInfo;
4416                }
4417                return null;
4418            }
4419            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4420                    ps.readUserState(userId), userId);
4421            if (ai != null) {
4422                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4423            }
4424            return ai;
4425        }
4426        return null;
4427    }
4428
4429    @Override
4430    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4431        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4432    }
4433
4434    /**
4435     * Important: The provided filterCallingUid is used exclusively to filter out applications
4436     * that can be seen based on user state. It's typically the original caller uid prior
4437     * to clearing. Because it can only be provided by trusted code, it's value can be
4438     * trusted and will be used as-is; unlike userId which will be validated by this method.
4439     */
4440    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4441            int filterCallingUid, int userId) {
4442        if (!sUserManager.exists(userId)) return null;
4443        flags = updateFlagsForApplication(flags, userId, packageName);
4444        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4445                false /* requireFullPermission */, false /* checkShell */, "get application info");
4446
4447        // writer
4448        synchronized (mPackages) {
4449            // Normalize package name to handle renamed packages and static libs
4450            packageName = resolveInternalPackageNameLPr(packageName,
4451                    PackageManager.VERSION_CODE_HIGHEST);
4452
4453            PackageParser.Package p = mPackages.get(packageName);
4454            if (DEBUG_PACKAGE_INFO) Log.v(
4455                    TAG, "getApplicationInfo " + packageName
4456                    + ": " + p);
4457            if (p != null) {
4458                PackageSetting ps = mSettings.mPackages.get(packageName);
4459                if (ps == null) return null;
4460                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4461                    return null;
4462                }
4463                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4464                    return null;
4465                }
4466                // Note: isEnabledLP() does not apply here - always return info
4467                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4468                        p, flags, ps.readUserState(userId), userId);
4469                if (ai != null) {
4470                    ai.packageName = resolveExternalPackageNameLPr(p);
4471                }
4472                return ai;
4473            }
4474            if ("android".equals(packageName)||"system".equals(packageName)) {
4475                return mAndroidApplication;
4476            }
4477            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4478                // Already generates the external package name
4479                return generateApplicationInfoFromSettingsLPw(packageName,
4480                        flags, filterCallingUid, userId);
4481            }
4482        }
4483        return null;
4484    }
4485
4486    private String normalizePackageNameLPr(String packageName) {
4487        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4488        return normalizedPackageName != null ? normalizedPackageName : packageName;
4489    }
4490
4491    @Override
4492    public void deletePreloadsFileCache() {
4493        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4494            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4495        }
4496        File dir = Environment.getDataPreloadsFileCacheDirectory();
4497        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4498        FileUtils.deleteContents(dir);
4499    }
4500
4501    @Override
4502    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4503            final int storageFlags, final IPackageDataObserver observer) {
4504        mContext.enforceCallingOrSelfPermission(
4505                android.Manifest.permission.CLEAR_APP_CACHE, null);
4506        mHandler.post(() -> {
4507            boolean success = false;
4508            try {
4509                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4510                success = true;
4511            } catch (IOException e) {
4512                Slog.w(TAG, e);
4513            }
4514            if (observer != null) {
4515                try {
4516                    observer.onRemoveCompleted(null, success);
4517                } catch (RemoteException e) {
4518                    Slog.w(TAG, e);
4519                }
4520            }
4521        });
4522    }
4523
4524    @Override
4525    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4526            final int storageFlags, final IntentSender pi) {
4527        mContext.enforceCallingOrSelfPermission(
4528                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4529        mHandler.post(() -> {
4530            boolean success = false;
4531            try {
4532                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4533                success = true;
4534            } catch (IOException e) {
4535                Slog.w(TAG, e);
4536            }
4537            if (pi != null) {
4538                try {
4539                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4540                } catch (SendIntentException e) {
4541                    Slog.w(TAG, e);
4542                }
4543            }
4544        });
4545    }
4546
4547    /**
4548     * Blocking call to clear various types of cached data across the system
4549     * until the requested bytes are available.
4550     */
4551    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4552        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4553        final File file = storage.findPathForUuid(volumeUuid);
4554        if (file.getUsableSpace() >= bytes) return;
4555
4556        if (ENABLE_FREE_CACHE_V2) {
4557            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4558                    volumeUuid);
4559            final boolean aggressive = (storageFlags
4560                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4561            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4562
4563            // 1. Pre-flight to determine if we have any chance to succeed
4564            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4565            if (internalVolume && (aggressive || SystemProperties
4566                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4567                deletePreloadsFileCache();
4568                if (file.getUsableSpace() >= bytes) return;
4569            }
4570
4571            // 3. Consider parsed APK data (aggressive only)
4572            if (internalVolume && aggressive) {
4573                FileUtils.deleteContents(mCacheDir);
4574                if (file.getUsableSpace() >= bytes) return;
4575            }
4576
4577            // 4. Consider cached app data (above quotas)
4578            try {
4579                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4580                        Installer.FLAG_FREE_CACHE_V2);
4581            } catch (InstallerException ignored) {
4582            }
4583            if (file.getUsableSpace() >= bytes) return;
4584
4585            // 5. Consider shared libraries with refcount=0 and age>min cache period
4586            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4587                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4588                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4589                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4590                return;
4591            }
4592
4593            // 6. Consider dexopt output (aggressive only)
4594            // TODO: Implement
4595
4596            // 7. Consider installed instant apps unused longer than min cache period
4597            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4598                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4599                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4600                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4601                return;
4602            }
4603
4604            // 8. Consider cached app data (below quotas)
4605            try {
4606                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4607                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4608            } catch (InstallerException ignored) {
4609            }
4610            if (file.getUsableSpace() >= bytes) return;
4611
4612            // 9. Consider DropBox entries
4613            // TODO: Implement
4614
4615            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4616            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4617                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4618                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4619                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4620                return;
4621            }
4622        } else {
4623            try {
4624                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4625            } catch (InstallerException ignored) {
4626            }
4627            if (file.getUsableSpace() >= bytes) return;
4628        }
4629
4630        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4631    }
4632
4633    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4634            throws IOException {
4635        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4636        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4637
4638        List<VersionedPackage> packagesToDelete = null;
4639        final long now = System.currentTimeMillis();
4640
4641        synchronized (mPackages) {
4642            final int[] allUsers = sUserManager.getUserIds();
4643            final int libCount = mSharedLibraries.size();
4644            for (int i = 0; i < libCount; i++) {
4645                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4646                if (versionedLib == null) {
4647                    continue;
4648                }
4649                final int versionCount = versionedLib.size();
4650                for (int j = 0; j < versionCount; j++) {
4651                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4652                    // Skip packages that are not static shared libs.
4653                    if (!libInfo.isStatic()) {
4654                        break;
4655                    }
4656                    // Important: We skip static shared libs used for some user since
4657                    // in such a case we need to keep the APK on the device. The check for
4658                    // a lib being used for any user is performed by the uninstall call.
4659                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4660                    // Resolve the package name - we use synthetic package names internally
4661                    final String internalPackageName = resolveInternalPackageNameLPr(
4662                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4663                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4664                    // Skip unused static shared libs cached less than the min period
4665                    // to prevent pruning a lib needed by a subsequently installed package.
4666                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4667                        continue;
4668                    }
4669                    if (packagesToDelete == null) {
4670                        packagesToDelete = new ArrayList<>();
4671                    }
4672                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4673                            declaringPackage.getVersionCode()));
4674                }
4675            }
4676        }
4677
4678        if (packagesToDelete != null) {
4679            final int packageCount = packagesToDelete.size();
4680            for (int i = 0; i < packageCount; i++) {
4681                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4682                // Delete the package synchronously (will fail of the lib used for any user).
4683                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4684                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4685                                == PackageManager.DELETE_SUCCEEDED) {
4686                    if (volume.getUsableSpace() >= neededSpace) {
4687                        return true;
4688                    }
4689                }
4690            }
4691        }
4692
4693        return false;
4694    }
4695
4696    /**
4697     * Update given flags based on encryption status of current user.
4698     */
4699    private int updateFlags(int flags, int userId) {
4700        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4701                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4702            // Caller expressed an explicit opinion about what encryption
4703            // aware/unaware components they want to see, so fall through and
4704            // give them what they want
4705        } else {
4706            // Caller expressed no opinion, so match based on user state
4707            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4708                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4709            } else {
4710                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4711            }
4712        }
4713        return flags;
4714    }
4715
4716    private UserManagerInternal getUserManagerInternal() {
4717        if (mUserManagerInternal == null) {
4718            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4719        }
4720        return mUserManagerInternal;
4721    }
4722
4723    private DeviceIdleController.LocalService getDeviceIdleController() {
4724        if (mDeviceIdleController == null) {
4725            mDeviceIdleController =
4726                    LocalServices.getService(DeviceIdleController.LocalService.class);
4727        }
4728        return mDeviceIdleController;
4729    }
4730
4731    /**
4732     * Update given flags when being used to request {@link PackageInfo}.
4733     */
4734    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4735        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4736        boolean triaged = true;
4737        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4738                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4739            // Caller is asking for component details, so they'd better be
4740            // asking for specific encryption matching behavior, or be triaged
4741            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4742                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4743                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4744                triaged = false;
4745            }
4746        }
4747        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4748                | PackageManager.MATCH_SYSTEM_ONLY
4749                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4750            triaged = false;
4751        }
4752        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4753            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4754                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4755                    + Debug.getCallers(5));
4756        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4757                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4758            // If the caller wants all packages and has a restricted profile associated with it,
4759            // then match all users. This is to make sure that launchers that need to access work
4760            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4761            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4762            flags |= PackageManager.MATCH_ANY_USER;
4763        }
4764        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4765            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4766                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4767        }
4768        return updateFlags(flags, userId);
4769    }
4770
4771    /**
4772     * Update given flags when being used to request {@link ApplicationInfo}.
4773     */
4774    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4775        return updateFlagsForPackage(flags, userId, cookie);
4776    }
4777
4778    /**
4779     * Update given flags when being used to request {@link ComponentInfo}.
4780     */
4781    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4782        if (cookie instanceof Intent) {
4783            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4784                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4785            }
4786        }
4787
4788        boolean triaged = true;
4789        // Caller is asking for component details, so they'd better be
4790        // asking for specific encryption matching behavior, or be triaged
4791        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4792                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4793                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4794            triaged = false;
4795        }
4796        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4797            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4798                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4799        }
4800
4801        return updateFlags(flags, userId);
4802    }
4803
4804    /**
4805     * Update given intent when being used to request {@link ResolveInfo}.
4806     */
4807    private Intent updateIntentForResolve(Intent intent) {
4808        if (intent.getSelector() != null) {
4809            intent = intent.getSelector();
4810        }
4811        if (DEBUG_PREFERRED) {
4812            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4813        }
4814        return intent;
4815    }
4816
4817    /**
4818     * Update given flags when being used to request {@link ResolveInfo}.
4819     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4820     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4821     * flag set. However, this flag is only honoured in three circumstances:
4822     * <ul>
4823     * <li>when called from a system process</li>
4824     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4825     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4826     * action and a {@code android.intent.category.BROWSABLE} category</li>
4827     * </ul>
4828     */
4829    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4830        return updateFlagsForResolve(flags, userId, intent, callingUid,
4831                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4832    }
4833    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4834            boolean wantInstantApps) {
4835        return updateFlagsForResolve(flags, userId, intent, callingUid,
4836                wantInstantApps, false /*onlyExposedExplicitly*/);
4837    }
4838    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4839            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4840        // Safe mode means we shouldn't match any third-party components
4841        if (mSafeMode) {
4842            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4843        }
4844        if (getInstantAppPackageName(callingUid) != null) {
4845            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4846            if (onlyExposedExplicitly) {
4847                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4848            }
4849            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4850            flags |= PackageManager.MATCH_INSTANT;
4851        } else {
4852            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4853            final boolean allowMatchInstant =
4854                    (wantInstantApps
4855                            && Intent.ACTION_VIEW.equals(intent.getAction())
4856                            && hasWebURI(intent))
4857                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4858            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4859                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4860            if (!allowMatchInstant) {
4861                flags &= ~PackageManager.MATCH_INSTANT;
4862            }
4863        }
4864        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4865    }
4866
4867    @Override
4868    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4869        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4870    }
4871
4872    /**
4873     * Important: The provided filterCallingUid is used exclusively to filter out activities
4874     * that can be seen based on user state. It's typically the original caller uid prior
4875     * to clearing. Because it can only be provided by trusted code, it's value can be
4876     * trusted and will be used as-is; unlike userId which will be validated by this method.
4877     */
4878    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4879            int filterCallingUid, int userId) {
4880        if (!sUserManager.exists(userId)) return null;
4881        flags = updateFlagsForComponent(flags, userId, component);
4882        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4883                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4884        synchronized (mPackages) {
4885            PackageParser.Activity a = mActivities.mActivities.get(component);
4886
4887            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4888            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4889                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4890                if (ps == null) return null;
4891                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4892                    return null;
4893                }
4894                return PackageParser.generateActivityInfo(
4895                        a, flags, ps.readUserState(userId), userId);
4896            }
4897            if (mResolveComponentName.equals(component)) {
4898                return PackageParser.generateActivityInfo(
4899                        mResolveActivity, flags, new PackageUserState(), userId);
4900            }
4901        }
4902        return null;
4903    }
4904
4905    @Override
4906    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4907            String resolvedType) {
4908        synchronized (mPackages) {
4909            if (component.equals(mResolveComponentName)) {
4910                // The resolver supports EVERYTHING!
4911                return true;
4912            }
4913            final int callingUid = Binder.getCallingUid();
4914            final int callingUserId = UserHandle.getUserId(callingUid);
4915            PackageParser.Activity a = mActivities.mActivities.get(component);
4916            if (a == null) {
4917                return false;
4918            }
4919            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4920            if (ps == null) {
4921                return false;
4922            }
4923            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4924                return false;
4925            }
4926            for (int i=0; i<a.intents.size(); i++) {
4927                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4928                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4929                    return true;
4930                }
4931            }
4932            return false;
4933        }
4934    }
4935
4936    @Override
4937    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4938        if (!sUserManager.exists(userId)) return null;
4939        final int callingUid = Binder.getCallingUid();
4940        flags = updateFlagsForComponent(flags, userId, component);
4941        enforceCrossUserPermission(callingUid, userId,
4942                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4943        synchronized (mPackages) {
4944            PackageParser.Activity a = mReceivers.mActivities.get(component);
4945            if (DEBUG_PACKAGE_INFO) Log.v(
4946                TAG, "getReceiverInfo " + component + ": " + a);
4947            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4948                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4949                if (ps == null) return null;
4950                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4951                    return null;
4952                }
4953                return PackageParser.generateActivityInfo(
4954                        a, flags, ps.readUserState(userId), userId);
4955            }
4956        }
4957        return null;
4958    }
4959
4960    @Override
4961    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4962            int flags, int userId) {
4963        if (!sUserManager.exists(userId)) return null;
4964        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4965        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4966            return null;
4967        }
4968
4969        flags = updateFlagsForPackage(flags, userId, null);
4970
4971        final boolean canSeeStaticLibraries =
4972                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4973                        == PERMISSION_GRANTED
4974                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4975                        == PERMISSION_GRANTED
4976                || canRequestPackageInstallsInternal(packageName,
4977                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4978                        false  /* throwIfPermNotDeclared*/)
4979                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4980                        == PERMISSION_GRANTED;
4981
4982        synchronized (mPackages) {
4983            List<SharedLibraryInfo> result = null;
4984
4985            final int libCount = mSharedLibraries.size();
4986            for (int i = 0; i < libCount; i++) {
4987                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4988                if (versionedLib == null) {
4989                    continue;
4990                }
4991
4992                final int versionCount = versionedLib.size();
4993                for (int j = 0; j < versionCount; j++) {
4994                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4995                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4996                        break;
4997                    }
4998                    final long identity = Binder.clearCallingIdentity();
4999                    try {
5000                        PackageInfo packageInfo = getPackageInfoVersioned(
5001                                libInfo.getDeclaringPackage(), flags
5002                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5003                        if (packageInfo == null) {
5004                            continue;
5005                        }
5006                    } finally {
5007                        Binder.restoreCallingIdentity(identity);
5008                    }
5009
5010                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5011                            libInfo.getVersion(), libInfo.getType(),
5012                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5013                            flags, userId));
5014
5015                    if (result == null) {
5016                        result = new ArrayList<>();
5017                    }
5018                    result.add(resLibInfo);
5019                }
5020            }
5021
5022            return result != null ? new ParceledListSlice<>(result) : null;
5023        }
5024    }
5025
5026    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5027            SharedLibraryInfo libInfo, int flags, int userId) {
5028        List<VersionedPackage> versionedPackages = null;
5029        final int packageCount = mSettings.mPackages.size();
5030        for (int i = 0; i < packageCount; i++) {
5031            PackageSetting ps = mSettings.mPackages.valueAt(i);
5032
5033            if (ps == null) {
5034                continue;
5035            }
5036
5037            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5038                continue;
5039            }
5040
5041            final String libName = libInfo.getName();
5042            if (libInfo.isStatic()) {
5043                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5044                if (libIdx < 0) {
5045                    continue;
5046                }
5047                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5048                    continue;
5049                }
5050                if (versionedPackages == null) {
5051                    versionedPackages = new ArrayList<>();
5052                }
5053                // If the dependent is a static shared lib, use the public package name
5054                String dependentPackageName = ps.name;
5055                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5056                    dependentPackageName = ps.pkg.manifestPackageName;
5057                }
5058                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5059            } else if (ps.pkg != null) {
5060                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5061                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5062                    if (versionedPackages == null) {
5063                        versionedPackages = new ArrayList<>();
5064                    }
5065                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5066                }
5067            }
5068        }
5069
5070        return versionedPackages;
5071    }
5072
5073    @Override
5074    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5075        if (!sUserManager.exists(userId)) return null;
5076        final int callingUid = Binder.getCallingUid();
5077        flags = updateFlagsForComponent(flags, userId, component);
5078        enforceCrossUserPermission(callingUid, userId,
5079                false /* requireFullPermission */, false /* checkShell */, "get service info");
5080        synchronized (mPackages) {
5081            PackageParser.Service s = mServices.mServices.get(component);
5082            if (DEBUG_PACKAGE_INFO) Log.v(
5083                TAG, "getServiceInfo " + component + ": " + s);
5084            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5085                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5086                if (ps == null) return null;
5087                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5088                    return null;
5089                }
5090                return PackageParser.generateServiceInfo(
5091                        s, flags, ps.readUserState(userId), userId);
5092            }
5093        }
5094        return null;
5095    }
5096
5097    @Override
5098    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5099        if (!sUserManager.exists(userId)) return null;
5100        final int callingUid = Binder.getCallingUid();
5101        flags = updateFlagsForComponent(flags, userId, component);
5102        enforceCrossUserPermission(callingUid, userId,
5103                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5104        synchronized (mPackages) {
5105            PackageParser.Provider p = mProviders.mProviders.get(component);
5106            if (DEBUG_PACKAGE_INFO) Log.v(
5107                TAG, "getProviderInfo " + component + ": " + p);
5108            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5109                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5110                if (ps == null) return null;
5111                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5112                    return null;
5113                }
5114                return PackageParser.generateProviderInfo(
5115                        p, flags, ps.readUserState(userId), userId);
5116            }
5117        }
5118        return null;
5119    }
5120
5121    @Override
5122    public String[] getSystemSharedLibraryNames() {
5123        // allow instant applications
5124        synchronized (mPackages) {
5125            Set<String> libs = null;
5126            final int libCount = mSharedLibraries.size();
5127            for (int i = 0; i < libCount; i++) {
5128                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5129                if (versionedLib == null) {
5130                    continue;
5131                }
5132                final int versionCount = versionedLib.size();
5133                for (int j = 0; j < versionCount; j++) {
5134                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5135                    if (!libEntry.info.isStatic()) {
5136                        if (libs == null) {
5137                            libs = new ArraySet<>();
5138                        }
5139                        libs.add(libEntry.info.getName());
5140                        break;
5141                    }
5142                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5143                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5144                            UserHandle.getUserId(Binder.getCallingUid()),
5145                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5146                        if (libs == null) {
5147                            libs = new ArraySet<>();
5148                        }
5149                        libs.add(libEntry.info.getName());
5150                        break;
5151                    }
5152                }
5153            }
5154
5155            if (libs != null) {
5156                String[] libsArray = new String[libs.size()];
5157                libs.toArray(libsArray);
5158                return libsArray;
5159            }
5160
5161            return null;
5162        }
5163    }
5164
5165    @Override
5166    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5167        // allow instant applications
5168        synchronized (mPackages) {
5169            return mServicesSystemSharedLibraryPackageName;
5170        }
5171    }
5172
5173    @Override
5174    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5175        // allow instant applications
5176        synchronized (mPackages) {
5177            return mSharedSystemSharedLibraryPackageName;
5178        }
5179    }
5180
5181    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5182        for (int i = userList.length - 1; i >= 0; --i) {
5183            final int userId = userList[i];
5184            // don't add instant app to the list of updates
5185            if (pkgSetting.getInstantApp(userId)) {
5186                continue;
5187            }
5188            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5189            if (changedPackages == null) {
5190                changedPackages = new SparseArray<>();
5191                mChangedPackages.put(userId, changedPackages);
5192            }
5193            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5194            if (sequenceNumbers == null) {
5195                sequenceNumbers = new HashMap<>();
5196                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5197            }
5198            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5199            if (sequenceNumber != null) {
5200                changedPackages.remove(sequenceNumber);
5201            }
5202            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5203            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5204        }
5205        mChangedPackagesSequenceNumber++;
5206    }
5207
5208    @Override
5209    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5211            return null;
5212        }
5213        synchronized (mPackages) {
5214            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5215                return null;
5216            }
5217            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5218            if (changedPackages == null) {
5219                return null;
5220            }
5221            final List<String> packageNames =
5222                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5223            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5224                final String packageName = changedPackages.get(i);
5225                if (packageName != null) {
5226                    packageNames.add(packageName);
5227                }
5228            }
5229            return packageNames.isEmpty()
5230                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5231        }
5232    }
5233
5234    @Override
5235    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5236        // allow instant applications
5237        ArrayList<FeatureInfo> res;
5238        synchronized (mAvailableFeatures) {
5239            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5240            res.addAll(mAvailableFeatures.values());
5241        }
5242        final FeatureInfo fi = new FeatureInfo();
5243        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5244                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5245        res.add(fi);
5246
5247        return new ParceledListSlice<>(res);
5248    }
5249
5250    @Override
5251    public boolean hasSystemFeature(String name, int version) {
5252        // allow instant applications
5253        synchronized (mAvailableFeatures) {
5254            final FeatureInfo feat = mAvailableFeatures.get(name);
5255            if (feat == null) {
5256                return false;
5257            } else {
5258                return feat.version >= version;
5259            }
5260        }
5261    }
5262
5263    @Override
5264    public int checkPermission(String permName, String pkgName, int userId) {
5265        if (!sUserManager.exists(userId)) {
5266            return PackageManager.PERMISSION_DENIED;
5267        }
5268        final int callingUid = Binder.getCallingUid();
5269
5270        synchronized (mPackages) {
5271            final PackageParser.Package p = mPackages.get(pkgName);
5272            if (p != null && p.mExtras != null) {
5273                final PackageSetting ps = (PackageSetting) p.mExtras;
5274                if (filterAppAccessLPr(ps, callingUid, userId)) {
5275                    return PackageManager.PERMISSION_DENIED;
5276                }
5277                final boolean instantApp = ps.getInstantApp(userId);
5278                final PermissionsState permissionsState = ps.getPermissionsState();
5279                if (permissionsState.hasPermission(permName, userId)) {
5280                    if (instantApp) {
5281                        BasePermission bp = mSettings.mPermissions.get(permName);
5282                        if (bp != null && bp.isInstant()) {
5283                            return PackageManager.PERMISSION_GRANTED;
5284                        }
5285                    } else {
5286                        return PackageManager.PERMISSION_GRANTED;
5287                    }
5288                }
5289                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5290                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5291                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5292                    return PackageManager.PERMISSION_GRANTED;
5293                }
5294            }
5295        }
5296
5297        return PackageManager.PERMISSION_DENIED;
5298    }
5299
5300    @Override
5301    public int checkUidPermission(String permName, int uid) {
5302        final int callingUid = Binder.getCallingUid();
5303        final int callingUserId = UserHandle.getUserId(callingUid);
5304        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5305        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5306        final int userId = UserHandle.getUserId(uid);
5307        if (!sUserManager.exists(userId)) {
5308            return PackageManager.PERMISSION_DENIED;
5309        }
5310
5311        synchronized (mPackages) {
5312            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5313            if (obj != null) {
5314                if (obj instanceof SharedUserSetting) {
5315                    if (isCallerInstantApp) {
5316                        return PackageManager.PERMISSION_DENIED;
5317                    }
5318                } else if (obj instanceof PackageSetting) {
5319                    final PackageSetting ps = (PackageSetting) obj;
5320                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5321                        return PackageManager.PERMISSION_DENIED;
5322                    }
5323                }
5324                final SettingBase settingBase = (SettingBase) obj;
5325                final PermissionsState permissionsState = settingBase.getPermissionsState();
5326                if (permissionsState.hasPermission(permName, userId)) {
5327                    if (isUidInstantApp) {
5328                        BasePermission bp = mSettings.mPermissions.get(permName);
5329                        if (bp != null && bp.isInstant()) {
5330                            return PackageManager.PERMISSION_GRANTED;
5331                        }
5332                    } else {
5333                        return PackageManager.PERMISSION_GRANTED;
5334                    }
5335                }
5336                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5337                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5338                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5339                    return PackageManager.PERMISSION_GRANTED;
5340                }
5341            } else {
5342                ArraySet<String> perms = mSystemPermissions.get(uid);
5343                if (perms != null) {
5344                    if (perms.contains(permName)) {
5345                        return PackageManager.PERMISSION_GRANTED;
5346                    }
5347                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5348                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5349                        return PackageManager.PERMISSION_GRANTED;
5350                    }
5351                }
5352            }
5353        }
5354
5355        return PackageManager.PERMISSION_DENIED;
5356    }
5357
5358    @Override
5359    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5360        if (UserHandle.getCallingUserId() != userId) {
5361            mContext.enforceCallingPermission(
5362                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5363                    "isPermissionRevokedByPolicy for user " + userId);
5364        }
5365
5366        if (checkPermission(permission, packageName, userId)
5367                == PackageManager.PERMISSION_GRANTED) {
5368            return false;
5369        }
5370
5371        final int callingUid = Binder.getCallingUid();
5372        if (getInstantAppPackageName(callingUid) != null) {
5373            if (!isCallerSameApp(packageName, callingUid)) {
5374                return false;
5375            }
5376        } else {
5377            if (isInstantApp(packageName, userId)) {
5378                return false;
5379            }
5380        }
5381
5382        final long identity = Binder.clearCallingIdentity();
5383        try {
5384            final int flags = getPermissionFlags(permission, packageName, userId);
5385            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5386        } finally {
5387            Binder.restoreCallingIdentity(identity);
5388        }
5389    }
5390
5391    @Override
5392    public String getPermissionControllerPackageName() {
5393        synchronized (mPackages) {
5394            return mRequiredInstallerPackage;
5395        }
5396    }
5397
5398    /**
5399     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5400     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5401     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5402     * @param message the message to log on security exception
5403     */
5404    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5405            boolean checkShell, String message) {
5406        if (userId < 0) {
5407            throw new IllegalArgumentException("Invalid userId " + userId);
5408        }
5409        if (checkShell) {
5410            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5411        }
5412        if (userId == UserHandle.getUserId(callingUid)) return;
5413        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5414            if (requireFullPermission) {
5415                mContext.enforceCallingOrSelfPermission(
5416                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5417            } else {
5418                try {
5419                    mContext.enforceCallingOrSelfPermission(
5420                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5421                } catch (SecurityException se) {
5422                    mContext.enforceCallingOrSelfPermission(
5423                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5424                }
5425            }
5426        }
5427    }
5428
5429    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5430        if (callingUid == Process.SHELL_UID) {
5431            if (userHandle >= 0
5432                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5433                throw new SecurityException("Shell does not have permission to access user "
5434                        + userHandle);
5435            } else if (userHandle < 0) {
5436                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5437                        + Debug.getCallers(3));
5438            }
5439        }
5440    }
5441
5442    private BasePermission findPermissionTreeLP(String permName) {
5443        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5444            if (permName.startsWith(bp.name) &&
5445                    permName.length() > bp.name.length() &&
5446                    permName.charAt(bp.name.length()) == '.') {
5447                return bp;
5448            }
5449        }
5450        return null;
5451    }
5452
5453    private BasePermission checkPermissionTreeLP(String permName) {
5454        if (permName != null) {
5455            BasePermission bp = findPermissionTreeLP(permName);
5456            if (bp != null) {
5457                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5458                    return bp;
5459                }
5460                throw new SecurityException("Calling uid "
5461                        + Binder.getCallingUid()
5462                        + " is not allowed to add to permission tree "
5463                        + bp.name + " owned by uid " + bp.uid);
5464            }
5465        }
5466        throw new SecurityException("No permission tree found for " + permName);
5467    }
5468
5469    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5470        if (s1 == null) {
5471            return s2 == null;
5472        }
5473        if (s2 == null) {
5474            return false;
5475        }
5476        if (s1.getClass() != s2.getClass()) {
5477            return false;
5478        }
5479        return s1.equals(s2);
5480    }
5481
5482    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5483        if (pi1.icon != pi2.icon) return false;
5484        if (pi1.logo != pi2.logo) return false;
5485        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5486        if (!compareStrings(pi1.name, pi2.name)) return false;
5487        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5488        // We'll take care of setting this one.
5489        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5490        // These are not currently stored in settings.
5491        //if (!compareStrings(pi1.group, pi2.group)) return false;
5492        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5493        //if (pi1.labelRes != pi2.labelRes) return false;
5494        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5495        return true;
5496    }
5497
5498    int permissionInfoFootprint(PermissionInfo info) {
5499        int size = info.name.length();
5500        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5501        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5502        return size;
5503    }
5504
5505    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5506        int size = 0;
5507        for (BasePermission perm : mSettings.mPermissions.values()) {
5508            if (perm.uid == tree.uid) {
5509                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5510            }
5511        }
5512        return size;
5513    }
5514
5515    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5516        // We calculate the max size of permissions defined by this uid and throw
5517        // if that plus the size of 'info' would exceed our stated maximum.
5518        if (tree.uid != Process.SYSTEM_UID) {
5519            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5520            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5521                throw new SecurityException("Permission tree size cap exceeded");
5522            }
5523        }
5524    }
5525
5526    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5527        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5528            throw new SecurityException("Instant apps can't add permissions");
5529        }
5530        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5531            throw new SecurityException("Label must be specified in permission");
5532        }
5533        BasePermission tree = checkPermissionTreeLP(info.name);
5534        BasePermission bp = mSettings.mPermissions.get(info.name);
5535        boolean added = bp == null;
5536        boolean changed = true;
5537        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5538        if (added) {
5539            enforcePermissionCapLocked(info, tree);
5540            bp = new BasePermission(info.name, tree.sourcePackage,
5541                    BasePermission.TYPE_DYNAMIC);
5542        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5543            throw new SecurityException(
5544                    "Not allowed to modify non-dynamic permission "
5545                    + info.name);
5546        } else {
5547            if (bp.protectionLevel == fixedLevel
5548                    && bp.perm.owner.equals(tree.perm.owner)
5549                    && bp.uid == tree.uid
5550                    && comparePermissionInfos(bp.perm.info, info)) {
5551                changed = false;
5552            }
5553        }
5554        bp.protectionLevel = fixedLevel;
5555        info = new PermissionInfo(info);
5556        info.protectionLevel = fixedLevel;
5557        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5558        bp.perm.info.packageName = tree.perm.info.packageName;
5559        bp.uid = tree.uid;
5560        if (added) {
5561            mSettings.mPermissions.put(info.name, bp);
5562        }
5563        if (changed) {
5564            if (!async) {
5565                mSettings.writeLPr();
5566            } else {
5567                scheduleWriteSettingsLocked();
5568            }
5569        }
5570        return added;
5571    }
5572
5573    @Override
5574    public boolean addPermission(PermissionInfo info) {
5575        synchronized (mPackages) {
5576            return addPermissionLocked(info, false);
5577        }
5578    }
5579
5580    @Override
5581    public boolean addPermissionAsync(PermissionInfo info) {
5582        synchronized (mPackages) {
5583            return addPermissionLocked(info, true);
5584        }
5585    }
5586
5587    @Override
5588    public void removePermission(String name) {
5589        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5590            throw new SecurityException("Instant applications don't have access to this method");
5591        }
5592        synchronized (mPackages) {
5593            checkPermissionTreeLP(name);
5594            BasePermission bp = mSettings.mPermissions.get(name);
5595            if (bp != null) {
5596                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5597                    throw new SecurityException(
5598                            "Not allowed to modify non-dynamic permission "
5599                            + name);
5600                }
5601                mSettings.mPermissions.remove(name);
5602                mSettings.writeLPr();
5603            }
5604        }
5605    }
5606
5607    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5608            PackageParser.Package pkg, BasePermission bp) {
5609        int index = pkg.requestedPermissions.indexOf(bp.name);
5610        if (index == -1) {
5611            throw new SecurityException("Package " + pkg.packageName
5612                    + " has not requested permission " + bp.name);
5613        }
5614        if (!bp.isRuntime() && !bp.isDevelopment()) {
5615            throw new SecurityException("Permission " + bp.name
5616                    + " is not a changeable permission type");
5617        }
5618    }
5619
5620    @Override
5621    public void grantRuntimePermission(String packageName, String name, final int userId) {
5622        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5623    }
5624
5625    private void grantRuntimePermission(String packageName, String name, final int userId,
5626            boolean overridePolicy) {
5627        if (!sUserManager.exists(userId)) {
5628            Log.e(TAG, "No such user:" + userId);
5629            return;
5630        }
5631        final int callingUid = Binder.getCallingUid();
5632
5633        mContext.enforceCallingOrSelfPermission(
5634                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5635                "grantRuntimePermission");
5636
5637        enforceCrossUserPermission(callingUid, userId,
5638                true /* requireFullPermission */, true /* checkShell */,
5639                "grantRuntimePermission");
5640
5641        final int uid;
5642        final PackageSetting ps;
5643
5644        synchronized (mPackages) {
5645            final PackageParser.Package pkg = mPackages.get(packageName);
5646            if (pkg == null) {
5647                throw new IllegalArgumentException("Unknown package: " + packageName);
5648            }
5649            final BasePermission bp = mSettings.mPermissions.get(name);
5650            if (bp == null) {
5651                throw new IllegalArgumentException("Unknown permission: " + name);
5652            }
5653            ps = (PackageSetting) pkg.mExtras;
5654            if (ps == null
5655                    || filterAppAccessLPr(ps, callingUid, userId)) {
5656                throw new IllegalArgumentException("Unknown package: " + packageName);
5657            }
5658
5659            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5660
5661            // If a permission review is required for legacy apps we represent
5662            // their permissions as always granted runtime ones since we need
5663            // to keep the review required permission flag per user while an
5664            // install permission's state is shared across all users.
5665            if (mPermissionReviewRequired
5666                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5667                    && bp.isRuntime()) {
5668                return;
5669            }
5670
5671            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5672
5673            final PermissionsState permissionsState = ps.getPermissionsState();
5674
5675            final int flags = permissionsState.getPermissionFlags(name, userId);
5676            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5677                throw new SecurityException("Cannot grant system fixed permission "
5678                        + name + " for package " + packageName);
5679            }
5680            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5681                throw new SecurityException("Cannot grant policy fixed permission "
5682                        + name + " for package " + packageName);
5683            }
5684
5685            if (bp.isDevelopment()) {
5686                // Development permissions must be handled specially, since they are not
5687                // normal runtime permissions.  For now they apply to all users.
5688                if (permissionsState.grantInstallPermission(bp) !=
5689                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5690                    scheduleWriteSettingsLocked();
5691                }
5692                return;
5693            }
5694
5695            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5696                throw new SecurityException("Cannot grant non-ephemeral permission"
5697                        + name + " for package " + packageName);
5698            }
5699
5700            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5701                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5702                return;
5703            }
5704
5705            final int result = permissionsState.grantRuntimePermission(bp, userId);
5706            switch (result) {
5707                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5708                    return;
5709                }
5710
5711                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5712                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5713                    mHandler.post(new Runnable() {
5714                        @Override
5715                        public void run() {
5716                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5717                        }
5718                    });
5719                }
5720                break;
5721            }
5722
5723            if (bp.isRuntime()) {
5724                logPermissionGranted(mContext, name, packageName);
5725            }
5726
5727            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5728
5729            // Not critical if that is lost - app has to request again.
5730            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5731        }
5732
5733        // Only need to do this if user is initialized. Otherwise it's a new user
5734        // and there are no processes running as the user yet and there's no need
5735        // to make an expensive call to remount processes for the changed permissions.
5736        if (READ_EXTERNAL_STORAGE.equals(name)
5737                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5738            final long token = Binder.clearCallingIdentity();
5739            try {
5740                if (sUserManager.isInitialized(userId)) {
5741                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5742                            StorageManagerInternal.class);
5743                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5744                }
5745            } finally {
5746                Binder.restoreCallingIdentity(token);
5747            }
5748        }
5749    }
5750
5751    @Override
5752    public void revokeRuntimePermission(String packageName, String name, int userId) {
5753        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5754    }
5755
5756    private void revokeRuntimePermission(String packageName, String name, int userId,
5757            boolean overridePolicy) {
5758        if (!sUserManager.exists(userId)) {
5759            Log.e(TAG, "No such user:" + userId);
5760            return;
5761        }
5762
5763        mContext.enforceCallingOrSelfPermission(
5764                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5765                "revokeRuntimePermission");
5766
5767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5768                true /* requireFullPermission */, true /* checkShell */,
5769                "revokeRuntimePermission");
5770
5771        final int appId;
5772
5773        synchronized (mPackages) {
5774            final PackageParser.Package pkg = mPackages.get(packageName);
5775            if (pkg == null) {
5776                throw new IllegalArgumentException("Unknown package: " + packageName);
5777            }
5778            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5779            if (ps == null
5780                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5781                throw new IllegalArgumentException("Unknown package: " + packageName);
5782            }
5783            final BasePermission bp = mSettings.mPermissions.get(name);
5784            if (bp == null) {
5785                throw new IllegalArgumentException("Unknown permission: " + name);
5786            }
5787
5788            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5789
5790            // If a permission review is required for legacy apps we represent
5791            // their permissions as always granted runtime ones since we need
5792            // to keep the review required permission flag per user while an
5793            // install permission's state is shared across all users.
5794            if (mPermissionReviewRequired
5795                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5796                    && bp.isRuntime()) {
5797                return;
5798            }
5799
5800            final PermissionsState permissionsState = ps.getPermissionsState();
5801
5802            final int flags = permissionsState.getPermissionFlags(name, userId);
5803            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5804                throw new SecurityException("Cannot revoke system fixed permission "
5805                        + name + " for package " + packageName);
5806            }
5807            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5808                throw new SecurityException("Cannot revoke policy fixed permission "
5809                        + name + " for package " + packageName);
5810            }
5811
5812            if (bp.isDevelopment()) {
5813                // Development permissions must be handled specially, since they are not
5814                // normal runtime permissions.  For now they apply to all users.
5815                if (permissionsState.revokeInstallPermission(bp) !=
5816                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5817                    scheduleWriteSettingsLocked();
5818                }
5819                return;
5820            }
5821
5822            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5823                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5824                return;
5825            }
5826
5827            if (bp.isRuntime()) {
5828                logPermissionRevoked(mContext, name, packageName);
5829            }
5830
5831            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5832
5833            // Critical, after this call app should never have the permission.
5834            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5835
5836            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5837        }
5838
5839        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5840    }
5841
5842    /**
5843     * Get the first event id for the permission.
5844     *
5845     * <p>There are four events for each permission: <ul>
5846     *     <li>Request permission: first id + 0</li>
5847     *     <li>Grant permission: first id + 1</li>
5848     *     <li>Request for permission denied: first id + 2</li>
5849     *     <li>Revoke permission: first id + 3</li>
5850     * </ul></p>
5851     *
5852     * @param name name of the permission
5853     *
5854     * @return The first event id for the permission
5855     */
5856    private static int getBaseEventId(@NonNull String name) {
5857        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5858
5859        if (eventIdIndex == -1) {
5860            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5861                    || Build.IS_USER) {
5862                Log.i(TAG, "Unknown permission " + name);
5863
5864                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5865            } else {
5866                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5867                //
5868                // Also update
5869                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5870                // - metrics_constants.proto
5871                throw new IllegalStateException("Unknown permission " + name);
5872            }
5873        }
5874
5875        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5876    }
5877
5878    /**
5879     * Log that a permission was revoked.
5880     *
5881     * @param context Context of the caller
5882     * @param name name of the permission
5883     * @param packageName package permission if for
5884     */
5885    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5886            @NonNull String packageName) {
5887        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5888    }
5889
5890    /**
5891     * Log that a permission request was granted.
5892     *
5893     * @param context Context of the caller
5894     * @param name name of the permission
5895     * @param packageName package permission if for
5896     */
5897    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5898            @NonNull String packageName) {
5899        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5900    }
5901
5902    @Override
5903    public void resetRuntimePermissions() {
5904        mContext.enforceCallingOrSelfPermission(
5905                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5906                "revokeRuntimePermission");
5907
5908        int callingUid = Binder.getCallingUid();
5909        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5910            mContext.enforceCallingOrSelfPermission(
5911                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5912                    "resetRuntimePermissions");
5913        }
5914
5915        synchronized (mPackages) {
5916            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5917            for (int userId : UserManagerService.getInstance().getUserIds()) {
5918                final int packageCount = mPackages.size();
5919                for (int i = 0; i < packageCount; i++) {
5920                    PackageParser.Package pkg = mPackages.valueAt(i);
5921                    if (!(pkg.mExtras instanceof PackageSetting)) {
5922                        continue;
5923                    }
5924                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5925                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5926                }
5927            }
5928        }
5929    }
5930
5931    @Override
5932    public int getPermissionFlags(String name, String packageName, int userId) {
5933        if (!sUserManager.exists(userId)) {
5934            return 0;
5935        }
5936
5937        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5938
5939        final int callingUid = Binder.getCallingUid();
5940        enforceCrossUserPermission(callingUid, userId,
5941                true /* requireFullPermission */, false /* checkShell */,
5942                "getPermissionFlags");
5943
5944        synchronized (mPackages) {
5945            final PackageParser.Package pkg = mPackages.get(packageName);
5946            if (pkg == null) {
5947                return 0;
5948            }
5949            final BasePermission bp = mSettings.mPermissions.get(name);
5950            if (bp == null) {
5951                return 0;
5952            }
5953            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5954            if (ps == null
5955                    || filterAppAccessLPr(ps, callingUid, userId)) {
5956                return 0;
5957            }
5958            PermissionsState permissionsState = ps.getPermissionsState();
5959            return permissionsState.getPermissionFlags(name, userId);
5960        }
5961    }
5962
5963    @Override
5964    public void updatePermissionFlags(String name, String packageName, int flagMask,
5965            int flagValues, int userId) {
5966        if (!sUserManager.exists(userId)) {
5967            return;
5968        }
5969
5970        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5971
5972        final int callingUid = Binder.getCallingUid();
5973        enforceCrossUserPermission(callingUid, userId,
5974                true /* requireFullPermission */, true /* checkShell */,
5975                "updatePermissionFlags");
5976
5977        // Only the system can change these flags and nothing else.
5978        if (getCallingUid() != Process.SYSTEM_UID) {
5979            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5980            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5981            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5982            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5983            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5984        }
5985
5986        synchronized (mPackages) {
5987            final PackageParser.Package pkg = mPackages.get(packageName);
5988            if (pkg == null) {
5989                throw new IllegalArgumentException("Unknown package: " + packageName);
5990            }
5991            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5992            if (ps == null
5993                    || filterAppAccessLPr(ps, callingUid, userId)) {
5994                throw new IllegalArgumentException("Unknown package: " + packageName);
5995            }
5996
5997            final BasePermission bp = mSettings.mPermissions.get(name);
5998            if (bp == null) {
5999                throw new IllegalArgumentException("Unknown permission: " + name);
6000            }
6001
6002            PermissionsState permissionsState = ps.getPermissionsState();
6003
6004            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6005
6006            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6007                // Install and runtime permissions are stored in different places,
6008                // so figure out what permission changed and persist the change.
6009                if (permissionsState.getInstallPermissionState(name) != null) {
6010                    scheduleWriteSettingsLocked();
6011                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6012                        || hadState) {
6013                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6014                }
6015            }
6016        }
6017    }
6018
6019    /**
6020     * Update the permission flags for all packages and runtime permissions of a user in order
6021     * to allow device or profile owner to remove POLICY_FIXED.
6022     */
6023    @Override
6024    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6025        if (!sUserManager.exists(userId)) {
6026            return;
6027        }
6028
6029        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6030
6031        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6032                true /* requireFullPermission */, true /* checkShell */,
6033                "updatePermissionFlagsForAllApps");
6034
6035        // Only the system can change system fixed flags.
6036        if (getCallingUid() != Process.SYSTEM_UID) {
6037            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6038            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6039        }
6040
6041        synchronized (mPackages) {
6042            boolean changed = false;
6043            final int packageCount = mPackages.size();
6044            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6045                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6046                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6047                if (ps == null) {
6048                    continue;
6049                }
6050                PermissionsState permissionsState = ps.getPermissionsState();
6051                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6052                        userId, flagMask, flagValues);
6053            }
6054            if (changed) {
6055                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6056            }
6057        }
6058    }
6059
6060    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6061        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6062                != PackageManager.PERMISSION_GRANTED
6063            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6064                != PackageManager.PERMISSION_GRANTED) {
6065            throw new SecurityException(message + " requires "
6066                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6067                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6068        }
6069    }
6070
6071    @Override
6072    public boolean shouldShowRequestPermissionRationale(String permissionName,
6073            String packageName, int userId) {
6074        if (UserHandle.getCallingUserId() != userId) {
6075            mContext.enforceCallingPermission(
6076                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6077                    "canShowRequestPermissionRationale for user " + userId);
6078        }
6079
6080        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6081        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6082            return false;
6083        }
6084
6085        if (checkPermission(permissionName, packageName, userId)
6086                == PackageManager.PERMISSION_GRANTED) {
6087            return false;
6088        }
6089
6090        final int flags;
6091
6092        final long identity = Binder.clearCallingIdentity();
6093        try {
6094            flags = getPermissionFlags(permissionName,
6095                    packageName, userId);
6096        } finally {
6097            Binder.restoreCallingIdentity(identity);
6098        }
6099
6100        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6101                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6102                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6103
6104        if ((flags & fixedFlags) != 0) {
6105            return false;
6106        }
6107
6108        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6109    }
6110
6111    @Override
6112    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6113        mContext.enforceCallingOrSelfPermission(
6114                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6115                "addOnPermissionsChangeListener");
6116
6117        synchronized (mPackages) {
6118            mOnPermissionChangeListeners.addListenerLocked(listener);
6119        }
6120    }
6121
6122    @Override
6123    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6124        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6125            throw new SecurityException("Instant applications don't have access to this method");
6126        }
6127        synchronized (mPackages) {
6128            mOnPermissionChangeListeners.removeListenerLocked(listener);
6129        }
6130    }
6131
6132    @Override
6133    public boolean isProtectedBroadcast(String actionName) {
6134        // allow instant applications
6135        synchronized (mProtectedBroadcasts) {
6136            if (mProtectedBroadcasts.contains(actionName)) {
6137                return true;
6138            } else if (actionName != null) {
6139                // TODO: remove these terrible hacks
6140                if (actionName.startsWith("android.net.netmon.lingerExpired")
6141                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6142                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6143                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6144                    return true;
6145                }
6146            }
6147        }
6148        return false;
6149    }
6150
6151    @Override
6152    public int checkSignatures(String pkg1, String pkg2) {
6153        synchronized (mPackages) {
6154            final PackageParser.Package p1 = mPackages.get(pkg1);
6155            final PackageParser.Package p2 = mPackages.get(pkg2);
6156            if (p1 == null || p1.mExtras == null
6157                    || p2 == null || p2.mExtras == null) {
6158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6159            }
6160            final int callingUid = Binder.getCallingUid();
6161            final int callingUserId = UserHandle.getUserId(callingUid);
6162            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6163            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6164            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6165                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6166                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6167            }
6168            return compareSignatures(p1.mSignatures, p2.mSignatures);
6169        }
6170    }
6171
6172    @Override
6173    public int checkUidSignatures(int uid1, int uid2) {
6174        final int callingUid = Binder.getCallingUid();
6175        final int callingUserId = UserHandle.getUserId(callingUid);
6176        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6177        // Map to base uids.
6178        uid1 = UserHandle.getAppId(uid1);
6179        uid2 = UserHandle.getAppId(uid2);
6180        // reader
6181        synchronized (mPackages) {
6182            Signature[] s1;
6183            Signature[] s2;
6184            Object obj = mSettings.getUserIdLPr(uid1);
6185            if (obj != null) {
6186                if (obj instanceof SharedUserSetting) {
6187                    if (isCallerInstantApp) {
6188                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6189                    }
6190                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6191                } else if (obj instanceof PackageSetting) {
6192                    final PackageSetting ps = (PackageSetting) obj;
6193                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6194                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6195                    }
6196                    s1 = ps.signatures.mSignatures;
6197                } else {
6198                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6199                }
6200            } else {
6201                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6202            }
6203            obj = mSettings.getUserIdLPr(uid2);
6204            if (obj != null) {
6205                if (obj instanceof SharedUserSetting) {
6206                    if (isCallerInstantApp) {
6207                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6208                    }
6209                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6210                } else if (obj instanceof PackageSetting) {
6211                    final PackageSetting ps = (PackageSetting) obj;
6212                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6213                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214                    }
6215                    s2 = ps.signatures.mSignatures;
6216                } else {
6217                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6218                }
6219            } else {
6220                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6221            }
6222            return compareSignatures(s1, s2);
6223        }
6224    }
6225
6226    /**
6227     * This method should typically only be used when granting or revoking
6228     * permissions, since the app may immediately restart after this call.
6229     * <p>
6230     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6231     * guard your work against the app being relaunched.
6232     */
6233    private void killUid(int appId, int userId, String reason) {
6234        final long identity = Binder.clearCallingIdentity();
6235        try {
6236            IActivityManager am = ActivityManager.getService();
6237            if (am != null) {
6238                try {
6239                    am.killUid(appId, userId, reason);
6240                } catch (RemoteException e) {
6241                    /* ignore - same process */
6242                }
6243            }
6244        } finally {
6245            Binder.restoreCallingIdentity(identity);
6246        }
6247    }
6248
6249    /**
6250     * Compares two sets of signatures. Returns:
6251     * <br />
6252     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6253     * <br />
6254     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6255     * <br />
6256     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6257     * <br />
6258     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6259     * <br />
6260     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6261     */
6262    static int compareSignatures(Signature[] s1, Signature[] s2) {
6263        if (s1 == null) {
6264            return s2 == null
6265                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6266                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6267        }
6268
6269        if (s2 == null) {
6270            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6271        }
6272
6273        if (s1.length != s2.length) {
6274            return PackageManager.SIGNATURE_NO_MATCH;
6275        }
6276
6277        // Since both signature sets are of size 1, we can compare without HashSets.
6278        if (s1.length == 1) {
6279            return s1[0].equals(s2[0]) ?
6280                    PackageManager.SIGNATURE_MATCH :
6281                    PackageManager.SIGNATURE_NO_MATCH;
6282        }
6283
6284        ArraySet<Signature> set1 = new ArraySet<Signature>();
6285        for (Signature sig : s1) {
6286            set1.add(sig);
6287        }
6288        ArraySet<Signature> set2 = new ArraySet<Signature>();
6289        for (Signature sig : s2) {
6290            set2.add(sig);
6291        }
6292        // Make sure s2 contains all signatures in s1.
6293        if (set1.equals(set2)) {
6294            return PackageManager.SIGNATURE_MATCH;
6295        }
6296        return PackageManager.SIGNATURE_NO_MATCH;
6297    }
6298
6299    /**
6300     * If the database version for this type of package (internal storage or
6301     * external storage) is less than the version where package signatures
6302     * were updated, return true.
6303     */
6304    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6305        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6306        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6307    }
6308
6309    /**
6310     * Used for backward compatibility to make sure any packages with
6311     * certificate chains get upgraded to the new style. {@code existingSigs}
6312     * will be in the old format (since they were stored on disk from before the
6313     * system upgrade) and {@code scannedSigs} will be in the newer format.
6314     */
6315    private int compareSignaturesCompat(PackageSignatures existingSigs,
6316            PackageParser.Package scannedPkg) {
6317        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6318            return PackageManager.SIGNATURE_NO_MATCH;
6319        }
6320
6321        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6322        for (Signature sig : existingSigs.mSignatures) {
6323            existingSet.add(sig);
6324        }
6325        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6326        for (Signature sig : scannedPkg.mSignatures) {
6327            try {
6328                Signature[] chainSignatures = sig.getChainSignatures();
6329                for (Signature chainSig : chainSignatures) {
6330                    scannedCompatSet.add(chainSig);
6331                }
6332            } catch (CertificateEncodingException e) {
6333                scannedCompatSet.add(sig);
6334            }
6335        }
6336        /*
6337         * Make sure the expanded scanned set contains all signatures in the
6338         * existing one.
6339         */
6340        if (scannedCompatSet.equals(existingSet)) {
6341            // Migrate the old signatures to the new scheme.
6342            existingSigs.assignSignatures(scannedPkg.mSignatures);
6343            // The new KeySets will be re-added later in the scanning process.
6344            synchronized (mPackages) {
6345                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6346            }
6347            return PackageManager.SIGNATURE_MATCH;
6348        }
6349        return PackageManager.SIGNATURE_NO_MATCH;
6350    }
6351
6352    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6353        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6354        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6355    }
6356
6357    private int compareSignaturesRecover(PackageSignatures existingSigs,
6358            PackageParser.Package scannedPkg) {
6359        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6360            return PackageManager.SIGNATURE_NO_MATCH;
6361        }
6362
6363        String msg = null;
6364        try {
6365            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6366                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6367                        + scannedPkg.packageName);
6368                return PackageManager.SIGNATURE_MATCH;
6369            }
6370        } catch (CertificateException e) {
6371            msg = e.getMessage();
6372        }
6373
6374        logCriticalInfo(Log.INFO,
6375                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6376        return PackageManager.SIGNATURE_NO_MATCH;
6377    }
6378
6379    @Override
6380    public List<String> getAllPackages() {
6381        final int callingUid = Binder.getCallingUid();
6382        final int callingUserId = UserHandle.getUserId(callingUid);
6383        synchronized (mPackages) {
6384            if (canViewInstantApps(callingUid, callingUserId)) {
6385                return new ArrayList<String>(mPackages.keySet());
6386            }
6387            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6388            final List<String> result = new ArrayList<>();
6389            if (instantAppPkgName != null) {
6390                // caller is an instant application; filter unexposed applications
6391                for (PackageParser.Package pkg : mPackages.values()) {
6392                    if (!pkg.visibleToInstantApps) {
6393                        continue;
6394                    }
6395                    result.add(pkg.packageName);
6396                }
6397            } else {
6398                // caller is a normal application; filter instant applications
6399                for (PackageParser.Package pkg : mPackages.values()) {
6400                    final PackageSetting ps =
6401                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6402                    if (ps != null
6403                            && ps.getInstantApp(callingUserId)
6404                            && !mInstantAppRegistry.isInstantAccessGranted(
6405                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6406                        continue;
6407                    }
6408                    result.add(pkg.packageName);
6409                }
6410            }
6411            return result;
6412        }
6413    }
6414
6415    @Override
6416    public String[] getPackagesForUid(int uid) {
6417        final int callingUid = Binder.getCallingUid();
6418        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6419        final int userId = UserHandle.getUserId(uid);
6420        uid = UserHandle.getAppId(uid);
6421        // reader
6422        synchronized (mPackages) {
6423            Object obj = mSettings.getUserIdLPr(uid);
6424            if (obj instanceof SharedUserSetting) {
6425                if (isCallerInstantApp) {
6426                    return null;
6427                }
6428                final SharedUserSetting sus = (SharedUserSetting) obj;
6429                final int N = sus.packages.size();
6430                String[] res = new String[N];
6431                final Iterator<PackageSetting> it = sus.packages.iterator();
6432                int i = 0;
6433                while (it.hasNext()) {
6434                    PackageSetting ps = it.next();
6435                    if (ps.getInstalled(userId)) {
6436                        res[i++] = ps.name;
6437                    } else {
6438                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6439                    }
6440                }
6441                return res;
6442            } else if (obj instanceof PackageSetting) {
6443                final PackageSetting ps = (PackageSetting) obj;
6444                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6445                    return new String[]{ps.name};
6446                }
6447            }
6448        }
6449        return null;
6450    }
6451
6452    @Override
6453    public String getNameForUid(int uid) {
6454        final int callingUid = Binder.getCallingUid();
6455        if (getInstantAppPackageName(callingUid) != null) {
6456            return null;
6457        }
6458        synchronized (mPackages) {
6459            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6460            if (obj instanceof SharedUserSetting) {
6461                final SharedUserSetting sus = (SharedUserSetting) obj;
6462                return sus.name + ":" + sus.userId;
6463            } else if (obj instanceof PackageSetting) {
6464                final PackageSetting ps = (PackageSetting) obj;
6465                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6466                    return null;
6467                }
6468                return ps.name;
6469            }
6470            return null;
6471        }
6472    }
6473
6474    @Override
6475    public String[] getNamesForUids(int[] uids) {
6476        if (uids == null || uids.length == 0) {
6477            return null;
6478        }
6479        final int callingUid = Binder.getCallingUid();
6480        if (getInstantAppPackageName(callingUid) != null) {
6481            return null;
6482        }
6483        final String[] names = new String[uids.length];
6484        synchronized (mPackages) {
6485            for (int i = uids.length - 1; i >= 0; i--) {
6486                final int uid = uids[i];
6487                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6488                if (obj instanceof SharedUserSetting) {
6489                    final SharedUserSetting sus = (SharedUserSetting) obj;
6490                    names[i] = "shared:" + sus.name;
6491                } else if (obj instanceof PackageSetting) {
6492                    final PackageSetting ps = (PackageSetting) obj;
6493                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6494                        names[i] = null;
6495                    } else {
6496                        names[i] = ps.name;
6497                    }
6498                } else {
6499                    names[i] = null;
6500                }
6501            }
6502        }
6503        return names;
6504    }
6505
6506    @Override
6507    public int getUidForSharedUser(String sharedUserName) {
6508        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6509            return -1;
6510        }
6511        if (sharedUserName == null) {
6512            return -1;
6513        }
6514        // reader
6515        synchronized (mPackages) {
6516            SharedUserSetting suid;
6517            try {
6518                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6519                if (suid != null) {
6520                    return suid.userId;
6521                }
6522            } catch (PackageManagerException ignore) {
6523                // can't happen, but, still need to catch it
6524            }
6525            return -1;
6526        }
6527    }
6528
6529    @Override
6530    public int getFlagsForUid(int uid) {
6531        final int callingUid = Binder.getCallingUid();
6532        if (getInstantAppPackageName(callingUid) != null) {
6533            return 0;
6534        }
6535        synchronized (mPackages) {
6536            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6537            if (obj instanceof SharedUserSetting) {
6538                final SharedUserSetting sus = (SharedUserSetting) obj;
6539                return sus.pkgFlags;
6540            } else if (obj instanceof PackageSetting) {
6541                final PackageSetting ps = (PackageSetting) obj;
6542                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6543                    return 0;
6544                }
6545                return ps.pkgFlags;
6546            }
6547        }
6548        return 0;
6549    }
6550
6551    @Override
6552    public int getPrivateFlagsForUid(int uid) {
6553        final int callingUid = Binder.getCallingUid();
6554        if (getInstantAppPackageName(callingUid) != null) {
6555            return 0;
6556        }
6557        synchronized (mPackages) {
6558            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6559            if (obj instanceof SharedUserSetting) {
6560                final SharedUserSetting sus = (SharedUserSetting) obj;
6561                return sus.pkgPrivateFlags;
6562            } else if (obj instanceof PackageSetting) {
6563                final PackageSetting ps = (PackageSetting) obj;
6564                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6565                    return 0;
6566                }
6567                return ps.pkgPrivateFlags;
6568            }
6569        }
6570        return 0;
6571    }
6572
6573    @Override
6574    public boolean isUidPrivileged(int uid) {
6575        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6576            return false;
6577        }
6578        uid = UserHandle.getAppId(uid);
6579        // reader
6580        synchronized (mPackages) {
6581            Object obj = mSettings.getUserIdLPr(uid);
6582            if (obj instanceof SharedUserSetting) {
6583                final SharedUserSetting sus = (SharedUserSetting) obj;
6584                final Iterator<PackageSetting> it = sus.packages.iterator();
6585                while (it.hasNext()) {
6586                    if (it.next().isPrivileged()) {
6587                        return true;
6588                    }
6589                }
6590            } else if (obj instanceof PackageSetting) {
6591                final PackageSetting ps = (PackageSetting) obj;
6592                return ps.isPrivileged();
6593            }
6594        }
6595        return false;
6596    }
6597
6598    @Override
6599    public String[] getAppOpPermissionPackages(String permissionName) {
6600        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6601            return null;
6602        }
6603        synchronized (mPackages) {
6604            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6605            if (pkgs == null) {
6606                return null;
6607            }
6608            return pkgs.toArray(new String[pkgs.size()]);
6609        }
6610    }
6611
6612    @Override
6613    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6614            int flags, int userId) {
6615        return resolveIntentInternal(
6616                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6617    }
6618
6619    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6620            int flags, int userId, boolean resolveForStart) {
6621        try {
6622            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6623
6624            if (!sUserManager.exists(userId)) return null;
6625            final int callingUid = Binder.getCallingUid();
6626            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6627            enforceCrossUserPermission(callingUid, userId,
6628                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6629
6630            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6631            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6632                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6633            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6634
6635            final ResolveInfo bestChoice =
6636                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6637            return bestChoice;
6638        } finally {
6639            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6640        }
6641    }
6642
6643    @Override
6644    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6645        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6646            throw new SecurityException(
6647                    "findPersistentPreferredActivity can only be run by the system");
6648        }
6649        if (!sUserManager.exists(userId)) {
6650            return null;
6651        }
6652        final int callingUid = Binder.getCallingUid();
6653        intent = updateIntentForResolve(intent);
6654        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6655        final int flags = updateFlagsForResolve(
6656                0, userId, intent, callingUid, false /*includeInstantApps*/);
6657        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6658                userId);
6659        synchronized (mPackages) {
6660            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6661                    userId);
6662        }
6663    }
6664
6665    @Override
6666    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6667            IntentFilter filter, int match, ComponentName activity) {
6668        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6669            return;
6670        }
6671        final int userId = UserHandle.getCallingUserId();
6672        if (DEBUG_PREFERRED) {
6673            Log.v(TAG, "setLastChosenActivity intent=" + intent
6674                + " resolvedType=" + resolvedType
6675                + " flags=" + flags
6676                + " filter=" + filter
6677                + " match=" + match
6678                + " activity=" + activity);
6679            filter.dump(new PrintStreamPrinter(System.out), "    ");
6680        }
6681        intent.setComponent(null);
6682        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6683                userId);
6684        // Find any earlier preferred or last chosen entries and nuke them
6685        findPreferredActivity(intent, resolvedType,
6686                flags, query, 0, false, true, false, userId);
6687        // Add the new activity as the last chosen for this filter
6688        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6689                "Setting last chosen");
6690    }
6691
6692    @Override
6693    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6694        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6695            return null;
6696        }
6697        final int userId = UserHandle.getCallingUserId();
6698        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6699        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6700                userId);
6701        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6702                false, false, false, userId);
6703    }
6704
6705    /**
6706     * Returns whether or not instant apps have been disabled remotely.
6707     */
6708    private boolean isEphemeralDisabled() {
6709        return mEphemeralAppsDisabled;
6710    }
6711
6712    private boolean isInstantAppAllowed(
6713            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6714            boolean skipPackageCheck) {
6715        if (mInstantAppResolverConnection == null) {
6716            return false;
6717        }
6718        if (mInstantAppInstallerActivity == null) {
6719            return false;
6720        }
6721        if (intent.getComponent() != null) {
6722            return false;
6723        }
6724        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6725            return false;
6726        }
6727        if (!skipPackageCheck && intent.getPackage() != null) {
6728            return false;
6729        }
6730        final boolean isWebUri = hasWebURI(intent);
6731        if (!isWebUri || intent.getData().getHost() == null) {
6732            return false;
6733        }
6734        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6735        // Or if there's already an ephemeral app installed that handles the action
6736        synchronized (mPackages) {
6737            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6738            for (int n = 0; n < count; n++) {
6739                final ResolveInfo info = resolvedActivities.get(n);
6740                final String packageName = info.activityInfo.packageName;
6741                final PackageSetting ps = mSettings.mPackages.get(packageName);
6742                if (ps != null) {
6743                    // only check domain verification status if the app is not a browser
6744                    if (!info.handleAllWebDataURI) {
6745                        // Try to get the status from User settings first
6746                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6747                        final int status = (int) (packedStatus >> 32);
6748                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6749                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6750                            if (DEBUG_EPHEMERAL) {
6751                                Slog.v(TAG, "DENY instant app;"
6752                                    + " pkg: " + packageName + ", status: " + status);
6753                            }
6754                            return false;
6755                        }
6756                    }
6757                    if (ps.getInstantApp(userId)) {
6758                        if (DEBUG_EPHEMERAL) {
6759                            Slog.v(TAG, "DENY instant app installed;"
6760                                    + " pkg: " + packageName);
6761                        }
6762                        return false;
6763                    }
6764                }
6765            }
6766        }
6767        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6768        return true;
6769    }
6770
6771    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6772            Intent origIntent, String resolvedType, String callingPackage,
6773            Bundle verificationBundle, int userId) {
6774        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6775                new InstantAppRequest(responseObj, origIntent, resolvedType,
6776                        callingPackage, userId, verificationBundle));
6777        mHandler.sendMessage(msg);
6778    }
6779
6780    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6781            int flags, List<ResolveInfo> query, int userId) {
6782        if (query != null) {
6783            final int N = query.size();
6784            if (N == 1) {
6785                return query.get(0);
6786            } else if (N > 1) {
6787                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6788                // If there is more than one activity with the same priority,
6789                // then let the user decide between them.
6790                ResolveInfo r0 = query.get(0);
6791                ResolveInfo r1 = query.get(1);
6792                if (DEBUG_INTENT_MATCHING || debug) {
6793                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6794                            + r1.activityInfo.name + "=" + r1.priority);
6795                }
6796                // If the first activity has a higher priority, or a different
6797                // default, then it is always desirable to pick it.
6798                if (r0.priority != r1.priority
6799                        || r0.preferredOrder != r1.preferredOrder
6800                        || r0.isDefault != r1.isDefault) {
6801                    return query.get(0);
6802                }
6803                // If we have saved a preference for a preferred activity for
6804                // this Intent, use that.
6805                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6806                        flags, query, r0.priority, true, false, debug, userId);
6807                if (ri != null) {
6808                    return ri;
6809                }
6810                // If we have an ephemeral app, use it
6811                for (int i = 0; i < N; i++) {
6812                    ri = query.get(i);
6813                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6814                        final String packageName = ri.activityInfo.packageName;
6815                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6816                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6817                        final int status = (int)(packedStatus >> 32);
6818                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6819                            return ri;
6820                        }
6821                    }
6822                }
6823                ri = new ResolveInfo(mResolveInfo);
6824                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6825                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6826                // If all of the options come from the same package, show the application's
6827                // label and icon instead of the generic resolver's.
6828                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6829                // and then throw away the ResolveInfo itself, meaning that the caller loses
6830                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6831                // a fallback for this case; we only set the target package's resources on
6832                // the ResolveInfo, not the ActivityInfo.
6833                final String intentPackage = intent.getPackage();
6834                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6835                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6836                    ri.resolvePackageName = intentPackage;
6837                    if (userNeedsBadging(userId)) {
6838                        ri.noResourceId = true;
6839                    } else {
6840                        ri.icon = appi.icon;
6841                    }
6842                    ri.iconResourceId = appi.icon;
6843                    ri.labelRes = appi.labelRes;
6844                }
6845                ri.activityInfo.applicationInfo = new ApplicationInfo(
6846                        ri.activityInfo.applicationInfo);
6847                if (userId != 0) {
6848                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6849                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6850                }
6851                // Make sure that the resolver is displayable in car mode
6852                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6853                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6854                return ri;
6855            }
6856        }
6857        return null;
6858    }
6859
6860    /**
6861     * Return true if the given list is not empty and all of its contents have
6862     * an activityInfo with the given package name.
6863     */
6864    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6865        if (ArrayUtils.isEmpty(list)) {
6866            return false;
6867        }
6868        for (int i = 0, N = list.size(); i < N; i++) {
6869            final ResolveInfo ri = list.get(i);
6870            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6871            if (ai == null || !packageName.equals(ai.packageName)) {
6872                return false;
6873            }
6874        }
6875        return true;
6876    }
6877
6878    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6879            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6880        final int N = query.size();
6881        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6882                .get(userId);
6883        // Get the list of persistent preferred activities that handle the intent
6884        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6885        List<PersistentPreferredActivity> pprefs = ppir != null
6886                ? ppir.queryIntent(intent, resolvedType,
6887                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6888                        userId)
6889                : null;
6890        if (pprefs != null && pprefs.size() > 0) {
6891            final int M = pprefs.size();
6892            for (int i=0; i<M; i++) {
6893                final PersistentPreferredActivity ppa = pprefs.get(i);
6894                if (DEBUG_PREFERRED || debug) {
6895                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6896                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6897                            + "\n  component=" + ppa.mComponent);
6898                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6899                }
6900                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6901                        flags | MATCH_DISABLED_COMPONENTS, userId);
6902                if (DEBUG_PREFERRED || debug) {
6903                    Slog.v(TAG, "Found persistent preferred activity:");
6904                    if (ai != null) {
6905                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6906                    } else {
6907                        Slog.v(TAG, "  null");
6908                    }
6909                }
6910                if (ai == null) {
6911                    // This previously registered persistent preferred activity
6912                    // component is no longer known. Ignore it and do NOT remove it.
6913                    continue;
6914                }
6915                for (int j=0; j<N; j++) {
6916                    final ResolveInfo ri = query.get(j);
6917                    if (!ri.activityInfo.applicationInfo.packageName
6918                            .equals(ai.applicationInfo.packageName)) {
6919                        continue;
6920                    }
6921                    if (!ri.activityInfo.name.equals(ai.name)) {
6922                        continue;
6923                    }
6924                    //  Found a persistent preference that can handle the intent.
6925                    if (DEBUG_PREFERRED || debug) {
6926                        Slog.v(TAG, "Returning persistent preferred activity: " +
6927                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6928                    }
6929                    return ri;
6930                }
6931            }
6932        }
6933        return null;
6934    }
6935
6936    // TODO: handle preferred activities missing while user has amnesia
6937    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6938            List<ResolveInfo> query, int priority, boolean always,
6939            boolean removeMatches, boolean debug, int userId) {
6940        if (!sUserManager.exists(userId)) return null;
6941        final int callingUid = Binder.getCallingUid();
6942        flags = updateFlagsForResolve(
6943                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6944        intent = updateIntentForResolve(intent);
6945        // writer
6946        synchronized (mPackages) {
6947            // Try to find a matching persistent preferred activity.
6948            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6949                    debug, userId);
6950
6951            // If a persistent preferred activity matched, use it.
6952            if (pri != null) {
6953                return pri;
6954            }
6955
6956            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6957            // Get the list of preferred activities that handle the intent
6958            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6959            List<PreferredActivity> prefs = pir != null
6960                    ? pir.queryIntent(intent, resolvedType,
6961                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6962                            userId)
6963                    : null;
6964            if (prefs != null && prefs.size() > 0) {
6965                boolean changed = false;
6966                try {
6967                    // First figure out how good the original match set is.
6968                    // We will only allow preferred activities that came
6969                    // from the same match quality.
6970                    int match = 0;
6971
6972                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6973
6974                    final int N = query.size();
6975                    for (int j=0; j<N; j++) {
6976                        final ResolveInfo ri = query.get(j);
6977                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6978                                + ": 0x" + Integer.toHexString(match));
6979                        if (ri.match > match) {
6980                            match = ri.match;
6981                        }
6982                    }
6983
6984                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6985                            + Integer.toHexString(match));
6986
6987                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6988                    final int M = prefs.size();
6989                    for (int i=0; i<M; i++) {
6990                        final PreferredActivity pa = prefs.get(i);
6991                        if (DEBUG_PREFERRED || debug) {
6992                            Slog.v(TAG, "Checking PreferredActivity ds="
6993                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6994                                    + "\n  component=" + pa.mPref.mComponent);
6995                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6996                        }
6997                        if (pa.mPref.mMatch != match) {
6998                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6999                                    + Integer.toHexString(pa.mPref.mMatch));
7000                            continue;
7001                        }
7002                        // If it's not an "always" type preferred activity and that's what we're
7003                        // looking for, skip it.
7004                        if (always && !pa.mPref.mAlways) {
7005                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7006                            continue;
7007                        }
7008                        final ActivityInfo ai = getActivityInfo(
7009                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7010                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7011                                userId);
7012                        if (DEBUG_PREFERRED || debug) {
7013                            Slog.v(TAG, "Found preferred activity:");
7014                            if (ai != null) {
7015                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7016                            } else {
7017                                Slog.v(TAG, "  null");
7018                            }
7019                        }
7020                        if (ai == null) {
7021                            // This previously registered preferred activity
7022                            // component is no longer known.  Most likely an update
7023                            // to the app was installed and in the new version this
7024                            // component no longer exists.  Clean it up by removing
7025                            // it from the preferred activities list, and skip it.
7026                            Slog.w(TAG, "Removing dangling preferred activity: "
7027                                    + pa.mPref.mComponent);
7028                            pir.removeFilter(pa);
7029                            changed = true;
7030                            continue;
7031                        }
7032                        for (int j=0; j<N; j++) {
7033                            final ResolveInfo ri = query.get(j);
7034                            if (!ri.activityInfo.applicationInfo.packageName
7035                                    .equals(ai.applicationInfo.packageName)) {
7036                                continue;
7037                            }
7038                            if (!ri.activityInfo.name.equals(ai.name)) {
7039                                continue;
7040                            }
7041
7042                            if (removeMatches) {
7043                                pir.removeFilter(pa);
7044                                changed = true;
7045                                if (DEBUG_PREFERRED) {
7046                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7047                                }
7048                                break;
7049                            }
7050
7051                            // Okay we found a previously set preferred or last chosen app.
7052                            // If the result set is different from when this
7053                            // was created, and is not a subset of the preferred set, we need to
7054                            // clear it and re-ask the user their preference, if we're looking for
7055                            // an "always" type entry.
7056                            if (always && !pa.mPref.sameSet(query)) {
7057                                if (pa.mPref.isSuperset(query)) {
7058                                    // some components of the set are no longer present in
7059                                    // the query, but the preferred activity can still be reused
7060                                    if (DEBUG_PREFERRED) {
7061                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7062                                                + " still valid as only non-preferred components"
7063                                                + " were removed for " + intent + " type "
7064                                                + resolvedType);
7065                                    }
7066                                    // remove obsolete components and re-add the up-to-date filter
7067                                    PreferredActivity freshPa = new PreferredActivity(pa,
7068                                            pa.mPref.mMatch,
7069                                            pa.mPref.discardObsoleteComponents(query),
7070                                            pa.mPref.mComponent,
7071                                            pa.mPref.mAlways);
7072                                    pir.removeFilter(pa);
7073                                    pir.addFilter(freshPa);
7074                                    changed = true;
7075                                } else {
7076                                    Slog.i(TAG,
7077                                            "Result set changed, dropping preferred activity for "
7078                                                    + intent + " type " + resolvedType);
7079                                    if (DEBUG_PREFERRED) {
7080                                        Slog.v(TAG, "Removing preferred activity since set changed "
7081                                                + pa.mPref.mComponent);
7082                                    }
7083                                    pir.removeFilter(pa);
7084                                    // Re-add the filter as a "last chosen" entry (!always)
7085                                    PreferredActivity lastChosen = new PreferredActivity(
7086                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7087                                    pir.addFilter(lastChosen);
7088                                    changed = true;
7089                                    return null;
7090                                }
7091                            }
7092
7093                            // Yay! Either the set matched or we're looking for the last chosen
7094                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7095                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7096                            return ri;
7097                        }
7098                    }
7099                } finally {
7100                    if (changed) {
7101                        if (DEBUG_PREFERRED) {
7102                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7103                        }
7104                        scheduleWritePackageRestrictionsLocked(userId);
7105                    }
7106                }
7107            }
7108        }
7109        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7110        return null;
7111    }
7112
7113    /*
7114     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7115     */
7116    @Override
7117    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7118            int targetUserId) {
7119        mContext.enforceCallingOrSelfPermission(
7120                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7121        List<CrossProfileIntentFilter> matches =
7122                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7123        if (matches != null) {
7124            int size = matches.size();
7125            for (int i = 0; i < size; i++) {
7126                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7127            }
7128        }
7129        if (hasWebURI(intent)) {
7130            // cross-profile app linking works only towards the parent.
7131            final int callingUid = Binder.getCallingUid();
7132            final UserInfo parent = getProfileParent(sourceUserId);
7133            synchronized(mPackages) {
7134                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7135                        false /*includeInstantApps*/);
7136                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7137                        intent, resolvedType, flags, sourceUserId, parent.id);
7138                return xpDomainInfo != null;
7139            }
7140        }
7141        return false;
7142    }
7143
7144    private UserInfo getProfileParent(int userId) {
7145        final long identity = Binder.clearCallingIdentity();
7146        try {
7147            return sUserManager.getProfileParent(userId);
7148        } finally {
7149            Binder.restoreCallingIdentity(identity);
7150        }
7151    }
7152
7153    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7154            String resolvedType, int userId) {
7155        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7156        if (resolver != null) {
7157            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7158        }
7159        return null;
7160    }
7161
7162    @Override
7163    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7164            String resolvedType, int flags, int userId) {
7165        try {
7166            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7167
7168            return new ParceledListSlice<>(
7169                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7170        } finally {
7171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7172        }
7173    }
7174
7175    /**
7176     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7177     * instant, returns {@code null}.
7178     */
7179    private String getInstantAppPackageName(int callingUid) {
7180        synchronized (mPackages) {
7181            // If the caller is an isolated app use the owner's uid for the lookup.
7182            if (Process.isIsolated(callingUid)) {
7183                callingUid = mIsolatedOwners.get(callingUid);
7184            }
7185            final int appId = UserHandle.getAppId(callingUid);
7186            final Object obj = mSettings.getUserIdLPr(appId);
7187            if (obj instanceof PackageSetting) {
7188                final PackageSetting ps = (PackageSetting) obj;
7189                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7190                return isInstantApp ? ps.pkg.packageName : null;
7191            }
7192        }
7193        return null;
7194    }
7195
7196    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7197            String resolvedType, int flags, int userId) {
7198        return queryIntentActivitiesInternal(
7199                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7200                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7201    }
7202
7203    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7204            String resolvedType, int flags, int filterCallingUid, int userId,
7205            boolean resolveForStart, boolean allowDynamicSplits) {
7206        if (!sUserManager.exists(userId)) return Collections.emptyList();
7207        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7209                false /* requireFullPermission */, false /* checkShell */,
7210                "query intent activities");
7211        final String pkgName = intent.getPackage();
7212        ComponentName comp = intent.getComponent();
7213        if (comp == null) {
7214            if (intent.getSelector() != null) {
7215                intent = intent.getSelector();
7216                comp = intent.getComponent();
7217            }
7218        }
7219
7220        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7221                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7222        if (comp != null) {
7223            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7224            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7225            if (ai != null) {
7226                // When specifying an explicit component, we prevent the activity from being
7227                // used when either 1) the calling package is normal and the activity is within
7228                // an ephemeral application or 2) the calling package is ephemeral and the
7229                // activity is not visible to ephemeral applications.
7230                final boolean matchInstantApp =
7231                        (flags & PackageManager.MATCH_INSTANT) != 0;
7232                final boolean matchVisibleToInstantAppOnly =
7233                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7234                final boolean matchExplicitlyVisibleOnly =
7235                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7236                final boolean isCallerInstantApp =
7237                        instantAppPkgName != null;
7238                final boolean isTargetSameInstantApp =
7239                        comp.getPackageName().equals(instantAppPkgName);
7240                final boolean isTargetInstantApp =
7241                        (ai.applicationInfo.privateFlags
7242                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7243                final boolean isTargetVisibleToInstantApp =
7244                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7245                final boolean isTargetExplicitlyVisibleToInstantApp =
7246                        isTargetVisibleToInstantApp
7247                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7248                final boolean isTargetHiddenFromInstantApp =
7249                        !isTargetVisibleToInstantApp
7250                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7251                final boolean blockResolution =
7252                        !isTargetSameInstantApp
7253                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7254                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7255                                        && isTargetHiddenFromInstantApp));
7256                if (!blockResolution) {
7257                    final ResolveInfo ri = new ResolveInfo();
7258                    ri.activityInfo = ai;
7259                    list.add(ri);
7260                }
7261            }
7262            return applyPostResolutionFilter(
7263                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7264        }
7265
7266        // reader
7267        boolean sortResult = false;
7268        boolean addEphemeral = false;
7269        List<ResolveInfo> result;
7270        final boolean ephemeralDisabled = isEphemeralDisabled();
7271        synchronized (mPackages) {
7272            if (pkgName == null) {
7273                List<CrossProfileIntentFilter> matchingFilters =
7274                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7275                // Check for results that need to skip the current profile.
7276                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7277                        resolvedType, flags, userId);
7278                if (xpResolveInfo != null) {
7279                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7280                    xpResult.add(xpResolveInfo);
7281                    return applyPostResolutionFilter(
7282                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7283                            allowDynamicSplits, filterCallingUid, userId);
7284                }
7285
7286                // Check for results in the current profile.
7287                result = filterIfNotSystemUser(mActivities.queryIntent(
7288                        intent, resolvedType, flags, userId), userId);
7289                addEphemeral = !ephemeralDisabled
7290                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7291                // Check for cross profile results.
7292                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7293                xpResolveInfo = queryCrossProfileIntents(
7294                        matchingFilters, intent, resolvedType, flags, userId,
7295                        hasNonNegativePriorityResult);
7296                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7297                    boolean isVisibleToUser = filterIfNotSystemUser(
7298                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7299                    if (isVisibleToUser) {
7300                        result.add(xpResolveInfo);
7301                        sortResult = true;
7302                    }
7303                }
7304                if (hasWebURI(intent)) {
7305                    CrossProfileDomainInfo xpDomainInfo = null;
7306                    final UserInfo parent = getProfileParent(userId);
7307                    if (parent != null) {
7308                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7309                                flags, userId, parent.id);
7310                    }
7311                    if (xpDomainInfo != null) {
7312                        if (xpResolveInfo != null) {
7313                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7314                            // in the result.
7315                            result.remove(xpResolveInfo);
7316                        }
7317                        if (result.size() == 0 && !addEphemeral) {
7318                            // No result in current profile, but found candidate in parent user.
7319                            // And we are not going to add emphemeral app, so we can return the
7320                            // result straight away.
7321                            result.add(xpDomainInfo.resolveInfo);
7322                            return applyPostResolutionFilter(result, instantAppPkgName,
7323                                    allowDynamicSplits, filterCallingUid, userId);
7324                        }
7325                    } else if (result.size() <= 1 && !addEphemeral) {
7326                        // No result in parent user and <= 1 result in current profile, and we
7327                        // are not going to add emphemeral app, so we can return the result without
7328                        // further processing.
7329                        return applyPostResolutionFilter(result, instantAppPkgName,
7330                                allowDynamicSplits, filterCallingUid, userId);
7331                    }
7332                    // We have more than one candidate (combining results from current and parent
7333                    // profile), so we need filtering and sorting.
7334                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7335                            intent, flags, result, xpDomainInfo, userId);
7336                    sortResult = true;
7337                }
7338            } else {
7339                final PackageParser.Package pkg = mPackages.get(pkgName);
7340                result = null;
7341                if (pkg != null) {
7342                    result = filterIfNotSystemUser(
7343                            mActivities.queryIntentForPackage(
7344                                    intent, resolvedType, flags, pkg.activities, userId),
7345                            userId);
7346                }
7347                if (result == null || result.size() == 0) {
7348                    // the caller wants to resolve for a particular package; however, there
7349                    // were no installed results, so, try to find an ephemeral result
7350                    addEphemeral = !ephemeralDisabled
7351                            && isInstantAppAllowed(
7352                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7353                    if (result == null) {
7354                        result = new ArrayList<>();
7355                    }
7356                }
7357            }
7358        }
7359        if (addEphemeral) {
7360            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7361        }
7362        if (sortResult) {
7363            Collections.sort(result, mResolvePrioritySorter);
7364        }
7365        return applyPostResolutionFilter(
7366                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7367    }
7368
7369    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7370            String resolvedType, int flags, int userId) {
7371        // first, check to see if we've got an instant app already installed
7372        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7373        ResolveInfo localInstantApp = null;
7374        boolean blockResolution = false;
7375        if (!alreadyResolvedLocally) {
7376            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7377                    flags
7378                        | PackageManager.GET_RESOLVED_FILTER
7379                        | PackageManager.MATCH_INSTANT
7380                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7381                    userId);
7382            for (int i = instantApps.size() - 1; i >= 0; --i) {
7383                final ResolveInfo info = instantApps.get(i);
7384                final String packageName = info.activityInfo.packageName;
7385                final PackageSetting ps = mSettings.mPackages.get(packageName);
7386                if (ps.getInstantApp(userId)) {
7387                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7388                    final int status = (int)(packedStatus >> 32);
7389                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7390                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7391                        // there's a local instant application installed, but, the user has
7392                        // chosen to never use it; skip resolution and don't acknowledge
7393                        // an instant application is even available
7394                        if (DEBUG_EPHEMERAL) {
7395                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7396                        }
7397                        blockResolution = true;
7398                        break;
7399                    } else {
7400                        // we have a locally installed instant application; skip resolution
7401                        // but acknowledge there's an instant application available
7402                        if (DEBUG_EPHEMERAL) {
7403                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7404                        }
7405                        localInstantApp = info;
7406                        break;
7407                    }
7408                }
7409            }
7410        }
7411        // no app installed, let's see if one's available
7412        AuxiliaryResolveInfo auxiliaryResponse = null;
7413        if (!blockResolution) {
7414            if (localInstantApp == null) {
7415                // we don't have an instant app locally, resolve externally
7416                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7417                final InstantAppRequest requestObject = new InstantAppRequest(
7418                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7419                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7420                auxiliaryResponse =
7421                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7422                                mContext, mInstantAppResolverConnection, requestObject);
7423                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7424            } else {
7425                // we have an instant application locally, but, we can't admit that since
7426                // callers shouldn't be able to determine prior browsing. create a dummy
7427                // auxiliary response so the downstream code behaves as if there's an
7428                // instant application available externally. when it comes time to start
7429                // the instant application, we'll do the right thing.
7430                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7431                auxiliaryResponse = new AuxiliaryResolveInfo(
7432                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7433                        ai.versionCode, null /*failureIntent*/);
7434            }
7435        }
7436        if (auxiliaryResponse != null) {
7437            if (DEBUG_EPHEMERAL) {
7438                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7439            }
7440            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7441            final PackageSetting ps =
7442                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7443            if (ps != null) {
7444                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7445                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7446                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7447                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7448                // make sure this resolver is the default
7449                ephemeralInstaller.isDefault = true;
7450                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7451                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7452                // add a non-generic filter
7453                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7454                ephemeralInstaller.filter.addDataPath(
7455                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7456                ephemeralInstaller.isInstantAppAvailable = true;
7457                result.add(ephemeralInstaller);
7458            }
7459        }
7460        return result;
7461    }
7462
7463    private static class CrossProfileDomainInfo {
7464        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7465        ResolveInfo resolveInfo;
7466        /* Best domain verification status of the activities found in the other profile */
7467        int bestDomainVerificationStatus;
7468    }
7469
7470    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7471            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7472        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7473                sourceUserId)) {
7474            return null;
7475        }
7476        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7477                resolvedType, flags, parentUserId);
7478
7479        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7480            return null;
7481        }
7482        CrossProfileDomainInfo result = null;
7483        int size = resultTargetUser.size();
7484        for (int i = 0; i < size; i++) {
7485            ResolveInfo riTargetUser = resultTargetUser.get(i);
7486            // Intent filter verification is only for filters that specify a host. So don't return
7487            // those that handle all web uris.
7488            if (riTargetUser.handleAllWebDataURI) {
7489                continue;
7490            }
7491            String packageName = riTargetUser.activityInfo.packageName;
7492            PackageSetting ps = mSettings.mPackages.get(packageName);
7493            if (ps == null) {
7494                continue;
7495            }
7496            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7497            int status = (int)(verificationState >> 32);
7498            if (result == null) {
7499                result = new CrossProfileDomainInfo();
7500                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7501                        sourceUserId, parentUserId);
7502                result.bestDomainVerificationStatus = status;
7503            } else {
7504                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7505                        result.bestDomainVerificationStatus);
7506            }
7507        }
7508        // Don't consider matches with status NEVER across profiles.
7509        if (result != null && result.bestDomainVerificationStatus
7510                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7511            return null;
7512        }
7513        return result;
7514    }
7515
7516    /**
7517     * Verification statuses are ordered from the worse to the best, except for
7518     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7519     */
7520    private int bestDomainVerificationStatus(int status1, int status2) {
7521        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7522            return status2;
7523        }
7524        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7525            return status1;
7526        }
7527        return (int) MathUtils.max(status1, status2);
7528    }
7529
7530    private boolean isUserEnabled(int userId) {
7531        long callingId = Binder.clearCallingIdentity();
7532        try {
7533            UserInfo userInfo = sUserManager.getUserInfo(userId);
7534            return userInfo != null && userInfo.isEnabled();
7535        } finally {
7536            Binder.restoreCallingIdentity(callingId);
7537        }
7538    }
7539
7540    /**
7541     * Filter out activities with systemUserOnly flag set, when current user is not System.
7542     *
7543     * @return filtered list
7544     */
7545    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7546        if (userId == UserHandle.USER_SYSTEM) {
7547            return resolveInfos;
7548        }
7549        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7550            ResolveInfo info = resolveInfos.get(i);
7551            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7552                resolveInfos.remove(i);
7553            }
7554        }
7555        return resolveInfos;
7556    }
7557
7558    /**
7559     * Filters out ephemeral activities.
7560     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7561     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7562     *
7563     * @param resolveInfos The pre-filtered list of resolved activities
7564     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7565     *          is performed.
7566     * @return A filtered list of resolved activities.
7567     */
7568    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7569            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7570        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7571            final ResolveInfo info = resolveInfos.get(i);
7572            // allow activities that are defined in the provided package
7573            if (allowDynamicSplits
7574                    && info.activityInfo.splitName != null
7575                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7576                            info.activityInfo.splitName)) {
7577                // requested activity is defined in a split that hasn't been installed yet.
7578                // add the installer to the resolve list
7579                if (DEBUG_INSTALL) {
7580                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7581                }
7582                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7583                final ComponentName installFailureActivity = findInstallFailureActivity(
7584                        info.activityInfo.packageName,  filterCallingUid, userId);
7585                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7586                        info.activityInfo.packageName, info.activityInfo.splitName,
7587                        installFailureActivity,
7588                        info.activityInfo.applicationInfo.versionCode,
7589                        null /*failureIntent*/);
7590                // make sure this resolver is the default
7591                installerInfo.isDefault = true;
7592                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7593                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7594                // add a non-generic filter
7595                installerInfo.filter = new IntentFilter();
7596                // load resources from the correct package
7597                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7598                resolveInfos.set(i, installerInfo);
7599                continue;
7600            }
7601            // caller is a full app, don't need to apply any other filtering
7602            if (ephemeralPkgName == null) {
7603                continue;
7604            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7605                // caller is same app; don't need to apply any other filtering
7606                continue;
7607            }
7608            // allow activities that have been explicitly exposed to ephemeral apps
7609            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7610            if (!isEphemeralApp
7611                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7612                continue;
7613            }
7614            resolveInfos.remove(i);
7615        }
7616        return resolveInfos;
7617    }
7618
7619    /**
7620     * Returns the activity component that can handle install failures.
7621     * <p>By default, the instant application installer handles failures. However, an
7622     * application may want to handle failures on its own. Applications do this by
7623     * creating an activity with an intent filter that handles the action
7624     * {@link Intent#ACTION_INSTALL_FAILURE}.
7625     */
7626    private @Nullable ComponentName findInstallFailureActivity(
7627            String packageName, int filterCallingUid, int userId) {
7628        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7629        failureActivityIntent.setPackage(packageName);
7630        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7631        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7632                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7633                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7634        final int NR = result.size();
7635        if (NR > 0) {
7636            for (int i = 0; i < NR; i++) {
7637                final ResolveInfo info = result.get(i);
7638                if (info.activityInfo.splitName != null) {
7639                    continue;
7640                }
7641                return new ComponentName(packageName, info.activityInfo.name);
7642            }
7643        }
7644        return null;
7645    }
7646
7647    /**
7648     * @param resolveInfos list of resolve infos in descending priority order
7649     * @return if the list contains a resolve info with non-negative priority
7650     */
7651    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7652        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7653    }
7654
7655    private static boolean hasWebURI(Intent intent) {
7656        if (intent.getData() == null) {
7657            return false;
7658        }
7659        final String scheme = intent.getScheme();
7660        if (TextUtils.isEmpty(scheme)) {
7661            return false;
7662        }
7663        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7664    }
7665
7666    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7667            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7668            int userId) {
7669        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7670
7671        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7672            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7673                    candidates.size());
7674        }
7675
7676        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7677        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7678        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7679        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7680        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7681        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7682
7683        synchronized (mPackages) {
7684            final int count = candidates.size();
7685            // First, try to use linked apps. Partition the candidates into four lists:
7686            // one for the final results, one for the "do not use ever", one for "undefined status"
7687            // and finally one for "browser app type".
7688            for (int n=0; n<count; n++) {
7689                ResolveInfo info = candidates.get(n);
7690                String packageName = info.activityInfo.packageName;
7691                PackageSetting ps = mSettings.mPackages.get(packageName);
7692                if (ps != null) {
7693                    // Add to the special match all list (Browser use case)
7694                    if (info.handleAllWebDataURI) {
7695                        matchAllList.add(info);
7696                        continue;
7697                    }
7698                    // Try to get the status from User settings first
7699                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7700                    int status = (int)(packedStatus >> 32);
7701                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7702                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7703                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7704                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7705                                    + " : linkgen=" + linkGeneration);
7706                        }
7707                        // Use link-enabled generation as preferredOrder, i.e.
7708                        // prefer newly-enabled over earlier-enabled.
7709                        info.preferredOrder = linkGeneration;
7710                        alwaysList.add(info);
7711                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7712                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7713                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7714                        }
7715                        neverList.add(info);
7716                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7717                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7718                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7719                        }
7720                        alwaysAskList.add(info);
7721                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7722                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7723                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7724                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7725                        }
7726                        undefinedList.add(info);
7727                    }
7728                }
7729            }
7730
7731            // We'll want to include browser possibilities in a few cases
7732            boolean includeBrowser = false;
7733
7734            // First try to add the "always" resolution(s) for the current user, if any
7735            if (alwaysList.size() > 0) {
7736                result.addAll(alwaysList);
7737            } else {
7738                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7739                result.addAll(undefinedList);
7740                // Maybe add one for the other profile.
7741                if (xpDomainInfo != null && (
7742                        xpDomainInfo.bestDomainVerificationStatus
7743                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7744                    result.add(xpDomainInfo.resolveInfo);
7745                }
7746                includeBrowser = true;
7747            }
7748
7749            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7750            // If there were 'always' entries their preferred order has been set, so we also
7751            // back that off to make the alternatives equivalent
7752            if (alwaysAskList.size() > 0) {
7753                for (ResolveInfo i : result) {
7754                    i.preferredOrder = 0;
7755                }
7756                result.addAll(alwaysAskList);
7757                includeBrowser = true;
7758            }
7759
7760            if (includeBrowser) {
7761                // Also add browsers (all of them or only the default one)
7762                if (DEBUG_DOMAIN_VERIFICATION) {
7763                    Slog.v(TAG, "   ...including browsers in candidate set");
7764                }
7765                if ((matchFlags & MATCH_ALL) != 0) {
7766                    result.addAll(matchAllList);
7767                } else {
7768                    // Browser/generic handling case.  If there's a default browser, go straight
7769                    // to that (but only if there is no other higher-priority match).
7770                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7771                    int maxMatchPrio = 0;
7772                    ResolveInfo defaultBrowserMatch = null;
7773                    final int numCandidates = matchAllList.size();
7774                    for (int n = 0; n < numCandidates; n++) {
7775                        ResolveInfo info = matchAllList.get(n);
7776                        // track the highest overall match priority...
7777                        if (info.priority > maxMatchPrio) {
7778                            maxMatchPrio = info.priority;
7779                        }
7780                        // ...and the highest-priority default browser match
7781                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7782                            if (defaultBrowserMatch == null
7783                                    || (defaultBrowserMatch.priority < info.priority)) {
7784                                if (debug) {
7785                                    Slog.v(TAG, "Considering default browser match " + info);
7786                                }
7787                                defaultBrowserMatch = info;
7788                            }
7789                        }
7790                    }
7791                    if (defaultBrowserMatch != null
7792                            && defaultBrowserMatch.priority >= maxMatchPrio
7793                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7794                    {
7795                        if (debug) {
7796                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7797                        }
7798                        result.add(defaultBrowserMatch);
7799                    } else {
7800                        result.addAll(matchAllList);
7801                    }
7802                }
7803
7804                // If there is nothing selected, add all candidates and remove the ones that the user
7805                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7806                if (result.size() == 0) {
7807                    result.addAll(candidates);
7808                    result.removeAll(neverList);
7809                }
7810            }
7811        }
7812        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7813            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7814                    result.size());
7815            for (ResolveInfo info : result) {
7816                Slog.v(TAG, "  + " + info.activityInfo);
7817            }
7818        }
7819        return result;
7820    }
7821
7822    // Returns a packed value as a long:
7823    //
7824    // high 'int'-sized word: link status: undefined/ask/never/always.
7825    // low 'int'-sized word: relative priority among 'always' results.
7826    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7827        long result = ps.getDomainVerificationStatusForUser(userId);
7828        // if none available, get the master status
7829        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7830            if (ps.getIntentFilterVerificationInfo() != null) {
7831                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7832            }
7833        }
7834        return result;
7835    }
7836
7837    private ResolveInfo querySkipCurrentProfileIntents(
7838            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7839            int flags, int sourceUserId) {
7840        if (matchingFilters != null) {
7841            int size = matchingFilters.size();
7842            for (int i = 0; i < size; i ++) {
7843                CrossProfileIntentFilter filter = matchingFilters.get(i);
7844                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7845                    // Checking if there are activities in the target user that can handle the
7846                    // intent.
7847                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7848                            resolvedType, flags, sourceUserId);
7849                    if (resolveInfo != null) {
7850                        return resolveInfo;
7851                    }
7852                }
7853            }
7854        }
7855        return null;
7856    }
7857
7858    // Return matching ResolveInfo in target user if any.
7859    private ResolveInfo queryCrossProfileIntents(
7860            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7861            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7862        if (matchingFilters != null) {
7863            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7864            // match the same intent. For performance reasons, it is better not to
7865            // run queryIntent twice for the same userId
7866            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7867            int size = matchingFilters.size();
7868            for (int i = 0; i < size; i++) {
7869                CrossProfileIntentFilter filter = matchingFilters.get(i);
7870                int targetUserId = filter.getTargetUserId();
7871                boolean skipCurrentProfile =
7872                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7873                boolean skipCurrentProfileIfNoMatchFound =
7874                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7875                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7876                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7877                    // Checking if there are activities in the target user that can handle the
7878                    // intent.
7879                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7880                            resolvedType, flags, sourceUserId);
7881                    if (resolveInfo != null) return resolveInfo;
7882                    alreadyTriedUserIds.put(targetUserId, true);
7883                }
7884            }
7885        }
7886        return null;
7887    }
7888
7889    /**
7890     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7891     * will forward the intent to the filter's target user.
7892     * Otherwise, returns null.
7893     */
7894    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7895            String resolvedType, int flags, int sourceUserId) {
7896        int targetUserId = filter.getTargetUserId();
7897        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7898                resolvedType, flags, targetUserId);
7899        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7900            // If all the matches in the target profile are suspended, return null.
7901            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7902                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7903                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7904                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7905                            targetUserId);
7906                }
7907            }
7908        }
7909        return null;
7910    }
7911
7912    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7913            int sourceUserId, int targetUserId) {
7914        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7915        long ident = Binder.clearCallingIdentity();
7916        boolean targetIsProfile;
7917        try {
7918            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7919        } finally {
7920            Binder.restoreCallingIdentity(ident);
7921        }
7922        String className;
7923        if (targetIsProfile) {
7924            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7925        } else {
7926            className = FORWARD_INTENT_TO_PARENT;
7927        }
7928        ComponentName forwardingActivityComponentName = new ComponentName(
7929                mAndroidApplication.packageName, className);
7930        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7931                sourceUserId);
7932        if (!targetIsProfile) {
7933            forwardingActivityInfo.showUserIcon = targetUserId;
7934            forwardingResolveInfo.noResourceId = true;
7935        }
7936        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7937        forwardingResolveInfo.priority = 0;
7938        forwardingResolveInfo.preferredOrder = 0;
7939        forwardingResolveInfo.match = 0;
7940        forwardingResolveInfo.isDefault = true;
7941        forwardingResolveInfo.filter = filter;
7942        forwardingResolveInfo.targetUserId = targetUserId;
7943        return forwardingResolveInfo;
7944    }
7945
7946    @Override
7947    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7948            Intent[] specifics, String[] specificTypes, Intent intent,
7949            String resolvedType, int flags, int userId) {
7950        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7951                specificTypes, intent, resolvedType, flags, userId));
7952    }
7953
7954    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7955            Intent[] specifics, String[] specificTypes, Intent intent,
7956            String resolvedType, int flags, int userId) {
7957        if (!sUserManager.exists(userId)) return Collections.emptyList();
7958        final int callingUid = Binder.getCallingUid();
7959        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7960                false /*includeInstantApps*/);
7961        enforceCrossUserPermission(callingUid, userId,
7962                false /*requireFullPermission*/, false /*checkShell*/,
7963                "query intent activity options");
7964        final String resultsAction = intent.getAction();
7965
7966        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7967                | PackageManager.GET_RESOLVED_FILTER, userId);
7968
7969        if (DEBUG_INTENT_MATCHING) {
7970            Log.v(TAG, "Query " + intent + ": " + results);
7971        }
7972
7973        int specificsPos = 0;
7974        int N;
7975
7976        // todo: note that the algorithm used here is O(N^2).  This
7977        // isn't a problem in our current environment, but if we start running
7978        // into situations where we have more than 5 or 10 matches then this
7979        // should probably be changed to something smarter...
7980
7981        // First we go through and resolve each of the specific items
7982        // that were supplied, taking care of removing any corresponding
7983        // duplicate items in the generic resolve list.
7984        if (specifics != null) {
7985            for (int i=0; i<specifics.length; i++) {
7986                final Intent sintent = specifics[i];
7987                if (sintent == null) {
7988                    continue;
7989                }
7990
7991                if (DEBUG_INTENT_MATCHING) {
7992                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7993                }
7994
7995                String action = sintent.getAction();
7996                if (resultsAction != null && resultsAction.equals(action)) {
7997                    // If this action was explicitly requested, then don't
7998                    // remove things that have it.
7999                    action = null;
8000                }
8001
8002                ResolveInfo ri = null;
8003                ActivityInfo ai = null;
8004
8005                ComponentName comp = sintent.getComponent();
8006                if (comp == null) {
8007                    ri = resolveIntent(
8008                        sintent,
8009                        specificTypes != null ? specificTypes[i] : null,
8010                            flags, userId);
8011                    if (ri == null) {
8012                        continue;
8013                    }
8014                    if (ri == mResolveInfo) {
8015                        // ACK!  Must do something better with this.
8016                    }
8017                    ai = ri.activityInfo;
8018                    comp = new ComponentName(ai.applicationInfo.packageName,
8019                            ai.name);
8020                } else {
8021                    ai = getActivityInfo(comp, flags, userId);
8022                    if (ai == null) {
8023                        continue;
8024                    }
8025                }
8026
8027                // Look for any generic query activities that are duplicates
8028                // of this specific one, and remove them from the results.
8029                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8030                N = results.size();
8031                int j;
8032                for (j=specificsPos; j<N; j++) {
8033                    ResolveInfo sri = results.get(j);
8034                    if ((sri.activityInfo.name.equals(comp.getClassName())
8035                            && sri.activityInfo.applicationInfo.packageName.equals(
8036                                    comp.getPackageName()))
8037                        || (action != null && sri.filter.matchAction(action))) {
8038                        results.remove(j);
8039                        if (DEBUG_INTENT_MATCHING) Log.v(
8040                            TAG, "Removing duplicate item from " + j
8041                            + " due to specific " + specificsPos);
8042                        if (ri == null) {
8043                            ri = sri;
8044                        }
8045                        j--;
8046                        N--;
8047                    }
8048                }
8049
8050                // Add this specific item to its proper place.
8051                if (ri == null) {
8052                    ri = new ResolveInfo();
8053                    ri.activityInfo = ai;
8054                }
8055                results.add(specificsPos, ri);
8056                ri.specificIndex = i;
8057                specificsPos++;
8058            }
8059        }
8060
8061        // Now we go through the remaining generic results and remove any
8062        // duplicate actions that are found here.
8063        N = results.size();
8064        for (int i=specificsPos; i<N-1; i++) {
8065            final ResolveInfo rii = results.get(i);
8066            if (rii.filter == null) {
8067                continue;
8068            }
8069
8070            // Iterate over all of the actions of this result's intent
8071            // filter...  typically this should be just one.
8072            final Iterator<String> it = rii.filter.actionsIterator();
8073            if (it == null) {
8074                continue;
8075            }
8076            while (it.hasNext()) {
8077                final String action = it.next();
8078                if (resultsAction != null && resultsAction.equals(action)) {
8079                    // If this action was explicitly requested, then don't
8080                    // remove things that have it.
8081                    continue;
8082                }
8083                for (int j=i+1; j<N; j++) {
8084                    final ResolveInfo rij = results.get(j);
8085                    if (rij.filter != null && rij.filter.hasAction(action)) {
8086                        results.remove(j);
8087                        if (DEBUG_INTENT_MATCHING) Log.v(
8088                            TAG, "Removing duplicate item from " + j
8089                            + " due to action " + action + " at " + i);
8090                        j--;
8091                        N--;
8092                    }
8093                }
8094            }
8095
8096            // If the caller didn't request filter information, drop it now
8097            // so we don't have to marshall/unmarshall it.
8098            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8099                rii.filter = null;
8100            }
8101        }
8102
8103        // Filter out the caller activity if so requested.
8104        if (caller != null) {
8105            N = results.size();
8106            for (int i=0; i<N; i++) {
8107                ActivityInfo ainfo = results.get(i).activityInfo;
8108                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8109                        && caller.getClassName().equals(ainfo.name)) {
8110                    results.remove(i);
8111                    break;
8112                }
8113            }
8114        }
8115
8116        // If the caller didn't request filter information,
8117        // drop them now so we don't have to
8118        // marshall/unmarshall it.
8119        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8120            N = results.size();
8121            for (int i=0; i<N; i++) {
8122                results.get(i).filter = null;
8123            }
8124        }
8125
8126        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8127        return results;
8128    }
8129
8130    @Override
8131    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8132            String resolvedType, int flags, int userId) {
8133        return new ParceledListSlice<>(
8134                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8135                        false /*allowDynamicSplits*/));
8136    }
8137
8138    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8139            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8140        if (!sUserManager.exists(userId)) return Collections.emptyList();
8141        final int callingUid = Binder.getCallingUid();
8142        enforceCrossUserPermission(callingUid, userId,
8143                false /*requireFullPermission*/, false /*checkShell*/,
8144                "query intent receivers");
8145        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8146        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8147                false /*includeInstantApps*/);
8148        ComponentName comp = intent.getComponent();
8149        if (comp == null) {
8150            if (intent.getSelector() != null) {
8151                intent = intent.getSelector();
8152                comp = intent.getComponent();
8153            }
8154        }
8155        if (comp != null) {
8156            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8157            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8158            if (ai != null) {
8159                // When specifying an explicit component, we prevent the activity from being
8160                // used when either 1) the calling package is normal and the activity is within
8161                // an instant application or 2) the calling package is ephemeral and the
8162                // activity is not visible to instant applications.
8163                final boolean matchInstantApp =
8164                        (flags & PackageManager.MATCH_INSTANT) != 0;
8165                final boolean matchVisibleToInstantAppOnly =
8166                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8167                final boolean matchExplicitlyVisibleOnly =
8168                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8169                final boolean isCallerInstantApp =
8170                        instantAppPkgName != null;
8171                final boolean isTargetSameInstantApp =
8172                        comp.getPackageName().equals(instantAppPkgName);
8173                final boolean isTargetInstantApp =
8174                        (ai.applicationInfo.privateFlags
8175                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8176                final boolean isTargetVisibleToInstantApp =
8177                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8178                final boolean isTargetExplicitlyVisibleToInstantApp =
8179                        isTargetVisibleToInstantApp
8180                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8181                final boolean isTargetHiddenFromInstantApp =
8182                        !isTargetVisibleToInstantApp
8183                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8184                final boolean blockResolution =
8185                        !isTargetSameInstantApp
8186                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8187                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8188                                        && isTargetHiddenFromInstantApp));
8189                if (!blockResolution) {
8190                    ResolveInfo ri = new ResolveInfo();
8191                    ri.activityInfo = ai;
8192                    list.add(ri);
8193                }
8194            }
8195            return applyPostResolutionFilter(
8196                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8197        }
8198
8199        // reader
8200        synchronized (mPackages) {
8201            String pkgName = intent.getPackage();
8202            if (pkgName == null) {
8203                final List<ResolveInfo> result =
8204                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8205                return applyPostResolutionFilter(
8206                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8207            }
8208            final PackageParser.Package pkg = mPackages.get(pkgName);
8209            if (pkg != null) {
8210                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8211                        intent, resolvedType, flags, pkg.receivers, userId);
8212                return applyPostResolutionFilter(
8213                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8214            }
8215            return Collections.emptyList();
8216        }
8217    }
8218
8219    @Override
8220    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8221        final int callingUid = Binder.getCallingUid();
8222        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8223    }
8224
8225    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8226            int userId, int callingUid) {
8227        if (!sUserManager.exists(userId)) return null;
8228        flags = updateFlagsForResolve(
8229                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8230        List<ResolveInfo> query = queryIntentServicesInternal(
8231                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8232        if (query != null) {
8233            if (query.size() >= 1) {
8234                // If there is more than one service with the same priority,
8235                // just arbitrarily pick the first one.
8236                return query.get(0);
8237            }
8238        }
8239        return null;
8240    }
8241
8242    @Override
8243    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8244            String resolvedType, int flags, int userId) {
8245        final int callingUid = Binder.getCallingUid();
8246        return new ParceledListSlice<>(queryIntentServicesInternal(
8247                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8248    }
8249
8250    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8251            String resolvedType, int flags, int userId, int callingUid,
8252            boolean includeInstantApps) {
8253        if (!sUserManager.exists(userId)) return Collections.emptyList();
8254        enforceCrossUserPermission(callingUid, userId,
8255                false /*requireFullPermission*/, false /*checkShell*/,
8256                "query intent receivers");
8257        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8258        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8259        ComponentName comp = intent.getComponent();
8260        if (comp == null) {
8261            if (intent.getSelector() != null) {
8262                intent = intent.getSelector();
8263                comp = intent.getComponent();
8264            }
8265        }
8266        if (comp != null) {
8267            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8268            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8269            if (si != null) {
8270                // When specifying an explicit component, we prevent the service from being
8271                // used when either 1) the service is in an instant application and the
8272                // caller is not the same instant application or 2) the calling package is
8273                // ephemeral and the activity is not visible to ephemeral applications.
8274                final boolean matchInstantApp =
8275                        (flags & PackageManager.MATCH_INSTANT) != 0;
8276                final boolean matchVisibleToInstantAppOnly =
8277                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8278                final boolean isCallerInstantApp =
8279                        instantAppPkgName != null;
8280                final boolean isTargetSameInstantApp =
8281                        comp.getPackageName().equals(instantAppPkgName);
8282                final boolean isTargetInstantApp =
8283                        (si.applicationInfo.privateFlags
8284                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8285                final boolean isTargetHiddenFromInstantApp =
8286                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8287                final boolean blockResolution =
8288                        !isTargetSameInstantApp
8289                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8290                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8291                                        && isTargetHiddenFromInstantApp));
8292                if (!blockResolution) {
8293                    final ResolveInfo ri = new ResolveInfo();
8294                    ri.serviceInfo = si;
8295                    list.add(ri);
8296                }
8297            }
8298            return list;
8299        }
8300
8301        // reader
8302        synchronized (mPackages) {
8303            String pkgName = intent.getPackage();
8304            if (pkgName == null) {
8305                return applyPostServiceResolutionFilter(
8306                        mServices.queryIntent(intent, resolvedType, flags, userId),
8307                        instantAppPkgName);
8308            }
8309            final PackageParser.Package pkg = mPackages.get(pkgName);
8310            if (pkg != null) {
8311                return applyPostServiceResolutionFilter(
8312                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8313                                userId),
8314                        instantAppPkgName);
8315            }
8316            return Collections.emptyList();
8317        }
8318    }
8319
8320    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8321            String instantAppPkgName) {
8322        if (instantAppPkgName == null) {
8323            return resolveInfos;
8324        }
8325        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8326            final ResolveInfo info = resolveInfos.get(i);
8327            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8328            // allow services that are defined in the provided package
8329            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8330                if (info.serviceInfo.splitName != null
8331                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8332                                info.serviceInfo.splitName)) {
8333                    // requested service is defined in a split that hasn't been installed yet.
8334                    // add the installer to the resolve list
8335                    if (DEBUG_EPHEMERAL) {
8336                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8337                    }
8338                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8339                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8340                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8341                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8342                            null /*failureIntent*/);
8343                    // make sure this resolver is the default
8344                    installerInfo.isDefault = true;
8345                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8346                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8347                    // add a non-generic filter
8348                    installerInfo.filter = new IntentFilter();
8349                    // load resources from the correct package
8350                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8351                    resolveInfos.set(i, installerInfo);
8352                }
8353                continue;
8354            }
8355            // allow services that have been explicitly exposed to ephemeral apps
8356            if (!isEphemeralApp
8357                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8358                continue;
8359            }
8360            resolveInfos.remove(i);
8361        }
8362        return resolveInfos;
8363    }
8364
8365    @Override
8366    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8367            String resolvedType, int flags, int userId) {
8368        return new ParceledListSlice<>(
8369                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8370    }
8371
8372    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8373            Intent intent, String resolvedType, int flags, int userId) {
8374        if (!sUserManager.exists(userId)) return Collections.emptyList();
8375        final int callingUid = Binder.getCallingUid();
8376        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8377        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8378                false /*includeInstantApps*/);
8379        ComponentName comp = intent.getComponent();
8380        if (comp == null) {
8381            if (intent.getSelector() != null) {
8382                intent = intent.getSelector();
8383                comp = intent.getComponent();
8384            }
8385        }
8386        if (comp != null) {
8387            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8388            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8389            if (pi != null) {
8390                // When specifying an explicit component, we prevent the provider from being
8391                // used when either 1) the provider is in an instant application and the
8392                // caller is not the same instant application or 2) the calling package is an
8393                // instant application and the provider is not visible to instant applications.
8394                final boolean matchInstantApp =
8395                        (flags & PackageManager.MATCH_INSTANT) != 0;
8396                final boolean matchVisibleToInstantAppOnly =
8397                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8398                final boolean isCallerInstantApp =
8399                        instantAppPkgName != null;
8400                final boolean isTargetSameInstantApp =
8401                        comp.getPackageName().equals(instantAppPkgName);
8402                final boolean isTargetInstantApp =
8403                        (pi.applicationInfo.privateFlags
8404                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8405                final boolean isTargetHiddenFromInstantApp =
8406                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8407                final boolean blockResolution =
8408                        !isTargetSameInstantApp
8409                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8410                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8411                                        && isTargetHiddenFromInstantApp));
8412                if (!blockResolution) {
8413                    final ResolveInfo ri = new ResolveInfo();
8414                    ri.providerInfo = pi;
8415                    list.add(ri);
8416                }
8417            }
8418            return list;
8419        }
8420
8421        // reader
8422        synchronized (mPackages) {
8423            String pkgName = intent.getPackage();
8424            if (pkgName == null) {
8425                return applyPostContentProviderResolutionFilter(
8426                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8427                        instantAppPkgName);
8428            }
8429            final PackageParser.Package pkg = mPackages.get(pkgName);
8430            if (pkg != null) {
8431                return applyPostContentProviderResolutionFilter(
8432                        mProviders.queryIntentForPackage(
8433                        intent, resolvedType, flags, pkg.providers, userId),
8434                        instantAppPkgName);
8435            }
8436            return Collections.emptyList();
8437        }
8438    }
8439
8440    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8441            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8442        if (instantAppPkgName == null) {
8443            return resolveInfos;
8444        }
8445        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8446            final ResolveInfo info = resolveInfos.get(i);
8447            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8448            // allow providers that are defined in the provided package
8449            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8450                if (info.providerInfo.splitName != null
8451                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8452                                info.providerInfo.splitName)) {
8453                    // requested provider is defined in a split that hasn't been installed yet.
8454                    // add the installer to the resolve list
8455                    if (DEBUG_EPHEMERAL) {
8456                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8457                    }
8458                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8459                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8460                            info.providerInfo.packageName, info.providerInfo.splitName,
8461                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8462                            null /*failureIntent*/);
8463                    // make sure this resolver is the default
8464                    installerInfo.isDefault = true;
8465                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8466                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8467                    // add a non-generic filter
8468                    installerInfo.filter = new IntentFilter();
8469                    // load resources from the correct package
8470                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8471                    resolveInfos.set(i, installerInfo);
8472                }
8473                continue;
8474            }
8475            // allow providers that have been explicitly exposed to instant applications
8476            if (!isEphemeralApp
8477                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8478                continue;
8479            }
8480            resolveInfos.remove(i);
8481        }
8482        return resolveInfos;
8483    }
8484
8485    @Override
8486    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8487        final int callingUid = Binder.getCallingUid();
8488        if (getInstantAppPackageName(callingUid) != null) {
8489            return ParceledListSlice.emptyList();
8490        }
8491        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8492        flags = updateFlagsForPackage(flags, userId, null);
8493        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8494        enforceCrossUserPermission(callingUid, userId,
8495                true /* requireFullPermission */, false /* checkShell */,
8496                "get installed packages");
8497
8498        // writer
8499        synchronized (mPackages) {
8500            ArrayList<PackageInfo> list;
8501            if (listUninstalled) {
8502                list = new ArrayList<>(mSettings.mPackages.size());
8503                for (PackageSetting ps : mSettings.mPackages.values()) {
8504                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8505                        continue;
8506                    }
8507                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8508                        return null;
8509                    }
8510                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8511                    if (pi != null) {
8512                        list.add(pi);
8513                    }
8514                }
8515            } else {
8516                list = new ArrayList<>(mPackages.size());
8517                for (PackageParser.Package p : mPackages.values()) {
8518                    final PackageSetting ps = (PackageSetting) p.mExtras;
8519                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8520                        continue;
8521                    }
8522                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8523                        return null;
8524                    }
8525                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8526                            p.mExtras, flags, userId);
8527                    if (pi != null) {
8528                        list.add(pi);
8529                    }
8530                }
8531            }
8532
8533            return new ParceledListSlice<>(list);
8534        }
8535    }
8536
8537    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8538            String[] permissions, boolean[] tmp, int flags, int userId) {
8539        int numMatch = 0;
8540        final PermissionsState permissionsState = ps.getPermissionsState();
8541        for (int i=0; i<permissions.length; i++) {
8542            final String permission = permissions[i];
8543            if (permissionsState.hasPermission(permission, userId)) {
8544                tmp[i] = true;
8545                numMatch++;
8546            } else {
8547                tmp[i] = false;
8548            }
8549        }
8550        if (numMatch == 0) {
8551            return;
8552        }
8553        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8554
8555        // The above might return null in cases of uninstalled apps or install-state
8556        // skew across users/profiles.
8557        if (pi != null) {
8558            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8559                if (numMatch == permissions.length) {
8560                    pi.requestedPermissions = permissions;
8561                } else {
8562                    pi.requestedPermissions = new String[numMatch];
8563                    numMatch = 0;
8564                    for (int i=0; i<permissions.length; i++) {
8565                        if (tmp[i]) {
8566                            pi.requestedPermissions[numMatch] = permissions[i];
8567                            numMatch++;
8568                        }
8569                    }
8570                }
8571            }
8572            list.add(pi);
8573        }
8574    }
8575
8576    @Override
8577    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8578            String[] permissions, int flags, int userId) {
8579        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8580        flags = updateFlagsForPackage(flags, userId, permissions);
8581        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8582                true /* requireFullPermission */, false /* checkShell */,
8583                "get packages holding permissions");
8584        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8585
8586        // writer
8587        synchronized (mPackages) {
8588            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8589            boolean[] tmpBools = new boolean[permissions.length];
8590            if (listUninstalled) {
8591                for (PackageSetting ps : mSettings.mPackages.values()) {
8592                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8593                            userId);
8594                }
8595            } else {
8596                for (PackageParser.Package pkg : mPackages.values()) {
8597                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8598                    if (ps != null) {
8599                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8600                                userId);
8601                    }
8602                }
8603            }
8604
8605            return new ParceledListSlice<PackageInfo>(list);
8606        }
8607    }
8608
8609    @Override
8610    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8611        final int callingUid = Binder.getCallingUid();
8612        if (getInstantAppPackageName(callingUid) != null) {
8613            return ParceledListSlice.emptyList();
8614        }
8615        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8616        flags = updateFlagsForApplication(flags, userId, null);
8617        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8618
8619        // writer
8620        synchronized (mPackages) {
8621            ArrayList<ApplicationInfo> list;
8622            if (listUninstalled) {
8623                list = new ArrayList<>(mSettings.mPackages.size());
8624                for (PackageSetting ps : mSettings.mPackages.values()) {
8625                    ApplicationInfo ai;
8626                    int effectiveFlags = flags;
8627                    if (ps.isSystem()) {
8628                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8629                    }
8630                    if (ps.pkg != null) {
8631                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8632                            continue;
8633                        }
8634                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8635                            return null;
8636                        }
8637                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8638                                ps.readUserState(userId), userId);
8639                        if (ai != null) {
8640                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8641                        }
8642                    } else {
8643                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8644                        // and already converts to externally visible package name
8645                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8646                                callingUid, effectiveFlags, userId);
8647                    }
8648                    if (ai != null) {
8649                        list.add(ai);
8650                    }
8651                }
8652            } else {
8653                list = new ArrayList<>(mPackages.size());
8654                for (PackageParser.Package p : mPackages.values()) {
8655                    if (p.mExtras != null) {
8656                        PackageSetting ps = (PackageSetting) p.mExtras;
8657                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8658                            continue;
8659                        }
8660                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8661                            return null;
8662                        }
8663                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8664                                ps.readUserState(userId), userId);
8665                        if (ai != null) {
8666                            ai.packageName = resolveExternalPackageNameLPr(p);
8667                            list.add(ai);
8668                        }
8669                    }
8670                }
8671            }
8672
8673            return new ParceledListSlice<>(list);
8674        }
8675    }
8676
8677    @Override
8678    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8679        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8680            return null;
8681        }
8682        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8683            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8684                    "getEphemeralApplications");
8685        }
8686        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8687                true /* requireFullPermission */, false /* checkShell */,
8688                "getEphemeralApplications");
8689        synchronized (mPackages) {
8690            List<InstantAppInfo> instantApps = mInstantAppRegistry
8691                    .getInstantAppsLPr(userId);
8692            if (instantApps != null) {
8693                return new ParceledListSlice<>(instantApps);
8694            }
8695        }
8696        return null;
8697    }
8698
8699    @Override
8700    public boolean isInstantApp(String packageName, int userId) {
8701        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8702                true /* requireFullPermission */, false /* checkShell */,
8703                "isInstantApp");
8704        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8705            return false;
8706        }
8707
8708        synchronized (mPackages) {
8709            int callingUid = Binder.getCallingUid();
8710            if (Process.isIsolated(callingUid)) {
8711                callingUid = mIsolatedOwners.get(callingUid);
8712            }
8713            final PackageSetting ps = mSettings.mPackages.get(packageName);
8714            PackageParser.Package pkg = mPackages.get(packageName);
8715            final boolean returnAllowed =
8716                    ps != null
8717                    && (isCallerSameApp(packageName, callingUid)
8718                            || canViewInstantApps(callingUid, userId)
8719                            || mInstantAppRegistry.isInstantAccessGranted(
8720                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8721            if (returnAllowed) {
8722                return ps.getInstantApp(userId);
8723            }
8724        }
8725        return false;
8726    }
8727
8728    @Override
8729    public byte[] getInstantAppCookie(String packageName, int userId) {
8730        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8731            return null;
8732        }
8733
8734        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8735                true /* requireFullPermission */, false /* checkShell */,
8736                "getInstantAppCookie");
8737        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8738            return null;
8739        }
8740        synchronized (mPackages) {
8741            return mInstantAppRegistry.getInstantAppCookieLPw(
8742                    packageName, userId);
8743        }
8744    }
8745
8746    @Override
8747    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8748        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8749            return true;
8750        }
8751
8752        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8753                true /* requireFullPermission */, true /* checkShell */,
8754                "setInstantAppCookie");
8755        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8756            return false;
8757        }
8758        synchronized (mPackages) {
8759            return mInstantAppRegistry.setInstantAppCookieLPw(
8760                    packageName, cookie, userId);
8761        }
8762    }
8763
8764    @Override
8765    public Bitmap getInstantAppIcon(String packageName, int userId) {
8766        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8767            return null;
8768        }
8769
8770        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8771            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8772                    "getInstantAppIcon");
8773        }
8774        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8775                true /* requireFullPermission */, false /* checkShell */,
8776                "getInstantAppIcon");
8777
8778        synchronized (mPackages) {
8779            return mInstantAppRegistry.getInstantAppIconLPw(
8780                    packageName, userId);
8781        }
8782    }
8783
8784    private boolean isCallerSameApp(String packageName, int uid) {
8785        PackageParser.Package pkg = mPackages.get(packageName);
8786        return pkg != null
8787                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8788    }
8789
8790    @Override
8791    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8792        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8793            return ParceledListSlice.emptyList();
8794        }
8795        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8796    }
8797
8798    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8799        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8800
8801        // reader
8802        synchronized (mPackages) {
8803            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8804            final int userId = UserHandle.getCallingUserId();
8805            while (i.hasNext()) {
8806                final PackageParser.Package p = i.next();
8807                if (p.applicationInfo == null) continue;
8808
8809                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8810                        && !p.applicationInfo.isDirectBootAware();
8811                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8812                        && p.applicationInfo.isDirectBootAware();
8813
8814                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8815                        && (!mSafeMode || isSystemApp(p))
8816                        && (matchesUnaware || matchesAware)) {
8817                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8818                    if (ps != null) {
8819                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8820                                ps.readUserState(userId), userId);
8821                        if (ai != null) {
8822                            finalList.add(ai);
8823                        }
8824                    }
8825                }
8826            }
8827        }
8828
8829        return finalList;
8830    }
8831
8832    @Override
8833    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8834        if (!sUserManager.exists(userId)) return null;
8835        flags = updateFlagsForComponent(flags, userId, name);
8836        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8837        // reader
8838        synchronized (mPackages) {
8839            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8840            PackageSetting ps = provider != null
8841                    ? mSettings.mPackages.get(provider.owner.packageName)
8842                    : null;
8843            if (ps != null) {
8844                final boolean isInstantApp = ps.getInstantApp(userId);
8845                // normal application; filter out instant application provider
8846                if (instantAppPkgName == null && isInstantApp) {
8847                    return null;
8848                }
8849                // instant application; filter out other instant applications
8850                if (instantAppPkgName != null
8851                        && isInstantApp
8852                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8853                    return null;
8854                }
8855                // instant application; filter out non-exposed provider
8856                if (instantAppPkgName != null
8857                        && !isInstantApp
8858                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8859                    return null;
8860                }
8861                // provider not enabled
8862                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8863                    return null;
8864                }
8865                return PackageParser.generateProviderInfo(
8866                        provider, flags, ps.readUserState(userId), userId);
8867            }
8868            return null;
8869        }
8870    }
8871
8872    /**
8873     * @deprecated
8874     */
8875    @Deprecated
8876    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8877        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8878            return;
8879        }
8880        // reader
8881        synchronized (mPackages) {
8882            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8883                    .entrySet().iterator();
8884            final int userId = UserHandle.getCallingUserId();
8885            while (i.hasNext()) {
8886                Map.Entry<String, PackageParser.Provider> entry = i.next();
8887                PackageParser.Provider p = entry.getValue();
8888                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8889
8890                if (ps != null && p.syncable
8891                        && (!mSafeMode || (p.info.applicationInfo.flags
8892                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8893                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8894                            ps.readUserState(userId), userId);
8895                    if (info != null) {
8896                        outNames.add(entry.getKey());
8897                        outInfo.add(info);
8898                    }
8899                }
8900            }
8901        }
8902    }
8903
8904    @Override
8905    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8906            int uid, int flags, String metaDataKey) {
8907        final int callingUid = Binder.getCallingUid();
8908        final int userId = processName != null ? UserHandle.getUserId(uid)
8909                : UserHandle.getCallingUserId();
8910        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8911        flags = updateFlagsForComponent(flags, userId, processName);
8912        ArrayList<ProviderInfo> finalList = null;
8913        // reader
8914        synchronized (mPackages) {
8915            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8916            while (i.hasNext()) {
8917                final PackageParser.Provider p = i.next();
8918                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8919                if (ps != null && p.info.authority != null
8920                        && (processName == null
8921                                || (p.info.processName.equals(processName)
8922                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8923                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8924
8925                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8926                    // parameter.
8927                    if (metaDataKey != null
8928                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8929                        continue;
8930                    }
8931                    final ComponentName component =
8932                            new ComponentName(p.info.packageName, p.info.name);
8933                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8934                        continue;
8935                    }
8936                    if (finalList == null) {
8937                        finalList = new ArrayList<ProviderInfo>(3);
8938                    }
8939                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8940                            ps.readUserState(userId), userId);
8941                    if (info != null) {
8942                        finalList.add(info);
8943                    }
8944                }
8945            }
8946        }
8947
8948        if (finalList != null) {
8949            Collections.sort(finalList, mProviderInitOrderSorter);
8950            return new ParceledListSlice<ProviderInfo>(finalList);
8951        }
8952
8953        return ParceledListSlice.emptyList();
8954    }
8955
8956    @Override
8957    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8958        // reader
8959        synchronized (mPackages) {
8960            final int callingUid = Binder.getCallingUid();
8961            final int callingUserId = UserHandle.getUserId(callingUid);
8962            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8963            if (ps == null) return null;
8964            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8965                return null;
8966            }
8967            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8968            return PackageParser.generateInstrumentationInfo(i, flags);
8969        }
8970    }
8971
8972    @Override
8973    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8974            String targetPackage, int flags) {
8975        final int callingUid = Binder.getCallingUid();
8976        final int callingUserId = UserHandle.getUserId(callingUid);
8977        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8978        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8979            return ParceledListSlice.emptyList();
8980        }
8981        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8982    }
8983
8984    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8985            int flags) {
8986        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8987
8988        // reader
8989        synchronized (mPackages) {
8990            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8991            while (i.hasNext()) {
8992                final PackageParser.Instrumentation p = i.next();
8993                if (targetPackage == null
8994                        || targetPackage.equals(p.info.targetPackage)) {
8995                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8996                            flags);
8997                    if (ii != null) {
8998                        finalList.add(ii);
8999                    }
9000                }
9001            }
9002        }
9003
9004        return finalList;
9005    }
9006
9007    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9008        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9009        try {
9010            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9011        } finally {
9012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9013        }
9014    }
9015
9016    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9017        final File[] files = dir.listFiles();
9018        if (ArrayUtils.isEmpty(files)) {
9019            Log.d(TAG, "No files in app dir " + dir);
9020            return;
9021        }
9022
9023        if (DEBUG_PACKAGE_SCANNING) {
9024            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9025                    + " flags=0x" + Integer.toHexString(parseFlags));
9026        }
9027        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9028                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9029                mParallelPackageParserCallback);
9030
9031        // Submit files for parsing in parallel
9032        int fileCount = 0;
9033        for (File file : files) {
9034            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9035                    && !PackageInstallerService.isStageName(file.getName());
9036            if (!isPackage) {
9037                // Ignore entries which are not packages
9038                continue;
9039            }
9040            parallelPackageParser.submit(file, parseFlags);
9041            fileCount++;
9042        }
9043
9044        // Process results one by one
9045        for (; fileCount > 0; fileCount--) {
9046            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9047            Throwable throwable = parseResult.throwable;
9048            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9049
9050            if (throwable == null) {
9051                // Static shared libraries have synthetic package names
9052                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9053                    renameStaticSharedLibraryPackage(parseResult.pkg);
9054                }
9055                try {
9056                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9057                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9058                                currentTime, null);
9059                    }
9060                } catch (PackageManagerException e) {
9061                    errorCode = e.error;
9062                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9063                }
9064            } else if (throwable instanceof PackageParser.PackageParserException) {
9065                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9066                        throwable;
9067                errorCode = e.error;
9068                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9069            } else {
9070                throw new IllegalStateException("Unexpected exception occurred while parsing "
9071                        + parseResult.scanFile, throwable);
9072            }
9073
9074            // Delete invalid userdata apps
9075            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9076                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9077                logCriticalInfo(Log.WARN,
9078                        "Deleting invalid package at " + parseResult.scanFile);
9079                removeCodePathLI(parseResult.scanFile);
9080            }
9081        }
9082        parallelPackageParser.close();
9083    }
9084
9085    private static File getSettingsProblemFile() {
9086        File dataDir = Environment.getDataDirectory();
9087        File systemDir = new File(dataDir, "system");
9088        File fname = new File(systemDir, "uiderrors.txt");
9089        return fname;
9090    }
9091
9092    static void reportSettingsProblem(int priority, String msg) {
9093        logCriticalInfo(priority, msg);
9094    }
9095
9096    public static void logCriticalInfo(int priority, String msg) {
9097        Slog.println(priority, TAG, msg);
9098        EventLogTags.writePmCriticalInfo(msg);
9099        try {
9100            File fname = getSettingsProblemFile();
9101            FileOutputStream out = new FileOutputStream(fname, true);
9102            PrintWriter pw = new FastPrintWriter(out);
9103            SimpleDateFormat formatter = new SimpleDateFormat();
9104            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9105            pw.println(dateString + ": " + msg);
9106            pw.close();
9107            FileUtils.setPermissions(
9108                    fname.toString(),
9109                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9110                    -1, -1);
9111        } catch (java.io.IOException e) {
9112        }
9113    }
9114
9115    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9116        if (srcFile.isDirectory()) {
9117            final File baseFile = new File(pkg.baseCodePath);
9118            long maxModifiedTime = baseFile.lastModified();
9119            if (pkg.splitCodePaths != null) {
9120                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9121                    final File splitFile = new File(pkg.splitCodePaths[i]);
9122                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9123                }
9124            }
9125            return maxModifiedTime;
9126        }
9127        return srcFile.lastModified();
9128    }
9129
9130    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9131            final int policyFlags) throws PackageManagerException {
9132        // When upgrading from pre-N MR1, verify the package time stamp using the package
9133        // directory and not the APK file.
9134        final long lastModifiedTime = mIsPreNMR1Upgrade
9135                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9136        if (ps != null
9137                && ps.codePath.equals(srcFile)
9138                && ps.timeStamp == lastModifiedTime
9139                && !isCompatSignatureUpdateNeeded(pkg)
9140                && !isRecoverSignatureUpdateNeeded(pkg)) {
9141            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9142            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9143            ArraySet<PublicKey> signingKs;
9144            synchronized (mPackages) {
9145                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9146            }
9147            if (ps.signatures.mSignatures != null
9148                    && ps.signatures.mSignatures.length != 0
9149                    && signingKs != null) {
9150                // Optimization: reuse the existing cached certificates
9151                // if the package appears to be unchanged.
9152                pkg.mSignatures = ps.signatures.mSignatures;
9153                pkg.mSigningKeys = signingKs;
9154                return;
9155            }
9156
9157            Slog.w(TAG, "PackageSetting for " + ps.name
9158                    + " is missing signatures.  Collecting certs again to recover them.");
9159        } else {
9160            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9161        }
9162
9163        try {
9164            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9165            PackageParser.collectCertificates(pkg, policyFlags);
9166        } catch (PackageParserException e) {
9167            throw PackageManagerException.from(e);
9168        } finally {
9169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9170        }
9171    }
9172
9173    /**
9174     *  Traces a package scan.
9175     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9176     */
9177    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9178            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9179        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9180        try {
9181            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9182        } finally {
9183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9184        }
9185    }
9186
9187    /**
9188     *  Scans a package and returns the newly parsed package.
9189     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9190     */
9191    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9192            long currentTime, UserHandle user) throws PackageManagerException {
9193        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9194        PackageParser pp = new PackageParser();
9195        pp.setSeparateProcesses(mSeparateProcesses);
9196        pp.setOnlyCoreApps(mOnlyCore);
9197        pp.setDisplayMetrics(mMetrics);
9198        pp.setCallback(mPackageParserCallback);
9199
9200        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9201            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9202        }
9203
9204        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9205        final PackageParser.Package pkg;
9206        try {
9207            pkg = pp.parsePackage(scanFile, parseFlags);
9208        } catch (PackageParserException e) {
9209            throw PackageManagerException.from(e);
9210        } finally {
9211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9212        }
9213
9214        // Static shared libraries have synthetic package names
9215        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9216            renameStaticSharedLibraryPackage(pkg);
9217        }
9218
9219        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9220    }
9221
9222    /**
9223     *  Scans a package and returns the newly parsed package.
9224     *  @throws PackageManagerException on a parse error.
9225     */
9226    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9227            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9228            throws PackageManagerException {
9229        // If the package has children and this is the first dive in the function
9230        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9231        // packages (parent and children) would be successfully scanned before the
9232        // actual scan since scanning mutates internal state and we want to atomically
9233        // install the package and its children.
9234        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9235            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9236                scanFlags |= SCAN_CHECK_ONLY;
9237            }
9238        } else {
9239            scanFlags &= ~SCAN_CHECK_ONLY;
9240        }
9241
9242        // Scan the parent
9243        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9244                scanFlags, currentTime, user);
9245
9246        // Scan the children
9247        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9248        for (int i = 0; i < childCount; i++) {
9249            PackageParser.Package childPackage = pkg.childPackages.get(i);
9250            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9251                    currentTime, user);
9252        }
9253
9254
9255        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9256            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9257        }
9258
9259        return scannedPkg;
9260    }
9261
9262    /**
9263     *  Scans a package and returns the newly parsed package.
9264     *  @throws PackageManagerException on a parse error.
9265     */
9266    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9267            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9268            throws PackageManagerException {
9269        PackageSetting ps = null;
9270        PackageSetting updatedPkg;
9271        // reader
9272        synchronized (mPackages) {
9273            // Look to see if we already know about this package.
9274            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9275            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9276                // This package has been renamed to its original name.  Let's
9277                // use that.
9278                ps = mSettings.getPackageLPr(oldName);
9279            }
9280            // If there was no original package, see one for the real package name.
9281            if (ps == null) {
9282                ps = mSettings.getPackageLPr(pkg.packageName);
9283            }
9284            // Check to see if this package could be hiding/updating a system
9285            // package.  Must look for it either under the original or real
9286            // package name depending on our state.
9287            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9288            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9289
9290            // If this is a package we don't know about on the system partition, we
9291            // may need to remove disabled child packages on the system partition
9292            // or may need to not add child packages if the parent apk is updated
9293            // on the data partition and no longer defines this child package.
9294            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9295                // If this is a parent package for an updated system app and this system
9296                // app got an OTA update which no longer defines some of the child packages
9297                // we have to prune them from the disabled system packages.
9298                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9299                if (disabledPs != null) {
9300                    final int scannedChildCount = (pkg.childPackages != null)
9301                            ? pkg.childPackages.size() : 0;
9302                    final int disabledChildCount = disabledPs.childPackageNames != null
9303                            ? disabledPs.childPackageNames.size() : 0;
9304                    for (int i = 0; i < disabledChildCount; i++) {
9305                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9306                        boolean disabledPackageAvailable = false;
9307                        for (int j = 0; j < scannedChildCount; j++) {
9308                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9309                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9310                                disabledPackageAvailable = true;
9311                                break;
9312                            }
9313                         }
9314                         if (!disabledPackageAvailable) {
9315                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9316                         }
9317                    }
9318                }
9319            }
9320        }
9321
9322        final boolean isUpdatedPkg = updatedPkg != null;
9323        final boolean isUpdatedSystemPkg = isUpdatedPkg
9324                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9325        boolean isUpdatedPkgBetter = false;
9326        // First check if this is a system package that may involve an update
9327        if (isUpdatedSystemPkg) {
9328            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9329            // it needs to drop FLAG_PRIVILEGED.
9330            if (locationIsPrivileged(scanFile)) {
9331                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9332            } else {
9333                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9334            }
9335
9336            if (ps != null && !ps.codePath.equals(scanFile)) {
9337                // The path has changed from what was last scanned...  check the
9338                // version of the new path against what we have stored to determine
9339                // what to do.
9340                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9341                if (pkg.mVersionCode <= ps.versionCode) {
9342                    // The system package has been updated and the code path does not match
9343                    // Ignore entry. Skip it.
9344                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9345                            + " ignored: updated version " + ps.versionCode
9346                            + " better than this " + pkg.mVersionCode);
9347                    if (!updatedPkg.codePath.equals(scanFile)) {
9348                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9349                                + ps.name + " changing from " + updatedPkg.codePathString
9350                                + " to " + scanFile);
9351                        updatedPkg.codePath = scanFile;
9352                        updatedPkg.codePathString = scanFile.toString();
9353                        updatedPkg.resourcePath = scanFile;
9354                        updatedPkg.resourcePathString = scanFile.toString();
9355                    }
9356                    updatedPkg.pkg = pkg;
9357                    updatedPkg.versionCode = pkg.mVersionCode;
9358
9359                    // Update the disabled system child packages to point to the package too.
9360                    final int childCount = updatedPkg.childPackageNames != null
9361                            ? updatedPkg.childPackageNames.size() : 0;
9362                    for (int i = 0; i < childCount; i++) {
9363                        String childPackageName = updatedPkg.childPackageNames.get(i);
9364                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9365                                childPackageName);
9366                        if (updatedChildPkg != null) {
9367                            updatedChildPkg.pkg = pkg;
9368                            updatedChildPkg.versionCode = pkg.mVersionCode;
9369                        }
9370                    }
9371                } else {
9372                    // The current app on the system partition is better than
9373                    // what we have updated to on the data partition; switch
9374                    // back to the system partition version.
9375                    // At this point, its safely assumed that package installation for
9376                    // apps in system partition will go through. If not there won't be a working
9377                    // version of the app
9378                    // writer
9379                    synchronized (mPackages) {
9380                        // Just remove the loaded entries from package lists.
9381                        mPackages.remove(ps.name);
9382                    }
9383
9384                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9385                            + " reverting from " + ps.codePathString
9386                            + ": new version " + pkg.mVersionCode
9387                            + " better than installed " + ps.versionCode);
9388
9389                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9390                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9391                    synchronized (mInstallLock) {
9392                        args.cleanUpResourcesLI();
9393                    }
9394                    synchronized (mPackages) {
9395                        mSettings.enableSystemPackageLPw(ps.name);
9396                    }
9397                    isUpdatedPkgBetter = true;
9398                }
9399            }
9400        }
9401
9402        String resourcePath = null;
9403        String baseResourcePath = null;
9404        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9405            if (ps != null && ps.resourcePathString != null) {
9406                resourcePath = ps.resourcePathString;
9407                baseResourcePath = ps.resourcePathString;
9408            } else {
9409                // Should not happen at all. Just log an error.
9410                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9411            }
9412        } else {
9413            resourcePath = pkg.codePath;
9414            baseResourcePath = pkg.baseCodePath;
9415        }
9416
9417        // Set application objects path explicitly.
9418        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9419        pkg.setApplicationInfoCodePath(pkg.codePath);
9420        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9421        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9422        pkg.setApplicationInfoResourcePath(resourcePath);
9423        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9424        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9425
9426        // throw an exception if we have an update to a system application, but, it's not more
9427        // recent than the package we've already scanned
9428        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9429            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9430                    + scanFile + " ignored: updated version " + ps.versionCode
9431                    + " better than this " + pkg.mVersionCode);
9432        }
9433
9434        if (isUpdatedPkg) {
9435            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9436            // initially
9437            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9438
9439            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9440            // flag set initially
9441            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9442                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9443            }
9444        }
9445
9446        // Verify certificates against what was last scanned
9447        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9448
9449        /*
9450         * A new system app appeared, but we already had a non-system one of the
9451         * same name installed earlier.
9452         */
9453        boolean shouldHideSystemApp = false;
9454        if (!isUpdatedPkg && ps != null
9455                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9456            /*
9457             * Check to make sure the signatures match first. If they don't,
9458             * wipe the installed application and its data.
9459             */
9460            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9461                    != PackageManager.SIGNATURE_MATCH) {
9462                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9463                        + " signatures don't match existing userdata copy; removing");
9464                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9465                        "scanPackageInternalLI")) {
9466                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9467                }
9468                ps = null;
9469            } else {
9470                /*
9471                 * If the newly-added system app is an older version than the
9472                 * already installed version, hide it. It will be scanned later
9473                 * and re-added like an update.
9474                 */
9475                if (pkg.mVersionCode <= ps.versionCode) {
9476                    shouldHideSystemApp = true;
9477                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9478                            + " but new version " + pkg.mVersionCode + " better than installed "
9479                            + ps.versionCode + "; hiding system");
9480                } else {
9481                    /*
9482                     * The newly found system app is a newer version that the
9483                     * one previously installed. Simply remove the
9484                     * already-installed application and replace it with our own
9485                     * while keeping the application data.
9486                     */
9487                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9488                            + " reverting from " + ps.codePathString + ": new version "
9489                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9490                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9491                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9492                    synchronized (mInstallLock) {
9493                        args.cleanUpResourcesLI();
9494                    }
9495                }
9496            }
9497        }
9498
9499        // The apk is forward locked (not public) if its code and resources
9500        // are kept in different files. (except for app in either system or
9501        // vendor path).
9502        // TODO grab this value from PackageSettings
9503        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9504            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9505                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9506            }
9507        }
9508
9509        final int userId = ((user == null) ? 0 : user.getIdentifier());
9510        if (ps != null && ps.getInstantApp(userId)) {
9511            scanFlags |= SCAN_AS_INSTANT_APP;
9512        }
9513        if (ps != null && ps.getVirtulalPreload(userId)) {
9514            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9515        }
9516
9517        // Note that we invoke the following method only if we are about to unpack an application
9518        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9519                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9520
9521        /*
9522         * If the system app should be overridden by a previously installed
9523         * data, hide the system app now and let the /data/app scan pick it up
9524         * again.
9525         */
9526        if (shouldHideSystemApp) {
9527            synchronized (mPackages) {
9528                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9529            }
9530        }
9531
9532        return scannedPkg;
9533    }
9534
9535    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9536        // Derive the new package synthetic package name
9537        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9538                + pkg.staticSharedLibVersion);
9539    }
9540
9541    private static String fixProcessName(String defProcessName,
9542            String processName) {
9543        if (processName == null) {
9544            return defProcessName;
9545        }
9546        return processName;
9547    }
9548
9549    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9550            throws PackageManagerException {
9551        if (pkgSetting.signatures.mSignatures != null) {
9552            // Already existing package. Make sure signatures match
9553            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9554                    == PackageManager.SIGNATURE_MATCH;
9555            if (!match) {
9556                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9557                        == PackageManager.SIGNATURE_MATCH;
9558            }
9559            if (!match) {
9560                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9561                        == PackageManager.SIGNATURE_MATCH;
9562            }
9563            if (!match) {
9564                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9565                        + pkg.packageName + " signatures do not match the "
9566                        + "previously installed version; ignoring!");
9567            }
9568        }
9569
9570        // Check for shared user signatures
9571        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9572            // Already existing package. Make sure signatures match
9573            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9574                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9575            if (!match) {
9576                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9577                        == PackageManager.SIGNATURE_MATCH;
9578            }
9579            if (!match) {
9580                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9581                        == PackageManager.SIGNATURE_MATCH;
9582            }
9583            if (!match) {
9584                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9585                        "Package " + pkg.packageName
9586                        + " has no signatures that match those in shared user "
9587                        + pkgSetting.sharedUser.name + "; ignoring!");
9588            }
9589        }
9590    }
9591
9592    /**
9593     * Enforces that only the system UID or root's UID can call a method exposed
9594     * via Binder.
9595     *
9596     * @param message used as message if SecurityException is thrown
9597     * @throws SecurityException if the caller is not system or root
9598     */
9599    private static final void enforceSystemOrRoot(String message) {
9600        final int uid = Binder.getCallingUid();
9601        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9602            throw new SecurityException(message);
9603        }
9604    }
9605
9606    @Override
9607    public void performFstrimIfNeeded() {
9608        enforceSystemOrRoot("Only the system can request fstrim");
9609
9610        // Before everything else, see whether we need to fstrim.
9611        try {
9612            IStorageManager sm = PackageHelper.getStorageManager();
9613            if (sm != null) {
9614                boolean doTrim = false;
9615                final long interval = android.provider.Settings.Global.getLong(
9616                        mContext.getContentResolver(),
9617                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9618                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9619                if (interval > 0) {
9620                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9621                    if (timeSinceLast > interval) {
9622                        doTrim = true;
9623                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9624                                + "; running immediately");
9625                    }
9626                }
9627                if (doTrim) {
9628                    final boolean dexOptDialogShown;
9629                    synchronized (mPackages) {
9630                        dexOptDialogShown = mDexOptDialogShown;
9631                    }
9632                    if (!isFirstBoot() && dexOptDialogShown) {
9633                        try {
9634                            ActivityManager.getService().showBootMessage(
9635                                    mContext.getResources().getString(
9636                                            R.string.android_upgrading_fstrim), true);
9637                        } catch (RemoteException e) {
9638                        }
9639                    }
9640                    sm.runMaintenance();
9641                }
9642            } else {
9643                Slog.e(TAG, "storageManager service unavailable!");
9644            }
9645        } catch (RemoteException e) {
9646            // Can't happen; StorageManagerService is local
9647        }
9648    }
9649
9650    @Override
9651    public void updatePackagesIfNeeded() {
9652        enforceSystemOrRoot("Only the system can request package update");
9653
9654        // We need to re-extract after an OTA.
9655        boolean causeUpgrade = isUpgrade();
9656
9657        // First boot or factory reset.
9658        // Note: we also handle devices that are upgrading to N right now as if it is their
9659        //       first boot, as they do not have profile data.
9660        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9661
9662        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9663        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9664
9665        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9666            return;
9667        }
9668
9669        List<PackageParser.Package> pkgs;
9670        synchronized (mPackages) {
9671            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9672        }
9673
9674        final long startTime = System.nanoTime();
9675        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9676                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9677                    false /* bootComplete */);
9678
9679        final int elapsedTimeSeconds =
9680                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9681
9682        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9683        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9684        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9685        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9686        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9687    }
9688
9689    /*
9690     * Return the prebuilt profile path given a package base code path.
9691     */
9692    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9693        return pkg.baseCodePath + ".prof";
9694    }
9695
9696    /**
9697     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9698     * containing statistics about the invocation. The array consists of three elements,
9699     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9700     * and {@code numberOfPackagesFailed}.
9701     */
9702    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9703            String compilerFilter, boolean bootComplete) {
9704
9705        int numberOfPackagesVisited = 0;
9706        int numberOfPackagesOptimized = 0;
9707        int numberOfPackagesSkipped = 0;
9708        int numberOfPackagesFailed = 0;
9709        final int numberOfPackagesToDexopt = pkgs.size();
9710
9711        for (PackageParser.Package pkg : pkgs) {
9712            numberOfPackagesVisited++;
9713
9714            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9715                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9716                // that are already compiled.
9717                File profileFile = new File(getPrebuildProfilePath(pkg));
9718                // Copy profile if it exists.
9719                if (profileFile.exists()) {
9720                    try {
9721                        // We could also do this lazily before calling dexopt in
9722                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9723                        // is that we don't have a good way to say "do this only once".
9724                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9725                                pkg.applicationInfo.uid, pkg.packageName)) {
9726                            Log.e(TAG, "Installer failed to copy system profile!");
9727                        }
9728                    } catch (Exception e) {
9729                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9730                                e);
9731                    }
9732                }
9733            }
9734
9735            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9736                if (DEBUG_DEXOPT) {
9737                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9738                }
9739                numberOfPackagesSkipped++;
9740                continue;
9741            }
9742
9743            if (DEBUG_DEXOPT) {
9744                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9745                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9746            }
9747
9748            if (showDialog) {
9749                try {
9750                    ActivityManager.getService().showBootMessage(
9751                            mContext.getResources().getString(R.string.android_upgrading_apk,
9752                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9753                } catch (RemoteException e) {
9754                }
9755                synchronized (mPackages) {
9756                    mDexOptDialogShown = true;
9757                }
9758            }
9759
9760            // If the OTA updates a system app which was previously preopted to a non-preopted state
9761            // the app might end up being verified at runtime. That's because by default the apps
9762            // are verify-profile but for preopted apps there's no profile.
9763            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9764            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9765            // filter (by default 'quicken').
9766            // Note that at this stage unused apps are already filtered.
9767            if (isSystemApp(pkg) &&
9768                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9769                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9770                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9771            }
9772
9773            // checkProfiles is false to avoid merging profiles during boot which
9774            // might interfere with background compilation (b/28612421).
9775            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9776            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9777            // trade-off worth doing to save boot time work.
9778            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9779            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9780                    pkg.packageName,
9781                    compilerFilter,
9782                    dexoptFlags));
9783
9784            if (pkg.isSystemApp()) {
9785                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9786                // too much boot after an OTA.
9787                int secondaryDexoptFlags = dexoptFlags |
9788                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9789                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9790                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9791                        pkg.packageName,
9792                        compilerFilter,
9793                        secondaryDexoptFlags));
9794            }
9795
9796            // TODO(shubhamajmera): Record secondary dexopt stats.
9797            switch (primaryDexOptStaus) {
9798                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9799                    numberOfPackagesOptimized++;
9800                    break;
9801                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9802                    numberOfPackagesSkipped++;
9803                    break;
9804                case PackageDexOptimizer.DEX_OPT_FAILED:
9805                    numberOfPackagesFailed++;
9806                    break;
9807                default:
9808                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9809                    break;
9810            }
9811        }
9812
9813        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9814                numberOfPackagesFailed };
9815    }
9816
9817    @Override
9818    public void notifyPackageUse(String packageName, int reason) {
9819        synchronized (mPackages) {
9820            final int callingUid = Binder.getCallingUid();
9821            final int callingUserId = UserHandle.getUserId(callingUid);
9822            if (getInstantAppPackageName(callingUid) != null) {
9823                if (!isCallerSameApp(packageName, callingUid)) {
9824                    return;
9825                }
9826            } else {
9827                if (isInstantApp(packageName, callingUserId)) {
9828                    return;
9829                }
9830            }
9831            final PackageParser.Package p = mPackages.get(packageName);
9832            if (p == null) {
9833                return;
9834            }
9835            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9836        }
9837    }
9838
9839    @Override
9840    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9841            List<String> classPaths, String loaderIsa) {
9842        int userId = UserHandle.getCallingUserId();
9843        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9844        if (ai == null) {
9845            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9846                + loadingPackageName + ", user=" + userId);
9847            return;
9848        }
9849        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9850    }
9851
9852    @Override
9853    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9854            IDexModuleRegisterCallback callback) {
9855        int userId = UserHandle.getCallingUserId();
9856        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9857        DexManager.RegisterDexModuleResult result;
9858        if (ai == null) {
9859            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9860                     " calling user. package=" + packageName + ", user=" + userId);
9861            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9862        } else {
9863            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9864        }
9865
9866        if (callback != null) {
9867            mHandler.post(() -> {
9868                try {
9869                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9870                } catch (RemoteException e) {
9871                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9872                }
9873            });
9874        }
9875    }
9876
9877    /**
9878     * Ask the package manager to perform a dex-opt with the given compiler filter.
9879     *
9880     * Note: exposed only for the shell command to allow moving packages explicitly to a
9881     *       definite state.
9882     */
9883    @Override
9884    public boolean performDexOptMode(String packageName,
9885            boolean checkProfiles, String targetCompilerFilter, boolean force,
9886            boolean bootComplete, String splitName) {
9887        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9888                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9889                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9890        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9891                splitName, flags));
9892    }
9893
9894    /**
9895     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9896     * secondary dex files belonging to the given package.
9897     *
9898     * Note: exposed only for the shell command to allow moving packages explicitly to a
9899     *       definite state.
9900     */
9901    @Override
9902    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9903            boolean force) {
9904        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9905                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9906                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9907                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9908        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9909    }
9910
9911    /*package*/ boolean performDexOpt(DexoptOptions options) {
9912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9913            return false;
9914        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9915            return false;
9916        }
9917
9918        if (options.isDexoptOnlySecondaryDex()) {
9919            return mDexManager.dexoptSecondaryDex(options);
9920        } else {
9921            int dexoptStatus = performDexOptWithStatus(options);
9922            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9923        }
9924    }
9925
9926    /**
9927     * Perform dexopt on the given package and return one of following result:
9928     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9929     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9930     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9931     */
9932    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9933        return performDexOptTraced(options);
9934    }
9935
9936    private int performDexOptTraced(DexoptOptions options) {
9937        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9938        try {
9939            return performDexOptInternal(options);
9940        } finally {
9941            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9942        }
9943    }
9944
9945    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9946    // if the package can now be considered up to date for the given filter.
9947    private int performDexOptInternal(DexoptOptions options) {
9948        PackageParser.Package p;
9949        synchronized (mPackages) {
9950            p = mPackages.get(options.getPackageName());
9951            if (p == null) {
9952                // Package could not be found. Report failure.
9953                return PackageDexOptimizer.DEX_OPT_FAILED;
9954            }
9955            mPackageUsage.maybeWriteAsync(mPackages);
9956            mCompilerStats.maybeWriteAsync();
9957        }
9958        long callingId = Binder.clearCallingIdentity();
9959        try {
9960            synchronized (mInstallLock) {
9961                return performDexOptInternalWithDependenciesLI(p, options);
9962            }
9963        } finally {
9964            Binder.restoreCallingIdentity(callingId);
9965        }
9966    }
9967
9968    public ArraySet<String> getOptimizablePackages() {
9969        ArraySet<String> pkgs = new ArraySet<String>();
9970        synchronized (mPackages) {
9971            for (PackageParser.Package p : mPackages.values()) {
9972                if (PackageDexOptimizer.canOptimizePackage(p)) {
9973                    pkgs.add(p.packageName);
9974                }
9975            }
9976        }
9977        return pkgs;
9978    }
9979
9980    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9981            DexoptOptions options) {
9982        // Select the dex optimizer based on the force parameter.
9983        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9984        //       allocate an object here.
9985        PackageDexOptimizer pdo = options.isForce()
9986                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9987                : mPackageDexOptimizer;
9988
9989        // Dexopt all dependencies first. Note: we ignore the return value and march on
9990        // on errors.
9991        // Note that we are going to call performDexOpt on those libraries as many times as
9992        // they are referenced in packages. When we do a batch of performDexOpt (for example
9993        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9994        // and the first package that uses the library will dexopt it. The
9995        // others will see that the compiled code for the library is up to date.
9996        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9997        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9998        if (!deps.isEmpty()) {
9999            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10000                    options.getCompilerFilter(), options.getSplitName(),
10001                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10002            for (PackageParser.Package depPackage : deps) {
10003                // TODO: Analyze and investigate if we (should) profile libraries.
10004                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10005                        getOrCreateCompilerPackageStats(depPackage),
10006                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10007            }
10008        }
10009        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10010                getOrCreateCompilerPackageStats(p),
10011                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10012    }
10013
10014    /**
10015     * Reconcile the information we have about the secondary dex files belonging to
10016     * {@code packagName} and the actual dex files. For all dex files that were
10017     * deleted, update the internal records and delete the generated oat files.
10018     */
10019    @Override
10020    public void reconcileSecondaryDexFiles(String packageName) {
10021        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10022            return;
10023        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10024            return;
10025        }
10026        mDexManager.reconcileSecondaryDexFiles(packageName);
10027    }
10028
10029    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10030    // a reference there.
10031    /*package*/ DexManager getDexManager() {
10032        return mDexManager;
10033    }
10034
10035    /**
10036     * Execute the background dexopt job immediately.
10037     */
10038    @Override
10039    public boolean runBackgroundDexoptJob() {
10040        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10041            return false;
10042        }
10043        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10044    }
10045
10046    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10047        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10048                || p.usesStaticLibraries != null) {
10049            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10050            Set<String> collectedNames = new HashSet<>();
10051            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10052
10053            retValue.remove(p);
10054
10055            return retValue;
10056        } else {
10057            return Collections.emptyList();
10058        }
10059    }
10060
10061    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10062            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10063        if (!collectedNames.contains(p.packageName)) {
10064            collectedNames.add(p.packageName);
10065            collected.add(p);
10066
10067            if (p.usesLibraries != null) {
10068                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10069                        null, collected, collectedNames);
10070            }
10071            if (p.usesOptionalLibraries != null) {
10072                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10073                        null, collected, collectedNames);
10074            }
10075            if (p.usesStaticLibraries != null) {
10076                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10077                        p.usesStaticLibrariesVersions, collected, collectedNames);
10078            }
10079        }
10080    }
10081
10082    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10083            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10084        final int libNameCount = libs.size();
10085        for (int i = 0; i < libNameCount; i++) {
10086            String libName = libs.get(i);
10087            int version = (versions != null && versions.length == libNameCount)
10088                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10089            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10090            if (libPkg != null) {
10091                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10092            }
10093        }
10094    }
10095
10096    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10097        synchronized (mPackages) {
10098            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10099            if (libEntry != null) {
10100                return mPackages.get(libEntry.apk);
10101            }
10102            return null;
10103        }
10104    }
10105
10106    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10107        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10108        if (versionedLib == null) {
10109            return null;
10110        }
10111        return versionedLib.get(version);
10112    }
10113
10114    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10115        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10116                pkg.staticSharedLibName);
10117        if (versionedLib == null) {
10118            return null;
10119        }
10120        int previousLibVersion = -1;
10121        final int versionCount = versionedLib.size();
10122        for (int i = 0; i < versionCount; i++) {
10123            final int libVersion = versionedLib.keyAt(i);
10124            if (libVersion < pkg.staticSharedLibVersion) {
10125                previousLibVersion = Math.max(previousLibVersion, libVersion);
10126            }
10127        }
10128        if (previousLibVersion >= 0) {
10129            return versionedLib.get(previousLibVersion);
10130        }
10131        return null;
10132    }
10133
10134    public void shutdown() {
10135        mPackageUsage.writeNow(mPackages);
10136        mCompilerStats.writeNow();
10137        mDexManager.writePackageDexUsageNow();
10138    }
10139
10140    @Override
10141    public void dumpProfiles(String packageName) {
10142        PackageParser.Package pkg;
10143        synchronized (mPackages) {
10144            pkg = mPackages.get(packageName);
10145            if (pkg == null) {
10146                throw new IllegalArgumentException("Unknown package: " + packageName);
10147            }
10148        }
10149        /* Only the shell, root, or the app user should be able to dump profiles. */
10150        int callingUid = Binder.getCallingUid();
10151        if (callingUid != Process.SHELL_UID &&
10152            callingUid != Process.ROOT_UID &&
10153            callingUid != pkg.applicationInfo.uid) {
10154            throw new SecurityException("dumpProfiles");
10155        }
10156
10157        synchronized (mInstallLock) {
10158            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10159            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10160            try {
10161                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10162                String codePaths = TextUtils.join(";", allCodePaths);
10163                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10164            } catch (InstallerException e) {
10165                Slog.w(TAG, "Failed to dump profiles", e);
10166            }
10167            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10168        }
10169    }
10170
10171    @Override
10172    public void forceDexOpt(String packageName) {
10173        enforceSystemOrRoot("forceDexOpt");
10174
10175        PackageParser.Package pkg;
10176        synchronized (mPackages) {
10177            pkg = mPackages.get(packageName);
10178            if (pkg == null) {
10179                throw new IllegalArgumentException("Unknown package: " + packageName);
10180            }
10181        }
10182
10183        synchronized (mInstallLock) {
10184            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10185
10186            // Whoever is calling forceDexOpt wants a compiled package.
10187            // Don't use profiles since that may cause compilation to be skipped.
10188            final int res = performDexOptInternalWithDependenciesLI(
10189                    pkg,
10190                    new DexoptOptions(packageName,
10191                            getDefaultCompilerFilter(),
10192                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10193
10194            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10195            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10196                throw new IllegalStateException("Failed to dexopt: " + res);
10197            }
10198        }
10199    }
10200
10201    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10202        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10203            Slog.w(TAG, "Unable to update from " + oldPkg.name
10204                    + " to " + newPkg.packageName
10205                    + ": old package not in system partition");
10206            return false;
10207        } else if (mPackages.get(oldPkg.name) != null) {
10208            Slog.w(TAG, "Unable to update from " + oldPkg.name
10209                    + " to " + newPkg.packageName
10210                    + ": old package still exists");
10211            return false;
10212        }
10213        return true;
10214    }
10215
10216    void removeCodePathLI(File codePath) {
10217        if (codePath.isDirectory()) {
10218            try {
10219                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10220            } catch (InstallerException e) {
10221                Slog.w(TAG, "Failed to remove code path", e);
10222            }
10223        } else {
10224            codePath.delete();
10225        }
10226    }
10227
10228    private int[] resolveUserIds(int userId) {
10229        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10230    }
10231
10232    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10233        if (pkg == null) {
10234            Slog.wtf(TAG, "Package was null!", new Throwable());
10235            return;
10236        }
10237        clearAppDataLeafLIF(pkg, userId, flags);
10238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10239        for (int i = 0; i < childCount; i++) {
10240            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10241        }
10242    }
10243
10244    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10245        final PackageSetting ps;
10246        synchronized (mPackages) {
10247            ps = mSettings.mPackages.get(pkg.packageName);
10248        }
10249        for (int realUserId : resolveUserIds(userId)) {
10250            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10251            try {
10252                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10253                        ceDataInode);
10254            } catch (InstallerException e) {
10255                Slog.w(TAG, String.valueOf(e));
10256            }
10257        }
10258    }
10259
10260    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10261        if (pkg == null) {
10262            Slog.wtf(TAG, "Package was null!", new Throwable());
10263            return;
10264        }
10265        destroyAppDataLeafLIF(pkg, userId, flags);
10266        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10267        for (int i = 0; i < childCount; i++) {
10268            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10269        }
10270    }
10271
10272    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10273        final PackageSetting ps;
10274        synchronized (mPackages) {
10275            ps = mSettings.mPackages.get(pkg.packageName);
10276        }
10277        for (int realUserId : resolveUserIds(userId)) {
10278            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10279            try {
10280                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10281                        ceDataInode);
10282            } catch (InstallerException e) {
10283                Slog.w(TAG, String.valueOf(e));
10284            }
10285            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10286        }
10287    }
10288
10289    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10290        if (pkg == null) {
10291            Slog.wtf(TAG, "Package was null!", new Throwable());
10292            return;
10293        }
10294        destroyAppProfilesLeafLIF(pkg);
10295        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10296        for (int i = 0; i < childCount; i++) {
10297            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10298        }
10299    }
10300
10301    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10302        try {
10303            mInstaller.destroyAppProfiles(pkg.packageName);
10304        } catch (InstallerException e) {
10305            Slog.w(TAG, String.valueOf(e));
10306        }
10307    }
10308
10309    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10310        if (pkg == null) {
10311            Slog.wtf(TAG, "Package was null!", new Throwable());
10312            return;
10313        }
10314        clearAppProfilesLeafLIF(pkg);
10315        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10316        for (int i = 0; i < childCount; i++) {
10317            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10318        }
10319    }
10320
10321    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10322        try {
10323            mInstaller.clearAppProfiles(pkg.packageName);
10324        } catch (InstallerException e) {
10325            Slog.w(TAG, String.valueOf(e));
10326        }
10327    }
10328
10329    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10330            long lastUpdateTime) {
10331        // Set parent install/update time
10332        PackageSetting ps = (PackageSetting) pkg.mExtras;
10333        if (ps != null) {
10334            ps.firstInstallTime = firstInstallTime;
10335            ps.lastUpdateTime = lastUpdateTime;
10336        }
10337        // Set children install/update time
10338        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10339        for (int i = 0; i < childCount; i++) {
10340            PackageParser.Package childPkg = pkg.childPackages.get(i);
10341            ps = (PackageSetting) childPkg.mExtras;
10342            if (ps != null) {
10343                ps.firstInstallTime = firstInstallTime;
10344                ps.lastUpdateTime = lastUpdateTime;
10345            }
10346        }
10347    }
10348
10349    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10350            PackageParser.Package changingLib) {
10351        if (file.path != null) {
10352            usesLibraryFiles.add(file.path);
10353            return;
10354        }
10355        PackageParser.Package p = mPackages.get(file.apk);
10356        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10357            // If we are doing this while in the middle of updating a library apk,
10358            // then we need to make sure to use that new apk for determining the
10359            // dependencies here.  (We haven't yet finished committing the new apk
10360            // to the package manager state.)
10361            if (p == null || p.packageName.equals(changingLib.packageName)) {
10362                p = changingLib;
10363            }
10364        }
10365        if (p != null) {
10366            usesLibraryFiles.addAll(p.getAllCodePaths());
10367            if (p.usesLibraryFiles != null) {
10368                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10369            }
10370        }
10371    }
10372
10373    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10374            PackageParser.Package changingLib) throws PackageManagerException {
10375        if (pkg == null) {
10376            return;
10377        }
10378        ArraySet<String> usesLibraryFiles = null;
10379        if (pkg.usesLibraries != null) {
10380            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10381                    null, null, pkg.packageName, changingLib, true, null);
10382        }
10383        if (pkg.usesStaticLibraries != null) {
10384            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10385                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10386                    pkg.packageName, changingLib, true, usesLibraryFiles);
10387        }
10388        if (pkg.usesOptionalLibraries != null) {
10389            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10390                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10391        }
10392        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10393            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10394        } else {
10395            pkg.usesLibraryFiles = null;
10396        }
10397    }
10398
10399    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10400            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10401            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10402            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10403            throws PackageManagerException {
10404        final int libCount = requestedLibraries.size();
10405        for (int i = 0; i < libCount; i++) {
10406            final String libName = requestedLibraries.get(i);
10407            final int libVersion = requiredVersions != null ? requiredVersions[i]
10408                    : SharedLibraryInfo.VERSION_UNDEFINED;
10409            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10410            if (libEntry == null) {
10411                if (required) {
10412                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10413                            "Package " + packageName + " requires unavailable shared library "
10414                                    + libName + "; failing!");
10415                } else if (DEBUG_SHARED_LIBRARIES) {
10416                    Slog.i(TAG, "Package " + packageName
10417                            + " desires unavailable shared library "
10418                            + libName + "; ignoring!");
10419                }
10420            } else {
10421                if (requiredVersions != null && requiredCertDigests != null) {
10422                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10423                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10424                            "Package " + packageName + " requires unavailable static shared"
10425                                    + " library " + libName + " version "
10426                                    + libEntry.info.getVersion() + "; failing!");
10427                    }
10428
10429                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10430                    if (libPkg == null) {
10431                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10432                                "Package " + packageName + " requires unavailable static shared"
10433                                        + " library; failing!");
10434                    }
10435
10436                    String expectedCertDigest = requiredCertDigests[i];
10437                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10438                                libPkg.mSignatures[0]);
10439                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10440                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10441                                "Package " + packageName + " requires differently signed" +
10442                                        " static shared library; failing!");
10443                    }
10444                }
10445
10446                if (outUsedLibraries == null) {
10447                    outUsedLibraries = new ArraySet<>();
10448                }
10449                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10450            }
10451        }
10452        return outUsedLibraries;
10453    }
10454
10455    private static boolean hasString(List<String> list, List<String> which) {
10456        if (list == null) {
10457            return false;
10458        }
10459        for (int i=list.size()-1; i>=0; i--) {
10460            for (int j=which.size()-1; j>=0; j--) {
10461                if (which.get(j).equals(list.get(i))) {
10462                    return true;
10463                }
10464            }
10465        }
10466        return false;
10467    }
10468
10469    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10470            PackageParser.Package changingPkg) {
10471        ArrayList<PackageParser.Package> res = null;
10472        for (PackageParser.Package pkg : mPackages.values()) {
10473            if (changingPkg != null
10474                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10475                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10476                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10477                            changingPkg.staticSharedLibName)) {
10478                return null;
10479            }
10480            if (res == null) {
10481                res = new ArrayList<>();
10482            }
10483            res.add(pkg);
10484            try {
10485                updateSharedLibrariesLPr(pkg, changingPkg);
10486            } catch (PackageManagerException e) {
10487                // If a system app update or an app and a required lib missing we
10488                // delete the package and for updated system apps keep the data as
10489                // it is better for the user to reinstall than to be in an limbo
10490                // state. Also libs disappearing under an app should never happen
10491                // - just in case.
10492                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10493                    final int flags = pkg.isUpdatedSystemApp()
10494                            ? PackageManager.DELETE_KEEP_DATA : 0;
10495                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10496                            flags , null, true, null);
10497                }
10498                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10499            }
10500        }
10501        return res;
10502    }
10503
10504    /**
10505     * Derive the value of the {@code cpuAbiOverride} based on the provided
10506     * value and an optional stored value from the package settings.
10507     */
10508    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10509        String cpuAbiOverride = null;
10510
10511        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10512            cpuAbiOverride = null;
10513        } else if (abiOverride != null) {
10514            cpuAbiOverride = abiOverride;
10515        } else if (settings != null) {
10516            cpuAbiOverride = settings.cpuAbiOverrideString;
10517        }
10518
10519        return cpuAbiOverride;
10520    }
10521
10522    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10523            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10524                    throws PackageManagerException {
10525        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10526        // If the package has children and this is the first dive in the function
10527        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10528        // whether all packages (parent and children) would be successfully scanned
10529        // before the actual scan since scanning mutates internal state and we want
10530        // to atomically install the package and its children.
10531        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10532            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10533                scanFlags |= SCAN_CHECK_ONLY;
10534            }
10535        } else {
10536            scanFlags &= ~SCAN_CHECK_ONLY;
10537        }
10538
10539        final PackageParser.Package scannedPkg;
10540        try {
10541            // Scan the parent
10542            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10543            // Scan the children
10544            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10545            for (int i = 0; i < childCount; i++) {
10546                PackageParser.Package childPkg = pkg.childPackages.get(i);
10547                scanPackageLI(childPkg, policyFlags,
10548                        scanFlags, currentTime, user);
10549            }
10550        } finally {
10551            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10552        }
10553
10554        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10555            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10556        }
10557
10558        return scannedPkg;
10559    }
10560
10561    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10562            int scanFlags, long currentTime, @Nullable UserHandle user)
10563                    throws PackageManagerException {
10564        boolean success = false;
10565        try {
10566            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10567                    currentTime, user);
10568            success = true;
10569            return res;
10570        } finally {
10571            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10572                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10573                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10574                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10575                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10576            }
10577        }
10578    }
10579
10580    /**
10581     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10582     */
10583    private static boolean apkHasCode(String fileName) {
10584        StrictJarFile jarFile = null;
10585        try {
10586            jarFile = new StrictJarFile(fileName,
10587                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10588            return jarFile.findEntry("classes.dex") != null;
10589        } catch (IOException ignore) {
10590        } finally {
10591            try {
10592                if (jarFile != null) {
10593                    jarFile.close();
10594                }
10595            } catch (IOException ignore) {}
10596        }
10597        return false;
10598    }
10599
10600    /**
10601     * Enforces code policy for the package. This ensures that if an APK has
10602     * declared hasCode="true" in its manifest that the APK actually contains
10603     * code.
10604     *
10605     * @throws PackageManagerException If bytecode could not be found when it should exist
10606     */
10607    private static void assertCodePolicy(PackageParser.Package pkg)
10608            throws PackageManagerException {
10609        final boolean shouldHaveCode =
10610                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10611        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10612            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10613                    "Package " + pkg.baseCodePath + " code is missing");
10614        }
10615
10616        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10617            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10618                final boolean splitShouldHaveCode =
10619                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10620                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10621                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10622                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10623                }
10624            }
10625        }
10626    }
10627
10628    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10629            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10630                    throws PackageManagerException {
10631        if (DEBUG_PACKAGE_SCANNING) {
10632            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10633                Log.d(TAG, "Scanning package " + pkg.packageName);
10634        }
10635
10636        applyPolicy(pkg, policyFlags);
10637
10638        assertPackageIsValid(pkg, policyFlags, scanFlags);
10639
10640        // Initialize package source and resource directories
10641        final File scanFile = new File(pkg.codePath);
10642        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10643        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10644
10645        SharedUserSetting suid = null;
10646        PackageSetting pkgSetting = null;
10647
10648        // Getting the package setting may have a side-effect, so if we
10649        // are only checking if scan would succeed, stash a copy of the
10650        // old setting to restore at the end.
10651        PackageSetting nonMutatedPs = null;
10652
10653        // We keep references to the derived CPU Abis from settings in oder to reuse
10654        // them in the case where we're not upgrading or booting for the first time.
10655        String primaryCpuAbiFromSettings = null;
10656        String secondaryCpuAbiFromSettings = null;
10657
10658        // writer
10659        synchronized (mPackages) {
10660            if (pkg.mSharedUserId != null) {
10661                // SIDE EFFECTS; may potentially allocate a new shared user
10662                suid = mSettings.getSharedUserLPw(
10663                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10664                if (DEBUG_PACKAGE_SCANNING) {
10665                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10666                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10667                                + "): packages=" + suid.packages);
10668                }
10669            }
10670
10671            // Check if we are renaming from an original package name.
10672            PackageSetting origPackage = null;
10673            String realName = null;
10674            if (pkg.mOriginalPackages != null) {
10675                // This package may need to be renamed to a previously
10676                // installed name.  Let's check on that...
10677                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10678                if (pkg.mOriginalPackages.contains(renamed)) {
10679                    // This package had originally been installed as the
10680                    // original name, and we have already taken care of
10681                    // transitioning to the new one.  Just update the new
10682                    // one to continue using the old name.
10683                    realName = pkg.mRealPackage;
10684                    if (!pkg.packageName.equals(renamed)) {
10685                        // Callers into this function may have already taken
10686                        // care of renaming the package; only do it here if
10687                        // it is not already done.
10688                        pkg.setPackageName(renamed);
10689                    }
10690                } else {
10691                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10692                        if ((origPackage = mSettings.getPackageLPr(
10693                                pkg.mOriginalPackages.get(i))) != null) {
10694                            // We do have the package already installed under its
10695                            // original name...  should we use it?
10696                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10697                                // New package is not compatible with original.
10698                                origPackage = null;
10699                                continue;
10700                            } else if (origPackage.sharedUser != null) {
10701                                // Make sure uid is compatible between packages.
10702                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10703                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10704                                            + " to " + pkg.packageName + ": old uid "
10705                                            + origPackage.sharedUser.name
10706                                            + " differs from " + pkg.mSharedUserId);
10707                                    origPackage = null;
10708                                    continue;
10709                                }
10710                                // TODO: Add case when shared user id is added [b/28144775]
10711                            } else {
10712                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10713                                        + pkg.packageName + " to old name " + origPackage.name);
10714                            }
10715                            break;
10716                        }
10717                    }
10718                }
10719            }
10720
10721            if (mTransferedPackages.contains(pkg.packageName)) {
10722                Slog.w(TAG, "Package " + pkg.packageName
10723                        + " was transferred to another, but its .apk remains");
10724            }
10725
10726            // See comments in nonMutatedPs declaration
10727            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10728                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10729                if (foundPs != null) {
10730                    nonMutatedPs = new PackageSetting(foundPs);
10731                }
10732            }
10733
10734            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10735                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10736                if (foundPs != null) {
10737                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10738                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10739                }
10740            }
10741
10742            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10743            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10744                PackageManagerService.reportSettingsProblem(Log.WARN,
10745                        "Package " + pkg.packageName + " shared user changed from "
10746                                + (pkgSetting.sharedUser != null
10747                                        ? pkgSetting.sharedUser.name : "<nothing>")
10748                                + " to "
10749                                + (suid != null ? suid.name : "<nothing>")
10750                                + "; replacing with new");
10751                pkgSetting = null;
10752            }
10753            final PackageSetting oldPkgSetting =
10754                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10755            final PackageSetting disabledPkgSetting =
10756                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10757
10758            String[] usesStaticLibraries = null;
10759            if (pkg.usesStaticLibraries != null) {
10760                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10761                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10762            }
10763
10764            if (pkgSetting == null) {
10765                final String parentPackageName = (pkg.parentPackage != null)
10766                        ? pkg.parentPackage.packageName : null;
10767                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10768                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10769                // REMOVE SharedUserSetting from method; update in a separate call
10770                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10771                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10772                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10773                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10774                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10775                        true /*allowInstall*/, instantApp, virtualPreload,
10776                        parentPackageName, pkg.getChildPackageNames(),
10777                        UserManagerService.getInstance(), usesStaticLibraries,
10778                        pkg.usesStaticLibrariesVersions);
10779                // SIDE EFFECTS; updates system state; move elsewhere
10780                if (origPackage != null) {
10781                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10782                }
10783                mSettings.addUserToSettingLPw(pkgSetting);
10784            } else {
10785                // REMOVE SharedUserSetting from method; update in a separate call.
10786                //
10787                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10788                // secondaryCpuAbi are not known at this point so we always update them
10789                // to null here, only to reset them at a later point.
10790                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10791                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10792                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10793                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10794                        UserManagerService.getInstance(), usesStaticLibraries,
10795                        pkg.usesStaticLibrariesVersions);
10796            }
10797            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10798            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10799
10800            // SIDE EFFECTS; modifies system state; move elsewhere
10801            if (pkgSetting.origPackage != null) {
10802                // If we are first transitioning from an original package,
10803                // fix up the new package's name now.  We need to do this after
10804                // looking up the package under its new name, so getPackageLP
10805                // can take care of fiddling things correctly.
10806                pkg.setPackageName(origPackage.name);
10807
10808                // File a report about this.
10809                String msg = "New package " + pkgSetting.realName
10810                        + " renamed to replace old package " + pkgSetting.name;
10811                reportSettingsProblem(Log.WARN, msg);
10812
10813                // Make a note of it.
10814                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10815                    mTransferedPackages.add(origPackage.name);
10816                }
10817
10818                // No longer need to retain this.
10819                pkgSetting.origPackage = null;
10820            }
10821
10822            // SIDE EFFECTS; modifies system state; move elsewhere
10823            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10824                // Make a note of it.
10825                mTransferedPackages.add(pkg.packageName);
10826            }
10827
10828            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10829                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10830            }
10831
10832            if ((scanFlags & SCAN_BOOTING) == 0
10833                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10834                // Check all shared libraries and map to their actual file path.
10835                // We only do this here for apps not on a system dir, because those
10836                // are the only ones that can fail an install due to this.  We
10837                // will take care of the system apps by updating all of their
10838                // library paths after the scan is done. Also during the initial
10839                // scan don't update any libs as we do this wholesale after all
10840                // apps are scanned to avoid dependency based scanning.
10841                updateSharedLibrariesLPr(pkg, null);
10842            }
10843
10844            if (mFoundPolicyFile) {
10845                SELinuxMMAC.assignSeInfoValue(pkg);
10846            }
10847            pkg.applicationInfo.uid = pkgSetting.appId;
10848            pkg.mExtras = pkgSetting;
10849
10850
10851            // Static shared libs have same package with different versions where
10852            // we internally use a synthetic package name to allow multiple versions
10853            // of the same package, therefore we need to compare signatures against
10854            // the package setting for the latest library version.
10855            PackageSetting signatureCheckPs = pkgSetting;
10856            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10857                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10858                if (libraryEntry != null) {
10859                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10860                }
10861            }
10862
10863            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10864                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10865                    // We just determined the app is signed correctly, so bring
10866                    // over the latest parsed certs.
10867                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10868                } else {
10869                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10870                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10871                                "Package " + pkg.packageName + " upgrade keys do not match the "
10872                                + "previously installed version");
10873                    } else {
10874                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10875                        String msg = "System package " + pkg.packageName
10876                                + " signature changed; retaining data.";
10877                        reportSettingsProblem(Log.WARN, msg);
10878                    }
10879                }
10880            } else {
10881                try {
10882                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10883                    verifySignaturesLP(signatureCheckPs, pkg);
10884                    // We just determined the app is signed correctly, so bring
10885                    // over the latest parsed certs.
10886                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10887                } catch (PackageManagerException e) {
10888                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10889                        throw e;
10890                    }
10891                    // The signature has changed, but this package is in the system
10892                    // image...  let's recover!
10893                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10894                    // However...  if this package is part of a shared user, but it
10895                    // doesn't match the signature of the shared user, let's fail.
10896                    // What this means is that you can't change the signatures
10897                    // associated with an overall shared user, which doesn't seem all
10898                    // that unreasonable.
10899                    if (signatureCheckPs.sharedUser != null) {
10900                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10901                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10902                            throw new PackageManagerException(
10903                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10904                                    "Signature mismatch for shared user: "
10905                                            + pkgSetting.sharedUser);
10906                        }
10907                    }
10908                    // File a report about this.
10909                    String msg = "System package " + pkg.packageName
10910                            + " signature changed; retaining data.";
10911                    reportSettingsProblem(Log.WARN, msg);
10912                }
10913            }
10914
10915            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10916                // This package wants to adopt ownership of permissions from
10917                // another package.
10918                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10919                    final String origName = pkg.mAdoptPermissions.get(i);
10920                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10921                    if (orig != null) {
10922                        if (verifyPackageUpdateLPr(orig, pkg)) {
10923                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10924                                    + pkg.packageName);
10925                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10926                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10927                        }
10928                    }
10929                }
10930            }
10931        }
10932
10933        pkg.applicationInfo.processName = fixProcessName(
10934                pkg.applicationInfo.packageName,
10935                pkg.applicationInfo.processName);
10936
10937        if (pkg != mPlatformPackage) {
10938            // Get all of our default paths setup
10939            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10940        }
10941
10942        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10943
10944        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10945            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10946                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10947                final boolean extractNativeLibs = !pkg.isLibrary();
10948                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10949                        mAppLib32InstallDir);
10950                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10951
10952                // Some system apps still use directory structure for native libraries
10953                // in which case we might end up not detecting abi solely based on apk
10954                // structure. Try to detect abi based on directory structure.
10955                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10956                        pkg.applicationInfo.primaryCpuAbi == null) {
10957                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10958                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10959                }
10960            } else {
10961                // This is not a first boot or an upgrade, don't bother deriving the
10962                // ABI during the scan. Instead, trust the value that was stored in the
10963                // package setting.
10964                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10965                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10966
10967                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10968
10969                if (DEBUG_ABI_SELECTION) {
10970                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10971                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10972                        pkg.applicationInfo.secondaryCpuAbi);
10973                }
10974            }
10975        } else {
10976            if ((scanFlags & SCAN_MOVE) != 0) {
10977                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10978                // but we already have this packages package info in the PackageSetting. We just
10979                // use that and derive the native library path based on the new codepath.
10980                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10981                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10982            }
10983
10984            // Set native library paths again. For moves, the path will be updated based on the
10985            // ABIs we've determined above. For non-moves, the path will be updated based on the
10986            // ABIs we determined during compilation, but the path will depend on the final
10987            // package path (after the rename away from the stage path).
10988            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10989        }
10990
10991        // This is a special case for the "system" package, where the ABI is
10992        // dictated by the zygote configuration (and init.rc). We should keep track
10993        // of this ABI so that we can deal with "normal" applications that run under
10994        // the same UID correctly.
10995        if (mPlatformPackage == pkg) {
10996            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10997                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10998        }
10999
11000        // If there's a mismatch between the abi-override in the package setting
11001        // and the abiOverride specified for the install. Warn about this because we
11002        // would've already compiled the app without taking the package setting into
11003        // account.
11004        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11005            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11006                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11007                        " for package " + pkg.packageName);
11008            }
11009        }
11010
11011        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11012        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11013        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11014
11015        // Copy the derived override back to the parsed package, so that we can
11016        // update the package settings accordingly.
11017        pkg.cpuAbiOverride = cpuAbiOverride;
11018
11019        if (DEBUG_ABI_SELECTION) {
11020            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11021                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11022                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11023        }
11024
11025        // Push the derived path down into PackageSettings so we know what to
11026        // clean up at uninstall time.
11027        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11028
11029        if (DEBUG_ABI_SELECTION) {
11030            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11031                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11032                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11033        }
11034
11035        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11036        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11037            // We don't do this here during boot because we can do it all
11038            // at once after scanning all existing packages.
11039            //
11040            // We also do this *before* we perform dexopt on this package, so that
11041            // we can avoid redundant dexopts, and also to make sure we've got the
11042            // code and package path correct.
11043            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11044        }
11045
11046        if (mFactoryTest && pkg.requestedPermissions.contains(
11047                android.Manifest.permission.FACTORY_TEST)) {
11048            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11049        }
11050
11051        if (isSystemApp(pkg)) {
11052            pkgSetting.isOrphaned = true;
11053        }
11054
11055        // Take care of first install / last update times.
11056        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11057        if (currentTime != 0) {
11058            if (pkgSetting.firstInstallTime == 0) {
11059                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11060            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11061                pkgSetting.lastUpdateTime = currentTime;
11062            }
11063        } else if (pkgSetting.firstInstallTime == 0) {
11064            // We need *something*.  Take time time stamp of the file.
11065            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11066        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11067            if (scanFileTime != pkgSetting.timeStamp) {
11068                // A package on the system image has changed; consider this
11069                // to be an update.
11070                pkgSetting.lastUpdateTime = scanFileTime;
11071            }
11072        }
11073        pkgSetting.setTimeStamp(scanFileTime);
11074
11075        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11076            if (nonMutatedPs != null) {
11077                synchronized (mPackages) {
11078                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11079                }
11080            }
11081        } else {
11082            final int userId = user == null ? 0 : user.getIdentifier();
11083            // Modify state for the given package setting
11084            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11085                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11086            if (pkgSetting.getInstantApp(userId)) {
11087                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11088            }
11089        }
11090        return pkg;
11091    }
11092
11093    /**
11094     * Applies policy to the parsed package based upon the given policy flags.
11095     * Ensures the package is in a good state.
11096     * <p>
11097     * Implementation detail: This method must NOT have any side effect. It would
11098     * ideally be static, but, it requires locks to read system state.
11099     */
11100    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11101        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11102            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11103            if (pkg.applicationInfo.isDirectBootAware()) {
11104                // we're direct boot aware; set for all components
11105                for (PackageParser.Service s : pkg.services) {
11106                    s.info.encryptionAware = s.info.directBootAware = true;
11107                }
11108                for (PackageParser.Provider p : pkg.providers) {
11109                    p.info.encryptionAware = p.info.directBootAware = true;
11110                }
11111                for (PackageParser.Activity a : pkg.activities) {
11112                    a.info.encryptionAware = a.info.directBootAware = true;
11113                }
11114                for (PackageParser.Activity r : pkg.receivers) {
11115                    r.info.encryptionAware = r.info.directBootAware = true;
11116                }
11117            }
11118            if (compressedFileExists(pkg.codePath)) {
11119                pkg.isStub = true;
11120            }
11121        } else {
11122            // Only allow system apps to be flagged as core apps.
11123            pkg.coreApp = false;
11124            // clear flags not applicable to regular apps
11125            pkg.applicationInfo.privateFlags &=
11126                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11127            pkg.applicationInfo.privateFlags &=
11128                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11129        }
11130        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11131
11132        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11133            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11134        }
11135
11136        if (!isSystemApp(pkg)) {
11137            // Only system apps can use these features.
11138            pkg.mOriginalPackages = null;
11139            pkg.mRealPackage = null;
11140            pkg.mAdoptPermissions = null;
11141        }
11142    }
11143
11144    /**
11145     * Asserts the parsed package is valid according to the given policy. If the
11146     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11147     * <p>
11148     * Implementation detail: This method must NOT have any side effects. It would
11149     * ideally be static, but, it requires locks to read system state.
11150     *
11151     * @throws PackageManagerException If the package fails any of the validation checks
11152     */
11153    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11154            throws PackageManagerException {
11155        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11156            assertCodePolicy(pkg);
11157        }
11158
11159        if (pkg.applicationInfo.getCodePath() == null ||
11160                pkg.applicationInfo.getResourcePath() == null) {
11161            // Bail out. The resource and code paths haven't been set.
11162            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11163                    "Code and resource paths haven't been set correctly");
11164        }
11165
11166        // Make sure we're not adding any bogus keyset info
11167        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11168        ksms.assertScannedPackageValid(pkg);
11169
11170        synchronized (mPackages) {
11171            // The special "android" package can only be defined once
11172            if (pkg.packageName.equals("android")) {
11173                if (mAndroidApplication != null) {
11174                    Slog.w(TAG, "*************************************************");
11175                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11176                    Slog.w(TAG, " codePath=" + pkg.codePath);
11177                    Slog.w(TAG, "*************************************************");
11178                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11179                            "Core android package being redefined.  Skipping.");
11180                }
11181            }
11182
11183            // A package name must be unique; don't allow duplicates
11184            if (mPackages.containsKey(pkg.packageName)) {
11185                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11186                        "Application package " + pkg.packageName
11187                        + " already installed.  Skipping duplicate.");
11188            }
11189
11190            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11191                // Static libs have a synthetic package name containing the version
11192                // but we still want the base name to be unique.
11193                if (mPackages.containsKey(pkg.manifestPackageName)) {
11194                    throw new PackageManagerException(
11195                            "Duplicate static shared lib provider package");
11196                }
11197
11198                // Static shared libraries should have at least O target SDK
11199                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11200                    throw new PackageManagerException(
11201                            "Packages declaring static-shared libs must target O SDK or higher");
11202                }
11203
11204                // Package declaring static a shared lib cannot be instant apps
11205                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11206                    throw new PackageManagerException(
11207                            "Packages declaring static-shared libs cannot be instant apps");
11208                }
11209
11210                // Package declaring static a shared lib cannot be renamed since the package
11211                // name is synthetic and apps can't code around package manager internals.
11212                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11213                    throw new PackageManagerException(
11214                            "Packages declaring static-shared libs cannot be renamed");
11215                }
11216
11217                // Package declaring static a shared lib cannot declare child packages
11218                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11219                    throw new PackageManagerException(
11220                            "Packages declaring static-shared libs cannot have child packages");
11221                }
11222
11223                // Package declaring static a shared lib cannot declare dynamic libs
11224                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11225                    throw new PackageManagerException(
11226                            "Packages declaring static-shared libs cannot declare dynamic libs");
11227                }
11228
11229                // Package declaring static a shared lib cannot declare shared users
11230                if (pkg.mSharedUserId != null) {
11231                    throw new PackageManagerException(
11232                            "Packages declaring static-shared libs cannot declare shared users");
11233                }
11234
11235                // Static shared libs cannot declare activities
11236                if (!pkg.activities.isEmpty()) {
11237                    throw new PackageManagerException(
11238                            "Static shared libs cannot declare activities");
11239                }
11240
11241                // Static shared libs cannot declare services
11242                if (!pkg.services.isEmpty()) {
11243                    throw new PackageManagerException(
11244                            "Static shared libs cannot declare services");
11245                }
11246
11247                // Static shared libs cannot declare providers
11248                if (!pkg.providers.isEmpty()) {
11249                    throw new PackageManagerException(
11250                            "Static shared libs cannot declare content providers");
11251                }
11252
11253                // Static shared libs cannot declare receivers
11254                if (!pkg.receivers.isEmpty()) {
11255                    throw new PackageManagerException(
11256                            "Static shared libs cannot declare broadcast receivers");
11257                }
11258
11259                // Static shared libs cannot declare permission groups
11260                if (!pkg.permissionGroups.isEmpty()) {
11261                    throw new PackageManagerException(
11262                            "Static shared libs cannot declare permission groups");
11263                }
11264
11265                // Static shared libs cannot declare permissions
11266                if (!pkg.permissions.isEmpty()) {
11267                    throw new PackageManagerException(
11268                            "Static shared libs cannot declare permissions");
11269                }
11270
11271                // Static shared libs cannot declare protected broadcasts
11272                if (pkg.protectedBroadcasts != null) {
11273                    throw new PackageManagerException(
11274                            "Static shared libs cannot declare protected broadcasts");
11275                }
11276
11277                // Static shared libs cannot be overlay targets
11278                if (pkg.mOverlayTarget != null) {
11279                    throw new PackageManagerException(
11280                            "Static shared libs cannot be overlay targets");
11281                }
11282
11283                // The version codes must be ordered as lib versions
11284                int minVersionCode = Integer.MIN_VALUE;
11285                int maxVersionCode = Integer.MAX_VALUE;
11286
11287                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11288                        pkg.staticSharedLibName);
11289                if (versionedLib != null) {
11290                    final int versionCount = versionedLib.size();
11291                    for (int i = 0; i < versionCount; i++) {
11292                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11293                        final int libVersionCode = libInfo.getDeclaringPackage()
11294                                .getVersionCode();
11295                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11296                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11297                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11298                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11299                        } else {
11300                            minVersionCode = maxVersionCode = libVersionCode;
11301                            break;
11302                        }
11303                    }
11304                }
11305                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11306                    throw new PackageManagerException("Static shared"
11307                            + " lib version codes must be ordered as lib versions");
11308                }
11309            }
11310
11311            // Only privileged apps and updated privileged apps can add child packages.
11312            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11313                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11314                    throw new PackageManagerException("Only privileged apps can add child "
11315                            + "packages. Ignoring package " + pkg.packageName);
11316                }
11317                final int childCount = pkg.childPackages.size();
11318                for (int i = 0; i < childCount; i++) {
11319                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11320                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11321                            childPkg.packageName)) {
11322                        throw new PackageManagerException("Can't override child of "
11323                                + "another disabled app. Ignoring package " + pkg.packageName);
11324                    }
11325                }
11326            }
11327
11328            // If we're only installing presumed-existing packages, require that the
11329            // scanned APK is both already known and at the path previously established
11330            // for it.  Previously unknown packages we pick up normally, but if we have an
11331            // a priori expectation about this package's install presence, enforce it.
11332            // With a singular exception for new system packages. When an OTA contains
11333            // a new system package, we allow the codepath to change from a system location
11334            // to the user-installed location. If we don't allow this change, any newer,
11335            // user-installed version of the application will be ignored.
11336            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11337                if (mExpectingBetter.containsKey(pkg.packageName)) {
11338                    logCriticalInfo(Log.WARN,
11339                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11340                } else {
11341                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11342                    if (known != null) {
11343                        if (DEBUG_PACKAGE_SCANNING) {
11344                            Log.d(TAG, "Examining " + pkg.codePath
11345                                    + " and requiring known paths " + known.codePathString
11346                                    + " & " + known.resourcePathString);
11347                        }
11348                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11349                                || !pkg.applicationInfo.getResourcePath().equals(
11350                                        known.resourcePathString)) {
11351                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11352                                    "Application package " + pkg.packageName
11353                                    + " found at " + pkg.applicationInfo.getCodePath()
11354                                    + " but expected at " + known.codePathString
11355                                    + "; ignoring.");
11356                        }
11357                    }
11358                }
11359            }
11360
11361            // Verify that this new package doesn't have any content providers
11362            // that conflict with existing packages.  Only do this if the
11363            // package isn't already installed, since we don't want to break
11364            // things that are installed.
11365            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11366                final int N = pkg.providers.size();
11367                int i;
11368                for (i=0; i<N; i++) {
11369                    PackageParser.Provider p = pkg.providers.get(i);
11370                    if (p.info.authority != null) {
11371                        String names[] = p.info.authority.split(";");
11372                        for (int j = 0; j < names.length; j++) {
11373                            if (mProvidersByAuthority.containsKey(names[j])) {
11374                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11375                                final String otherPackageName =
11376                                        ((other != null && other.getComponentName() != null) ?
11377                                                other.getComponentName().getPackageName() : "?");
11378                                throw new PackageManagerException(
11379                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11380                                        "Can't install because provider name " + names[j]
11381                                                + " (in package " + pkg.applicationInfo.packageName
11382                                                + ") is already used by " + otherPackageName);
11383                            }
11384                        }
11385                    }
11386                }
11387            }
11388        }
11389    }
11390
11391    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11392            int type, String declaringPackageName, int declaringVersionCode) {
11393        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11394        if (versionedLib == null) {
11395            versionedLib = new SparseArray<>();
11396            mSharedLibraries.put(name, versionedLib);
11397            if (type == SharedLibraryInfo.TYPE_STATIC) {
11398                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11399            }
11400        } else if (versionedLib.indexOfKey(version) >= 0) {
11401            return false;
11402        }
11403        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11404                version, type, declaringPackageName, declaringVersionCode);
11405        versionedLib.put(version, libEntry);
11406        return true;
11407    }
11408
11409    private boolean removeSharedLibraryLPw(String name, int version) {
11410        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11411        if (versionedLib == null) {
11412            return false;
11413        }
11414        final int libIdx = versionedLib.indexOfKey(version);
11415        if (libIdx < 0) {
11416            return false;
11417        }
11418        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11419        versionedLib.remove(version);
11420        if (versionedLib.size() <= 0) {
11421            mSharedLibraries.remove(name);
11422            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11423                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11424                        .getPackageName());
11425            }
11426        }
11427        return true;
11428    }
11429
11430    /**
11431     * Adds a scanned package to the system. When this method is finished, the package will
11432     * be available for query, resolution, etc...
11433     */
11434    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11435            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11436        final String pkgName = pkg.packageName;
11437        if (mCustomResolverComponentName != null &&
11438                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11439            setUpCustomResolverActivity(pkg);
11440        }
11441
11442        if (pkg.packageName.equals("android")) {
11443            synchronized (mPackages) {
11444                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11445                    // Set up information for our fall-back user intent resolution activity.
11446                    mPlatformPackage = pkg;
11447                    pkg.mVersionCode = mSdkVersion;
11448                    mAndroidApplication = pkg.applicationInfo;
11449                    if (!mResolverReplaced) {
11450                        mResolveActivity.applicationInfo = mAndroidApplication;
11451                        mResolveActivity.name = ResolverActivity.class.getName();
11452                        mResolveActivity.packageName = mAndroidApplication.packageName;
11453                        mResolveActivity.processName = "system:ui";
11454                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11455                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11456                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11457                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11458                        mResolveActivity.exported = true;
11459                        mResolveActivity.enabled = true;
11460                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11461                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11462                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11463                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11464                                | ActivityInfo.CONFIG_ORIENTATION
11465                                | ActivityInfo.CONFIG_KEYBOARD
11466                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11467                        mResolveInfo.activityInfo = mResolveActivity;
11468                        mResolveInfo.priority = 0;
11469                        mResolveInfo.preferredOrder = 0;
11470                        mResolveInfo.match = 0;
11471                        mResolveComponentName = new ComponentName(
11472                                mAndroidApplication.packageName, mResolveActivity.name);
11473                    }
11474                }
11475            }
11476        }
11477
11478        ArrayList<PackageParser.Package> clientLibPkgs = null;
11479        // writer
11480        synchronized (mPackages) {
11481            boolean hasStaticSharedLibs = false;
11482
11483            // Any app can add new static shared libraries
11484            if (pkg.staticSharedLibName != null) {
11485                // Static shared libs don't allow renaming as they have synthetic package
11486                // names to allow install of multiple versions, so use name from manifest.
11487                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11488                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11489                        pkg.manifestPackageName, pkg.mVersionCode)) {
11490                    hasStaticSharedLibs = true;
11491                } else {
11492                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11493                                + pkg.staticSharedLibName + " already exists; skipping");
11494                }
11495                // Static shared libs cannot be updated once installed since they
11496                // use synthetic package name which includes the version code, so
11497                // not need to update other packages's shared lib dependencies.
11498            }
11499
11500            if (!hasStaticSharedLibs
11501                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11502                // Only system apps can add new dynamic shared libraries.
11503                if (pkg.libraryNames != null) {
11504                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11505                        String name = pkg.libraryNames.get(i);
11506                        boolean allowed = false;
11507                        if (pkg.isUpdatedSystemApp()) {
11508                            // New library entries can only be added through the
11509                            // system image.  This is important to get rid of a lot
11510                            // of nasty edge cases: for example if we allowed a non-
11511                            // system update of the app to add a library, then uninstalling
11512                            // the update would make the library go away, and assumptions
11513                            // we made such as through app install filtering would now
11514                            // have allowed apps on the device which aren't compatible
11515                            // with it.  Better to just have the restriction here, be
11516                            // conservative, and create many fewer cases that can negatively
11517                            // impact the user experience.
11518                            final PackageSetting sysPs = mSettings
11519                                    .getDisabledSystemPkgLPr(pkg.packageName);
11520                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11521                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11522                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11523                                        allowed = true;
11524                                        break;
11525                                    }
11526                                }
11527                            }
11528                        } else {
11529                            allowed = true;
11530                        }
11531                        if (allowed) {
11532                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11533                                    SharedLibraryInfo.VERSION_UNDEFINED,
11534                                    SharedLibraryInfo.TYPE_DYNAMIC,
11535                                    pkg.packageName, pkg.mVersionCode)) {
11536                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11537                                        + name + " already exists; skipping");
11538                            }
11539                        } else {
11540                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11541                                    + name + " that is not declared on system image; skipping");
11542                        }
11543                    }
11544
11545                    if ((scanFlags & SCAN_BOOTING) == 0) {
11546                        // If we are not booting, we need to update any applications
11547                        // that are clients of our shared library.  If we are booting,
11548                        // this will all be done once the scan is complete.
11549                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11550                    }
11551                }
11552            }
11553        }
11554
11555        if ((scanFlags & SCAN_BOOTING) != 0) {
11556            // No apps can run during boot scan, so they don't need to be frozen
11557        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11558            // Caller asked to not kill app, so it's probably not frozen
11559        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11560            // Caller asked us to ignore frozen check for some reason; they
11561            // probably didn't know the package name
11562        } else {
11563            // We're doing major surgery on this package, so it better be frozen
11564            // right now to keep it from launching
11565            checkPackageFrozen(pkgName);
11566        }
11567
11568        // Also need to kill any apps that are dependent on the library.
11569        if (clientLibPkgs != null) {
11570            for (int i=0; i<clientLibPkgs.size(); i++) {
11571                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11572                killApplication(clientPkg.applicationInfo.packageName,
11573                        clientPkg.applicationInfo.uid, "update lib");
11574            }
11575        }
11576
11577        // writer
11578        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11579
11580        synchronized (mPackages) {
11581            // We don't expect installation to fail beyond this point
11582
11583            // Add the new setting to mSettings
11584            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11585            // Add the new setting to mPackages
11586            mPackages.put(pkg.applicationInfo.packageName, pkg);
11587            // Make sure we don't accidentally delete its data.
11588            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11589            while (iter.hasNext()) {
11590                PackageCleanItem item = iter.next();
11591                if (pkgName.equals(item.packageName)) {
11592                    iter.remove();
11593                }
11594            }
11595
11596            // Add the package's KeySets to the global KeySetManagerService
11597            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11598            ksms.addScannedPackageLPw(pkg);
11599
11600            int N = pkg.providers.size();
11601            StringBuilder r = null;
11602            int i;
11603            for (i=0; i<N; i++) {
11604                PackageParser.Provider p = pkg.providers.get(i);
11605                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11606                        p.info.processName);
11607                mProviders.addProvider(p);
11608                p.syncable = p.info.isSyncable;
11609                if (p.info.authority != null) {
11610                    String names[] = p.info.authority.split(";");
11611                    p.info.authority = null;
11612                    for (int j = 0; j < names.length; j++) {
11613                        if (j == 1 && p.syncable) {
11614                            // We only want the first authority for a provider to possibly be
11615                            // syncable, so if we already added this provider using a different
11616                            // authority clear the syncable flag. We copy the provider before
11617                            // changing it because the mProviders object contains a reference
11618                            // to a provider that we don't want to change.
11619                            // Only do this for the second authority since the resulting provider
11620                            // object can be the same for all future authorities for this provider.
11621                            p = new PackageParser.Provider(p);
11622                            p.syncable = false;
11623                        }
11624                        if (!mProvidersByAuthority.containsKey(names[j])) {
11625                            mProvidersByAuthority.put(names[j], p);
11626                            if (p.info.authority == null) {
11627                                p.info.authority = names[j];
11628                            } else {
11629                                p.info.authority = p.info.authority + ";" + names[j];
11630                            }
11631                            if (DEBUG_PACKAGE_SCANNING) {
11632                                if (chatty)
11633                                    Log.d(TAG, "Registered content provider: " + names[j]
11634                                            + ", className = " + p.info.name + ", isSyncable = "
11635                                            + p.info.isSyncable);
11636                            }
11637                        } else {
11638                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11639                            Slog.w(TAG, "Skipping provider name " + names[j] +
11640                                    " (in package " + pkg.applicationInfo.packageName +
11641                                    "): name already used by "
11642                                    + ((other != null && other.getComponentName() != null)
11643                                            ? other.getComponentName().getPackageName() : "?"));
11644                        }
11645                    }
11646                }
11647                if (chatty) {
11648                    if (r == null) {
11649                        r = new StringBuilder(256);
11650                    } else {
11651                        r.append(' ');
11652                    }
11653                    r.append(p.info.name);
11654                }
11655            }
11656            if (r != null) {
11657                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11658            }
11659
11660            N = pkg.services.size();
11661            r = null;
11662            for (i=0; i<N; i++) {
11663                PackageParser.Service s = pkg.services.get(i);
11664                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11665                        s.info.processName);
11666                mServices.addService(s);
11667                if (chatty) {
11668                    if (r == null) {
11669                        r = new StringBuilder(256);
11670                    } else {
11671                        r.append(' ');
11672                    }
11673                    r.append(s.info.name);
11674                }
11675            }
11676            if (r != null) {
11677                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11678            }
11679
11680            N = pkg.receivers.size();
11681            r = null;
11682            for (i=0; i<N; i++) {
11683                PackageParser.Activity a = pkg.receivers.get(i);
11684                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11685                        a.info.processName);
11686                mReceivers.addActivity(a, "receiver");
11687                if (chatty) {
11688                    if (r == null) {
11689                        r = new StringBuilder(256);
11690                    } else {
11691                        r.append(' ');
11692                    }
11693                    r.append(a.info.name);
11694                }
11695            }
11696            if (r != null) {
11697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11698            }
11699
11700            N = pkg.activities.size();
11701            r = null;
11702            for (i=0; i<N; i++) {
11703                PackageParser.Activity a = pkg.activities.get(i);
11704                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11705                        a.info.processName);
11706                mActivities.addActivity(a, "activity");
11707                if (chatty) {
11708                    if (r == null) {
11709                        r = new StringBuilder(256);
11710                    } else {
11711                        r.append(' ');
11712                    }
11713                    r.append(a.info.name);
11714                }
11715            }
11716            if (r != null) {
11717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11718            }
11719
11720            N = pkg.permissionGroups.size();
11721            r = null;
11722            for (i=0; i<N; i++) {
11723                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11724                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11725                final String curPackageName = cur == null ? null : cur.info.packageName;
11726                // Dont allow ephemeral apps to define new permission groups.
11727                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11728                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11729                            + pg.info.packageName
11730                            + " ignored: instant apps cannot define new permission groups.");
11731                    continue;
11732                }
11733                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11734                if (cur == null || isPackageUpdate) {
11735                    mPermissionGroups.put(pg.info.name, pg);
11736                    if (chatty) {
11737                        if (r == null) {
11738                            r = new StringBuilder(256);
11739                        } else {
11740                            r.append(' ');
11741                        }
11742                        if (isPackageUpdate) {
11743                            r.append("UPD:");
11744                        }
11745                        r.append(pg.info.name);
11746                    }
11747                } else {
11748                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11749                            + pg.info.packageName + " ignored: original from "
11750                            + cur.info.packageName);
11751                    if (chatty) {
11752                        if (r == null) {
11753                            r = new StringBuilder(256);
11754                        } else {
11755                            r.append(' ');
11756                        }
11757                        r.append("DUP:");
11758                        r.append(pg.info.name);
11759                    }
11760                }
11761            }
11762            if (r != null) {
11763                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11764            }
11765
11766            N = pkg.permissions.size();
11767            r = null;
11768            for (i=0; i<N; i++) {
11769                PackageParser.Permission p = pkg.permissions.get(i);
11770
11771                // Dont allow ephemeral apps to define new permissions.
11772                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11773                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11774                            + p.info.packageName
11775                            + " ignored: instant apps cannot define new permissions.");
11776                    continue;
11777                }
11778
11779                // Assume by default that we did not install this permission into the system.
11780                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11781
11782                // Now that permission groups have a special meaning, we ignore permission
11783                // groups for legacy apps to prevent unexpected behavior. In particular,
11784                // permissions for one app being granted to someone just because they happen
11785                // to be in a group defined by another app (before this had no implications).
11786                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11787                    p.group = mPermissionGroups.get(p.info.group);
11788                    // Warn for a permission in an unknown group.
11789                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11790                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11791                                + p.info.packageName + " in an unknown group " + p.info.group);
11792                    }
11793                }
11794
11795                ArrayMap<String, BasePermission> permissionMap =
11796                        p.tree ? mSettings.mPermissionTrees
11797                                : mSettings.mPermissions;
11798                BasePermission bp = permissionMap.get(p.info.name);
11799
11800                // Allow system apps to redefine non-system permissions
11801                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11802                    final boolean currentOwnerIsSystem = (bp.perm != null
11803                            && isSystemApp(bp.perm.owner));
11804                    if (isSystemApp(p.owner)) {
11805                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11806                            // It's a built-in permission and no owner, take ownership now
11807                            bp.packageSetting = pkgSetting;
11808                            bp.perm = p;
11809                            bp.uid = pkg.applicationInfo.uid;
11810                            bp.sourcePackage = p.info.packageName;
11811                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11812                        } else if (!currentOwnerIsSystem) {
11813                            String msg = "New decl " + p.owner + " of permission  "
11814                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11815                            reportSettingsProblem(Log.WARN, msg);
11816                            bp = null;
11817                        }
11818                    }
11819                }
11820
11821                if (bp == null) {
11822                    bp = new BasePermission(p.info.name, p.info.packageName,
11823                            BasePermission.TYPE_NORMAL);
11824                    permissionMap.put(p.info.name, bp);
11825                }
11826
11827                if (bp.perm == null) {
11828                    if (bp.sourcePackage == null
11829                            || bp.sourcePackage.equals(p.info.packageName)) {
11830                        BasePermission tree = findPermissionTreeLP(p.info.name);
11831                        if (tree == null
11832                                || tree.sourcePackage.equals(p.info.packageName)) {
11833                            bp.packageSetting = pkgSetting;
11834                            bp.perm = p;
11835                            bp.uid = pkg.applicationInfo.uid;
11836                            bp.sourcePackage = p.info.packageName;
11837                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11838                            if (chatty) {
11839                                if (r == null) {
11840                                    r = new StringBuilder(256);
11841                                } else {
11842                                    r.append(' ');
11843                                }
11844                                r.append(p.info.name);
11845                            }
11846                        } else {
11847                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11848                                    + p.info.packageName + " ignored: base tree "
11849                                    + tree.name + " is from package "
11850                                    + tree.sourcePackage);
11851                        }
11852                    } else {
11853                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11854                                + p.info.packageName + " ignored: original from "
11855                                + bp.sourcePackage);
11856                    }
11857                } else if (chatty) {
11858                    if (r == null) {
11859                        r = new StringBuilder(256);
11860                    } else {
11861                        r.append(' ');
11862                    }
11863                    r.append("DUP:");
11864                    r.append(p.info.name);
11865                }
11866                if (bp.perm == p) {
11867                    bp.protectionLevel = p.info.protectionLevel;
11868                }
11869            }
11870
11871            if (r != null) {
11872                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11873            }
11874
11875            N = pkg.instrumentation.size();
11876            r = null;
11877            for (i=0; i<N; i++) {
11878                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11879                a.info.packageName = pkg.applicationInfo.packageName;
11880                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11881                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11882                a.info.splitNames = pkg.splitNames;
11883                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11884                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11885                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11886                a.info.dataDir = pkg.applicationInfo.dataDir;
11887                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11888                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11889                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11890                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11891                mInstrumentation.put(a.getComponentName(), a);
11892                if (chatty) {
11893                    if (r == null) {
11894                        r = new StringBuilder(256);
11895                    } else {
11896                        r.append(' ');
11897                    }
11898                    r.append(a.info.name);
11899                }
11900            }
11901            if (r != null) {
11902                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11903            }
11904
11905            if (pkg.protectedBroadcasts != null) {
11906                N = pkg.protectedBroadcasts.size();
11907                synchronized (mProtectedBroadcasts) {
11908                    for (i = 0; i < N; i++) {
11909                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11910                    }
11911                }
11912            }
11913        }
11914
11915        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11916    }
11917
11918    /**
11919     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11920     * is derived purely on the basis of the contents of {@code scanFile} and
11921     * {@code cpuAbiOverride}.
11922     *
11923     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11924     */
11925    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11926                                 String cpuAbiOverride, boolean extractLibs,
11927                                 File appLib32InstallDir)
11928            throws PackageManagerException {
11929        // Give ourselves some initial paths; we'll come back for another
11930        // pass once we've determined ABI below.
11931        setNativeLibraryPaths(pkg, appLib32InstallDir);
11932
11933        // We would never need to extract libs for forward-locked and external packages,
11934        // since the container service will do it for us. We shouldn't attempt to
11935        // extract libs from system app when it was not updated.
11936        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11937                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11938            extractLibs = false;
11939        }
11940
11941        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11942        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11943
11944        NativeLibraryHelper.Handle handle = null;
11945        try {
11946            handle = NativeLibraryHelper.Handle.create(pkg);
11947            // TODO(multiArch): This can be null for apps that didn't go through the
11948            // usual installation process. We can calculate it again, like we
11949            // do during install time.
11950            //
11951            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11952            // unnecessary.
11953            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11954
11955            // Null out the abis so that they can be recalculated.
11956            pkg.applicationInfo.primaryCpuAbi = null;
11957            pkg.applicationInfo.secondaryCpuAbi = null;
11958            if (isMultiArch(pkg.applicationInfo)) {
11959                // Warn if we've set an abiOverride for multi-lib packages..
11960                // By definition, we need to copy both 32 and 64 bit libraries for
11961                // such packages.
11962                if (pkg.cpuAbiOverride != null
11963                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11964                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11965                }
11966
11967                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11968                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11969                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11970                    if (extractLibs) {
11971                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11972                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11973                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11974                                useIsaSpecificSubdirs);
11975                    } else {
11976                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11977                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11978                    }
11979                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11980                }
11981
11982                // Shared library native code should be in the APK zip aligned
11983                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11984                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11985                            "Shared library native lib extraction not supported");
11986                }
11987
11988                maybeThrowExceptionForMultiArchCopy(
11989                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11990
11991                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11992                    if (extractLibs) {
11993                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11994                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11995                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11996                                useIsaSpecificSubdirs);
11997                    } else {
11998                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11999                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12000                    }
12001                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12002                }
12003
12004                maybeThrowExceptionForMultiArchCopy(
12005                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12006
12007                if (abi64 >= 0) {
12008                    // Shared library native libs should be in the APK zip aligned
12009                    if (extractLibs && pkg.isLibrary()) {
12010                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12011                                "Shared library native lib extraction not supported");
12012                    }
12013                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12014                }
12015
12016                if (abi32 >= 0) {
12017                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12018                    if (abi64 >= 0) {
12019                        if (pkg.use32bitAbi) {
12020                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12021                            pkg.applicationInfo.primaryCpuAbi = abi;
12022                        } else {
12023                            pkg.applicationInfo.secondaryCpuAbi = abi;
12024                        }
12025                    } else {
12026                        pkg.applicationInfo.primaryCpuAbi = abi;
12027                    }
12028                }
12029            } else {
12030                String[] abiList = (cpuAbiOverride != null) ?
12031                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12032
12033                // Enable gross and lame hacks for apps that are built with old
12034                // SDK tools. We must scan their APKs for renderscript bitcode and
12035                // not launch them if it's present. Don't bother checking on devices
12036                // that don't have 64 bit support.
12037                boolean needsRenderScriptOverride = false;
12038                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12039                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12040                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12041                    needsRenderScriptOverride = true;
12042                }
12043
12044                final int copyRet;
12045                if (extractLibs) {
12046                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12047                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12048                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12049                } else {
12050                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12051                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12052                }
12053                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12054
12055                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12056                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12057                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12058                }
12059
12060                if (copyRet >= 0) {
12061                    // Shared libraries that have native libs must be multi-architecture
12062                    if (pkg.isLibrary()) {
12063                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12064                                "Shared library with native libs must be multiarch");
12065                    }
12066                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12067                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12068                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12069                } else if (needsRenderScriptOverride) {
12070                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12071                }
12072            }
12073        } catch (IOException ioe) {
12074            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12075        } finally {
12076            IoUtils.closeQuietly(handle);
12077        }
12078
12079        // Now that we've calculated the ABIs and determined if it's an internal app,
12080        // we will go ahead and populate the nativeLibraryPath.
12081        setNativeLibraryPaths(pkg, appLib32InstallDir);
12082    }
12083
12084    /**
12085     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12086     * i.e, so that all packages can be run inside a single process if required.
12087     *
12088     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12089     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12090     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12091     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12092     * updating a package that belongs to a shared user.
12093     *
12094     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12095     * adds unnecessary complexity.
12096     */
12097    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12098            PackageParser.Package scannedPackage) {
12099        String requiredInstructionSet = null;
12100        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12101            requiredInstructionSet = VMRuntime.getInstructionSet(
12102                     scannedPackage.applicationInfo.primaryCpuAbi);
12103        }
12104
12105        PackageSetting requirer = null;
12106        for (PackageSetting ps : packagesForUser) {
12107            // If packagesForUser contains scannedPackage, we skip it. This will happen
12108            // when scannedPackage is an update of an existing package. Without this check,
12109            // we will never be able to change the ABI of any package belonging to a shared
12110            // user, even if it's compatible with other packages.
12111            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12112                if (ps.primaryCpuAbiString == null) {
12113                    continue;
12114                }
12115
12116                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12117                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12118                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12119                    // this but there's not much we can do.
12120                    String errorMessage = "Instruction set mismatch, "
12121                            + ((requirer == null) ? "[caller]" : requirer)
12122                            + " requires " + requiredInstructionSet + " whereas " + ps
12123                            + " requires " + instructionSet;
12124                    Slog.w(TAG, errorMessage);
12125                }
12126
12127                if (requiredInstructionSet == null) {
12128                    requiredInstructionSet = instructionSet;
12129                    requirer = ps;
12130                }
12131            }
12132        }
12133
12134        if (requiredInstructionSet != null) {
12135            String adjustedAbi;
12136            if (requirer != null) {
12137                // requirer != null implies that either scannedPackage was null or that scannedPackage
12138                // did not require an ABI, in which case we have to adjust scannedPackage to match
12139                // the ABI of the set (which is the same as requirer's ABI)
12140                adjustedAbi = requirer.primaryCpuAbiString;
12141                if (scannedPackage != null) {
12142                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12143                }
12144            } else {
12145                // requirer == null implies that we're updating all ABIs in the set to
12146                // match scannedPackage.
12147                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12148            }
12149
12150            for (PackageSetting ps : packagesForUser) {
12151                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12152                    if (ps.primaryCpuAbiString != null) {
12153                        continue;
12154                    }
12155
12156                    ps.primaryCpuAbiString = adjustedAbi;
12157                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12158                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12159                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12160                        if (DEBUG_ABI_SELECTION) {
12161                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12162                                    + " (requirer="
12163                                    + (requirer != null ? requirer.pkg : "null")
12164                                    + ", scannedPackage="
12165                                    + (scannedPackage != null ? scannedPackage : "null")
12166                                    + ")");
12167                        }
12168                        try {
12169                            mInstaller.rmdex(ps.codePathString,
12170                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12171                        } catch (InstallerException ignored) {
12172                        }
12173                    }
12174                }
12175            }
12176        }
12177    }
12178
12179    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12180        synchronized (mPackages) {
12181            mResolverReplaced = true;
12182            // Set up information for custom user intent resolution activity.
12183            mResolveActivity.applicationInfo = pkg.applicationInfo;
12184            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12185            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12186            mResolveActivity.processName = pkg.applicationInfo.packageName;
12187            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12188            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12189                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12190            mResolveActivity.theme = 0;
12191            mResolveActivity.exported = true;
12192            mResolveActivity.enabled = true;
12193            mResolveInfo.activityInfo = mResolveActivity;
12194            mResolveInfo.priority = 0;
12195            mResolveInfo.preferredOrder = 0;
12196            mResolveInfo.match = 0;
12197            mResolveComponentName = mCustomResolverComponentName;
12198            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12199                    mResolveComponentName);
12200        }
12201    }
12202
12203    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12204        if (installerActivity == null) {
12205            if (DEBUG_EPHEMERAL) {
12206                Slog.d(TAG, "Clear ephemeral installer activity");
12207            }
12208            mInstantAppInstallerActivity = null;
12209            return;
12210        }
12211
12212        if (DEBUG_EPHEMERAL) {
12213            Slog.d(TAG, "Set ephemeral installer activity: "
12214                    + installerActivity.getComponentName());
12215        }
12216        // Set up information for ephemeral installer activity
12217        mInstantAppInstallerActivity = installerActivity;
12218        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12219                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12220        mInstantAppInstallerActivity.exported = true;
12221        mInstantAppInstallerActivity.enabled = true;
12222        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12223        mInstantAppInstallerInfo.priority = 0;
12224        mInstantAppInstallerInfo.preferredOrder = 1;
12225        mInstantAppInstallerInfo.isDefault = true;
12226        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12227                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12228    }
12229
12230    private static String calculateBundledApkRoot(final String codePathString) {
12231        final File codePath = new File(codePathString);
12232        final File codeRoot;
12233        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12234            codeRoot = Environment.getRootDirectory();
12235        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12236            codeRoot = Environment.getOemDirectory();
12237        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12238            codeRoot = Environment.getVendorDirectory();
12239        } else {
12240            // Unrecognized code path; take its top real segment as the apk root:
12241            // e.g. /something/app/blah.apk => /something
12242            try {
12243                File f = codePath.getCanonicalFile();
12244                File parent = f.getParentFile();    // non-null because codePath is a file
12245                File tmp;
12246                while ((tmp = parent.getParentFile()) != null) {
12247                    f = parent;
12248                    parent = tmp;
12249                }
12250                codeRoot = f;
12251                Slog.w(TAG, "Unrecognized code path "
12252                        + codePath + " - using " + codeRoot);
12253            } catch (IOException e) {
12254                // Can't canonicalize the code path -- shenanigans?
12255                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12256                return Environment.getRootDirectory().getPath();
12257            }
12258        }
12259        return codeRoot.getPath();
12260    }
12261
12262    /**
12263     * Derive and set the location of native libraries for the given package,
12264     * which varies depending on where and how the package was installed.
12265     */
12266    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12267        final ApplicationInfo info = pkg.applicationInfo;
12268        final String codePath = pkg.codePath;
12269        final File codeFile = new File(codePath);
12270        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12271        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12272
12273        info.nativeLibraryRootDir = null;
12274        info.nativeLibraryRootRequiresIsa = false;
12275        info.nativeLibraryDir = null;
12276        info.secondaryNativeLibraryDir = null;
12277
12278        if (isApkFile(codeFile)) {
12279            // Monolithic install
12280            if (bundledApp) {
12281                // If "/system/lib64/apkname" exists, assume that is the per-package
12282                // native library directory to use; otherwise use "/system/lib/apkname".
12283                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12284                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12285                        getPrimaryInstructionSet(info));
12286
12287                // This is a bundled system app so choose the path based on the ABI.
12288                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12289                // is just the default path.
12290                final String apkName = deriveCodePathName(codePath);
12291                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12292                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12293                        apkName).getAbsolutePath();
12294
12295                if (info.secondaryCpuAbi != null) {
12296                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12297                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12298                            secondaryLibDir, apkName).getAbsolutePath();
12299                }
12300            } else if (asecApp) {
12301                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12302                        .getAbsolutePath();
12303            } else {
12304                final String apkName = deriveCodePathName(codePath);
12305                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12306                        .getAbsolutePath();
12307            }
12308
12309            info.nativeLibraryRootRequiresIsa = false;
12310            info.nativeLibraryDir = info.nativeLibraryRootDir;
12311        } else {
12312            // Cluster install
12313            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12314            info.nativeLibraryRootRequiresIsa = true;
12315
12316            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12317                    getPrimaryInstructionSet(info)).getAbsolutePath();
12318
12319            if (info.secondaryCpuAbi != null) {
12320                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12321                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12322            }
12323        }
12324    }
12325
12326    /**
12327     * Calculate the abis and roots for a bundled app. These can uniquely
12328     * be determined from the contents of the system partition, i.e whether
12329     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12330     * of this information, and instead assume that the system was built
12331     * sensibly.
12332     */
12333    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12334                                           PackageSetting pkgSetting) {
12335        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12336
12337        // If "/system/lib64/apkname" exists, assume that is the per-package
12338        // native library directory to use; otherwise use "/system/lib/apkname".
12339        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12340        setBundledAppAbi(pkg, apkRoot, apkName);
12341        // pkgSetting might be null during rescan following uninstall of updates
12342        // to a bundled app, so accommodate that possibility.  The settings in
12343        // that case will be established later from the parsed package.
12344        //
12345        // If the settings aren't null, sync them up with what we've just derived.
12346        // note that apkRoot isn't stored in the package settings.
12347        if (pkgSetting != null) {
12348            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12349            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12350        }
12351    }
12352
12353    /**
12354     * Deduces the ABI of a bundled app and sets the relevant fields on the
12355     * parsed pkg object.
12356     *
12357     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12358     *        under which system libraries are installed.
12359     * @param apkName the name of the installed package.
12360     */
12361    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12362        final File codeFile = new File(pkg.codePath);
12363
12364        final boolean has64BitLibs;
12365        final boolean has32BitLibs;
12366        if (isApkFile(codeFile)) {
12367            // Monolithic install
12368            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12369            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12370        } else {
12371            // Cluster install
12372            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12373            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12374                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12375                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12376                has64BitLibs = (new File(rootDir, isa)).exists();
12377            } else {
12378                has64BitLibs = false;
12379            }
12380            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12381                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12382                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12383                has32BitLibs = (new File(rootDir, isa)).exists();
12384            } else {
12385                has32BitLibs = false;
12386            }
12387        }
12388
12389        if (has64BitLibs && !has32BitLibs) {
12390            // The package has 64 bit libs, but not 32 bit libs. Its primary
12391            // ABI should be 64 bit. We can safely assume here that the bundled
12392            // native libraries correspond to the most preferred ABI in the list.
12393
12394            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12395            pkg.applicationInfo.secondaryCpuAbi = null;
12396        } else if (has32BitLibs && !has64BitLibs) {
12397            // The package has 32 bit libs but not 64 bit libs. Its primary
12398            // ABI should be 32 bit.
12399
12400            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12401            pkg.applicationInfo.secondaryCpuAbi = null;
12402        } else if (has32BitLibs && has64BitLibs) {
12403            // The application has both 64 and 32 bit bundled libraries. We check
12404            // here that the app declares multiArch support, and warn if it doesn't.
12405            //
12406            // We will be lenient here and record both ABIs. The primary will be the
12407            // ABI that's higher on the list, i.e, a device that's configured to prefer
12408            // 64 bit apps will see a 64 bit primary ABI,
12409
12410            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12411                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12412            }
12413
12414            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12415                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12416                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12417            } else {
12418                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12419                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12420            }
12421        } else {
12422            pkg.applicationInfo.primaryCpuAbi = null;
12423            pkg.applicationInfo.secondaryCpuAbi = null;
12424        }
12425    }
12426
12427    private void killApplication(String pkgName, int appId, String reason) {
12428        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12429    }
12430
12431    private void killApplication(String pkgName, int appId, int userId, String reason) {
12432        // Request the ActivityManager to kill the process(only for existing packages)
12433        // so that we do not end up in a confused state while the user is still using the older
12434        // version of the application while the new one gets installed.
12435        final long token = Binder.clearCallingIdentity();
12436        try {
12437            IActivityManager am = ActivityManager.getService();
12438            if (am != null) {
12439                try {
12440                    am.killApplication(pkgName, appId, userId, reason);
12441                } catch (RemoteException e) {
12442                }
12443            }
12444        } finally {
12445            Binder.restoreCallingIdentity(token);
12446        }
12447    }
12448
12449    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12450        // Remove the parent package setting
12451        PackageSetting ps = (PackageSetting) pkg.mExtras;
12452        if (ps != null) {
12453            removePackageLI(ps, chatty);
12454        }
12455        // Remove the child package setting
12456        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12457        for (int i = 0; i < childCount; i++) {
12458            PackageParser.Package childPkg = pkg.childPackages.get(i);
12459            ps = (PackageSetting) childPkg.mExtras;
12460            if (ps != null) {
12461                removePackageLI(ps, chatty);
12462            }
12463        }
12464    }
12465
12466    void removePackageLI(PackageSetting ps, boolean chatty) {
12467        if (DEBUG_INSTALL) {
12468            if (chatty)
12469                Log.d(TAG, "Removing package " + ps.name);
12470        }
12471
12472        // writer
12473        synchronized (mPackages) {
12474            mPackages.remove(ps.name);
12475            final PackageParser.Package pkg = ps.pkg;
12476            if (pkg != null) {
12477                cleanPackageDataStructuresLILPw(pkg, chatty);
12478            }
12479        }
12480    }
12481
12482    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12483        if (DEBUG_INSTALL) {
12484            if (chatty)
12485                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12486        }
12487
12488        // writer
12489        synchronized (mPackages) {
12490            // Remove the parent package
12491            mPackages.remove(pkg.applicationInfo.packageName);
12492            cleanPackageDataStructuresLILPw(pkg, chatty);
12493
12494            // Remove the child packages
12495            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12496            for (int i = 0; i < childCount; i++) {
12497                PackageParser.Package childPkg = pkg.childPackages.get(i);
12498                mPackages.remove(childPkg.applicationInfo.packageName);
12499                cleanPackageDataStructuresLILPw(childPkg, chatty);
12500            }
12501        }
12502    }
12503
12504    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12505        int N = pkg.providers.size();
12506        StringBuilder r = null;
12507        int i;
12508        for (i=0; i<N; i++) {
12509            PackageParser.Provider p = pkg.providers.get(i);
12510            mProviders.removeProvider(p);
12511            if (p.info.authority == null) {
12512
12513                /* There was another ContentProvider with this authority when
12514                 * this app was installed so this authority is null,
12515                 * Ignore it as we don't have to unregister the provider.
12516                 */
12517                continue;
12518            }
12519            String names[] = p.info.authority.split(";");
12520            for (int j = 0; j < names.length; j++) {
12521                if (mProvidersByAuthority.get(names[j]) == p) {
12522                    mProvidersByAuthority.remove(names[j]);
12523                    if (DEBUG_REMOVE) {
12524                        if (chatty)
12525                            Log.d(TAG, "Unregistered content provider: " + names[j]
12526                                    + ", className = " + p.info.name + ", isSyncable = "
12527                                    + p.info.isSyncable);
12528                    }
12529                }
12530            }
12531            if (DEBUG_REMOVE && chatty) {
12532                if (r == null) {
12533                    r = new StringBuilder(256);
12534                } else {
12535                    r.append(' ');
12536                }
12537                r.append(p.info.name);
12538            }
12539        }
12540        if (r != null) {
12541            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12542        }
12543
12544        N = pkg.services.size();
12545        r = null;
12546        for (i=0; i<N; i++) {
12547            PackageParser.Service s = pkg.services.get(i);
12548            mServices.removeService(s);
12549            if (chatty) {
12550                if (r == null) {
12551                    r = new StringBuilder(256);
12552                } else {
12553                    r.append(' ');
12554                }
12555                r.append(s.info.name);
12556            }
12557        }
12558        if (r != null) {
12559            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12560        }
12561
12562        N = pkg.receivers.size();
12563        r = null;
12564        for (i=0; i<N; i++) {
12565            PackageParser.Activity a = pkg.receivers.get(i);
12566            mReceivers.removeActivity(a, "receiver");
12567            if (DEBUG_REMOVE && chatty) {
12568                if (r == null) {
12569                    r = new StringBuilder(256);
12570                } else {
12571                    r.append(' ');
12572                }
12573                r.append(a.info.name);
12574            }
12575        }
12576        if (r != null) {
12577            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12578        }
12579
12580        N = pkg.activities.size();
12581        r = null;
12582        for (i=0; i<N; i++) {
12583            PackageParser.Activity a = pkg.activities.get(i);
12584            mActivities.removeActivity(a, "activity");
12585            if (DEBUG_REMOVE && chatty) {
12586                if (r == null) {
12587                    r = new StringBuilder(256);
12588                } else {
12589                    r.append(' ');
12590                }
12591                r.append(a.info.name);
12592            }
12593        }
12594        if (r != null) {
12595            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12596        }
12597
12598        N = pkg.permissions.size();
12599        r = null;
12600        for (i=0; i<N; i++) {
12601            PackageParser.Permission p = pkg.permissions.get(i);
12602            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12603            if (bp == null) {
12604                bp = mSettings.mPermissionTrees.get(p.info.name);
12605            }
12606            if (bp != null && bp.perm == p) {
12607                bp.perm = null;
12608                if (DEBUG_REMOVE && chatty) {
12609                    if (r == null) {
12610                        r = new StringBuilder(256);
12611                    } else {
12612                        r.append(' ');
12613                    }
12614                    r.append(p.info.name);
12615                }
12616            }
12617            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12618                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12619                if (appOpPkgs != null) {
12620                    appOpPkgs.remove(pkg.packageName);
12621                }
12622            }
12623        }
12624        if (r != null) {
12625            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12626        }
12627
12628        N = pkg.requestedPermissions.size();
12629        r = null;
12630        for (i=0; i<N; i++) {
12631            String perm = pkg.requestedPermissions.get(i);
12632            BasePermission bp = mSettings.mPermissions.get(perm);
12633            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12634                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12635                if (appOpPkgs != null) {
12636                    appOpPkgs.remove(pkg.packageName);
12637                    if (appOpPkgs.isEmpty()) {
12638                        mAppOpPermissionPackages.remove(perm);
12639                    }
12640                }
12641            }
12642        }
12643        if (r != null) {
12644            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12645        }
12646
12647        N = pkg.instrumentation.size();
12648        r = null;
12649        for (i=0; i<N; i++) {
12650            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12651            mInstrumentation.remove(a.getComponentName());
12652            if (DEBUG_REMOVE && chatty) {
12653                if (r == null) {
12654                    r = new StringBuilder(256);
12655                } else {
12656                    r.append(' ');
12657                }
12658                r.append(a.info.name);
12659            }
12660        }
12661        if (r != null) {
12662            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12663        }
12664
12665        r = null;
12666        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12667            // Only system apps can hold shared libraries.
12668            if (pkg.libraryNames != null) {
12669                for (i = 0; i < pkg.libraryNames.size(); i++) {
12670                    String name = pkg.libraryNames.get(i);
12671                    if (removeSharedLibraryLPw(name, 0)) {
12672                        if (DEBUG_REMOVE && chatty) {
12673                            if (r == null) {
12674                                r = new StringBuilder(256);
12675                            } else {
12676                                r.append(' ');
12677                            }
12678                            r.append(name);
12679                        }
12680                    }
12681                }
12682            }
12683        }
12684
12685        r = null;
12686
12687        // Any package can hold static shared libraries.
12688        if (pkg.staticSharedLibName != null) {
12689            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12690                if (DEBUG_REMOVE && chatty) {
12691                    if (r == null) {
12692                        r = new StringBuilder(256);
12693                    } else {
12694                        r.append(' ');
12695                    }
12696                    r.append(pkg.staticSharedLibName);
12697                }
12698            }
12699        }
12700
12701        if (r != null) {
12702            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12703        }
12704    }
12705
12706    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12707        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12708            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12709                return true;
12710            }
12711        }
12712        return false;
12713    }
12714
12715    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12716    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12717    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12718
12719    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12720        // Update the parent permissions
12721        updatePermissionsLPw(pkg.packageName, pkg, flags);
12722        // Update the child permissions
12723        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12724        for (int i = 0; i < childCount; i++) {
12725            PackageParser.Package childPkg = pkg.childPackages.get(i);
12726            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12727        }
12728    }
12729
12730    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12731            int flags) {
12732        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12733        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12734    }
12735
12736    private void updatePermissionsLPw(String changingPkg,
12737            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12738        // Make sure there are no dangling permission trees.
12739        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12740        while (it.hasNext()) {
12741            final BasePermission bp = it.next();
12742            if (bp.packageSetting == null) {
12743                // We may not yet have parsed the package, so just see if
12744                // we still know about its settings.
12745                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12746            }
12747            if (bp.packageSetting == null) {
12748                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12749                        + " from package " + bp.sourcePackage);
12750                it.remove();
12751            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12752                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12753                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12754                            + " from package " + bp.sourcePackage);
12755                    flags |= UPDATE_PERMISSIONS_ALL;
12756                    it.remove();
12757                }
12758            }
12759        }
12760
12761        // Make sure all dynamic permissions have been assigned to a package,
12762        // and make sure there are no dangling permissions.
12763        it = mSettings.mPermissions.values().iterator();
12764        while (it.hasNext()) {
12765            final BasePermission bp = it.next();
12766            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12767                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12768                        + bp.name + " pkg=" + bp.sourcePackage
12769                        + " info=" + bp.pendingInfo);
12770                if (bp.packageSetting == null && bp.pendingInfo != null) {
12771                    final BasePermission tree = findPermissionTreeLP(bp.name);
12772                    if (tree != null && tree.perm != null) {
12773                        bp.packageSetting = tree.packageSetting;
12774                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12775                                new PermissionInfo(bp.pendingInfo));
12776                        bp.perm.info.packageName = tree.perm.info.packageName;
12777                        bp.perm.info.name = bp.name;
12778                        bp.uid = tree.uid;
12779                    }
12780                }
12781            }
12782            if (bp.packageSetting == null) {
12783                // We may not yet have parsed the package, so just see if
12784                // we still know about its settings.
12785                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12786            }
12787            if (bp.packageSetting == null) {
12788                Slog.w(TAG, "Removing dangling permission: " + bp.name
12789                        + " from package " + bp.sourcePackage);
12790                it.remove();
12791            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12792                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12793                    Slog.i(TAG, "Removing old permission: " + bp.name
12794                            + " from package " + bp.sourcePackage);
12795                    flags |= UPDATE_PERMISSIONS_ALL;
12796                    it.remove();
12797                }
12798            }
12799        }
12800
12801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12802        // Now update the permissions for all packages, in particular
12803        // replace the granted permissions of the system packages.
12804        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12805            for (PackageParser.Package pkg : mPackages.values()) {
12806                if (pkg != pkgInfo) {
12807                    // Only replace for packages on requested volume
12808                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12809                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12810                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12811                    grantPermissionsLPw(pkg, replace, changingPkg);
12812                }
12813            }
12814        }
12815
12816        if (pkgInfo != null) {
12817            // Only replace for packages on requested volume
12818            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12819            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12820                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12821            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12822        }
12823        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12824    }
12825
12826    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12827            String packageOfInterest) {
12828        // IMPORTANT: There are two types of permissions: install and runtime.
12829        // Install time permissions are granted when the app is installed to
12830        // all device users and users added in the future. Runtime permissions
12831        // are granted at runtime explicitly to specific users. Normal and signature
12832        // protected permissions are install time permissions. Dangerous permissions
12833        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12834        // otherwise they are runtime permissions. This function does not manage
12835        // runtime permissions except for the case an app targeting Lollipop MR1
12836        // being upgraded to target a newer SDK, in which case dangerous permissions
12837        // are transformed from install time to runtime ones.
12838
12839        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12840        if (ps == null) {
12841            return;
12842        }
12843
12844        PermissionsState permissionsState = ps.getPermissionsState();
12845        PermissionsState origPermissions = permissionsState;
12846
12847        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12848
12849        boolean runtimePermissionsRevoked = false;
12850        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12851
12852        boolean changedInstallPermission = false;
12853
12854        if (replace) {
12855            ps.installPermissionsFixed = false;
12856            if (!ps.isSharedUser()) {
12857                origPermissions = new PermissionsState(permissionsState);
12858                permissionsState.reset();
12859            } else {
12860                // We need to know only about runtime permission changes since the
12861                // calling code always writes the install permissions state but
12862                // the runtime ones are written only if changed. The only cases of
12863                // changed runtime permissions here are promotion of an install to
12864                // runtime and revocation of a runtime from a shared user.
12865                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12866                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12867                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12868                    runtimePermissionsRevoked = true;
12869                }
12870            }
12871        }
12872
12873        permissionsState.setGlobalGids(mGlobalGids);
12874
12875        final int N = pkg.requestedPermissions.size();
12876        for (int i=0; i<N; i++) {
12877            final String name = pkg.requestedPermissions.get(i);
12878            final BasePermission bp = mSettings.mPermissions.get(name);
12879            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12880                    >= Build.VERSION_CODES.M;
12881
12882            if (DEBUG_INSTALL) {
12883                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12884            }
12885
12886            if (bp == null || bp.packageSetting == null) {
12887                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12888                    if (DEBUG_PERMISSIONS) {
12889                        Slog.i(TAG, "Unknown permission " + name
12890                                + " in package " + pkg.packageName);
12891                    }
12892                }
12893                continue;
12894            }
12895
12896
12897            // Limit ephemeral apps to ephemeral allowed permissions.
12898            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12899                if (DEBUG_PERMISSIONS) {
12900                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12901                            + pkg.packageName);
12902                }
12903                continue;
12904            }
12905
12906            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12907                if (DEBUG_PERMISSIONS) {
12908                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12909                            + pkg.packageName);
12910                }
12911                continue;
12912            }
12913
12914            final String perm = bp.name;
12915            boolean allowedSig = false;
12916            int grant = GRANT_DENIED;
12917
12918            // Keep track of app op permissions.
12919            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12920                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12921                if (pkgs == null) {
12922                    pkgs = new ArraySet<>();
12923                    mAppOpPermissionPackages.put(bp.name, pkgs);
12924                }
12925                pkgs.add(pkg.packageName);
12926            }
12927
12928            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12929            switch (level) {
12930                case PermissionInfo.PROTECTION_NORMAL: {
12931                    // For all apps normal permissions are install time ones.
12932                    grant = GRANT_INSTALL;
12933                } break;
12934
12935                case PermissionInfo.PROTECTION_DANGEROUS: {
12936                    // If a permission review is required for legacy apps we represent
12937                    // their permissions as always granted runtime ones since we need
12938                    // to keep the review required permission flag per user while an
12939                    // install permission's state is shared across all users.
12940                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12941                        // For legacy apps dangerous permissions are install time ones.
12942                        grant = GRANT_INSTALL;
12943                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12944                        // For legacy apps that became modern, install becomes runtime.
12945                        grant = GRANT_UPGRADE;
12946                    } else if (mPromoteSystemApps
12947                            && isSystemApp(ps)
12948                            && mExistingSystemPackages.contains(ps.name)) {
12949                        // For legacy system apps, install becomes runtime.
12950                        // We cannot check hasInstallPermission() for system apps since those
12951                        // permissions were granted implicitly and not persisted pre-M.
12952                        grant = GRANT_UPGRADE;
12953                    } else {
12954                        // For modern apps keep runtime permissions unchanged.
12955                        grant = GRANT_RUNTIME;
12956                    }
12957                } break;
12958
12959                case PermissionInfo.PROTECTION_SIGNATURE: {
12960                    // For all apps signature permissions are install time ones.
12961                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12962                    if (allowedSig) {
12963                        grant = GRANT_INSTALL;
12964                    }
12965                } break;
12966            }
12967
12968            if (DEBUG_PERMISSIONS) {
12969                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12970            }
12971
12972            if (grant != GRANT_DENIED) {
12973                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12974                    // If this is an existing, non-system package, then
12975                    // we can't add any new permissions to it.
12976                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12977                        // Except...  if this is a permission that was added
12978                        // to the platform (note: need to only do this when
12979                        // updating the platform).
12980                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12981                            grant = GRANT_DENIED;
12982                        }
12983                    }
12984                }
12985
12986                switch (grant) {
12987                    case GRANT_INSTALL: {
12988                        // Revoke this as runtime permission to handle the case of
12989                        // a runtime permission being downgraded to an install one.
12990                        // Also in permission review mode we keep dangerous permissions
12991                        // for legacy apps
12992                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12993                            if (origPermissions.getRuntimePermissionState(
12994                                    bp.name, userId) != null) {
12995                                // Revoke the runtime permission and clear the flags.
12996                                origPermissions.revokeRuntimePermission(bp, userId);
12997                                origPermissions.updatePermissionFlags(bp, userId,
12998                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12999                                // If we revoked a permission permission, we have to write.
13000                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13001                                        changedRuntimePermissionUserIds, userId);
13002                            }
13003                        }
13004                        // Grant an install permission.
13005                        if (permissionsState.grantInstallPermission(bp) !=
13006                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13007                            changedInstallPermission = true;
13008                        }
13009                    } break;
13010
13011                    case GRANT_RUNTIME: {
13012                        // Grant previously granted runtime permissions.
13013                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13014                            PermissionState permissionState = origPermissions
13015                                    .getRuntimePermissionState(bp.name, userId);
13016                            int flags = permissionState != null
13017                                    ? permissionState.getFlags() : 0;
13018                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13019                                // Don't propagate the permission in a permission review mode if
13020                                // the former was revoked, i.e. marked to not propagate on upgrade.
13021                                // Note that in a permission review mode install permissions are
13022                                // represented as constantly granted runtime ones since we need to
13023                                // keep a per user state associated with the permission. Also the
13024                                // revoke on upgrade flag is no longer applicable and is reset.
13025                                final boolean revokeOnUpgrade = (flags & PackageManager
13026                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13027                                if (revokeOnUpgrade) {
13028                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13029                                    // Since we changed the flags, we have to write.
13030                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13031                                            changedRuntimePermissionUserIds, userId);
13032                                }
13033                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13034                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13035                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13036                                        // If we cannot put the permission as it was,
13037                                        // we have to write.
13038                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13039                                                changedRuntimePermissionUserIds, userId);
13040                                    }
13041                                }
13042
13043                                // If the app supports runtime permissions no need for a review.
13044                                if (mPermissionReviewRequired
13045                                        && appSupportsRuntimePermissions
13046                                        && (flags & PackageManager
13047                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13048                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13049                                    // Since we changed the flags, we have to write.
13050                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13051                                            changedRuntimePermissionUserIds, userId);
13052                                }
13053                            } else if (mPermissionReviewRequired
13054                                    && !appSupportsRuntimePermissions) {
13055                                // For legacy apps that need a permission review, every new
13056                                // runtime permission is granted but it is pending a review.
13057                                // We also need to review only platform defined runtime
13058                                // permissions as these are the only ones the platform knows
13059                                // how to disable the API to simulate revocation as legacy
13060                                // apps don't expect to run with revoked permissions.
13061                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13062                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13063                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13064                                        // We changed the flags, hence have to write.
13065                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13066                                                changedRuntimePermissionUserIds, userId);
13067                                    }
13068                                }
13069                                if (permissionsState.grantRuntimePermission(bp, userId)
13070                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13071                                    // We changed the permission, hence have to write.
13072                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13073                                            changedRuntimePermissionUserIds, userId);
13074                                }
13075                            }
13076                            // Propagate the permission flags.
13077                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13078                        }
13079                    } break;
13080
13081                    case GRANT_UPGRADE: {
13082                        // Grant runtime permissions for a previously held install permission.
13083                        PermissionState permissionState = origPermissions
13084                                .getInstallPermissionState(bp.name);
13085                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13086
13087                        if (origPermissions.revokeInstallPermission(bp)
13088                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13089                            // We will be transferring the permission flags, so clear them.
13090                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13091                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13092                            changedInstallPermission = true;
13093                        }
13094
13095                        // If the permission is not to be promoted to runtime we ignore it and
13096                        // also its other flags as they are not applicable to install permissions.
13097                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13098                            for (int userId : currentUserIds) {
13099                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13100                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13101                                    // Transfer the permission flags.
13102                                    permissionsState.updatePermissionFlags(bp, userId,
13103                                            flags, flags);
13104                                    // If we granted the permission, we have to write.
13105                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13106                                            changedRuntimePermissionUserIds, userId);
13107                                }
13108                            }
13109                        }
13110                    } break;
13111
13112                    default: {
13113                        if (packageOfInterest == null
13114                                || packageOfInterest.equals(pkg.packageName)) {
13115                            if (DEBUG_PERMISSIONS) {
13116                                Slog.i(TAG, "Not granting permission " + perm
13117                                        + " to package " + pkg.packageName
13118                                        + " because it was previously installed without");
13119                            }
13120                        }
13121                    } break;
13122                }
13123            } else {
13124                if (permissionsState.revokeInstallPermission(bp) !=
13125                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13126                    // Also drop the permission flags.
13127                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13128                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13129                    changedInstallPermission = true;
13130                    Slog.i(TAG, "Un-granting permission " + perm
13131                            + " from package " + pkg.packageName
13132                            + " (protectionLevel=" + bp.protectionLevel
13133                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13134                            + ")");
13135                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13136                    // Don't print warning for app op permissions, since it is fine for them
13137                    // not to be granted, there is a UI for the user to decide.
13138                    if (DEBUG_PERMISSIONS
13139                            && (packageOfInterest == null
13140                                    || packageOfInterest.equals(pkg.packageName))) {
13141                        Slog.i(TAG, "Not granting permission " + perm
13142                                + " to package " + pkg.packageName
13143                                + " (protectionLevel=" + bp.protectionLevel
13144                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13145                                + ")");
13146                    }
13147                }
13148            }
13149        }
13150
13151        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13152                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13153            // This is the first that we have heard about this package, so the
13154            // permissions we have now selected are fixed until explicitly
13155            // changed.
13156            ps.installPermissionsFixed = true;
13157        }
13158
13159        // Persist the runtime permissions state for users with changes. If permissions
13160        // were revoked because no app in the shared user declares them we have to
13161        // write synchronously to avoid losing runtime permissions state.
13162        for (int userId : changedRuntimePermissionUserIds) {
13163            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13164        }
13165    }
13166
13167    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13168        boolean allowed = false;
13169        final int NP = PackageParser.NEW_PERMISSIONS.length;
13170        for (int ip=0; ip<NP; ip++) {
13171            final PackageParser.NewPermissionInfo npi
13172                    = PackageParser.NEW_PERMISSIONS[ip];
13173            if (npi.name.equals(perm)
13174                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13175                allowed = true;
13176                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13177                        + pkg.packageName);
13178                break;
13179            }
13180        }
13181        return allowed;
13182    }
13183
13184    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13185            BasePermission bp, PermissionsState origPermissions) {
13186        boolean privilegedPermission = (bp.protectionLevel
13187                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13188        boolean privappPermissionsDisable =
13189                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13190        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13191        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13192        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13193                && !platformPackage && platformPermission) {
13194            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13195                    .getPrivAppPermissions(pkg.packageName);
13196            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13197            if (!whitelisted) {
13198                Slog.w(TAG, "Privileged permission " + perm + " for package "
13199                        + pkg.packageName + " - not in privapp-permissions whitelist");
13200                // Only report violations for apps on system image
13201                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13202                    if (mPrivappPermissionsViolations == null) {
13203                        mPrivappPermissionsViolations = new ArraySet<>();
13204                    }
13205                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13206                }
13207                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13208                    return false;
13209                }
13210            }
13211        }
13212        boolean allowed = (compareSignatures(
13213                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13214                        == PackageManager.SIGNATURE_MATCH)
13215                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13216                        == PackageManager.SIGNATURE_MATCH);
13217        if (!allowed && privilegedPermission) {
13218            if (isSystemApp(pkg)) {
13219                // For updated system applications, a system permission
13220                // is granted only if it had been defined by the original application.
13221                if (pkg.isUpdatedSystemApp()) {
13222                    final PackageSetting sysPs = mSettings
13223                            .getDisabledSystemPkgLPr(pkg.packageName);
13224                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13225                        // If the original was granted this permission, we take
13226                        // that grant decision as read and propagate it to the
13227                        // update.
13228                        if (sysPs.isPrivileged()) {
13229                            allowed = true;
13230                        }
13231                    } else {
13232                        // The system apk may have been updated with an older
13233                        // version of the one on the data partition, but which
13234                        // granted a new system permission that it didn't have
13235                        // before.  In this case we do want to allow the app to
13236                        // now get the new permission if the ancestral apk is
13237                        // privileged to get it.
13238                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13239                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13240                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13241                                    allowed = true;
13242                                    break;
13243                                }
13244                            }
13245                        }
13246                        // Also if a privileged parent package on the system image or any of
13247                        // its children requested a privileged permission, the updated child
13248                        // packages can also get the permission.
13249                        if (pkg.parentPackage != null) {
13250                            final PackageSetting disabledSysParentPs = mSettings
13251                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13252                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13253                                    && disabledSysParentPs.isPrivileged()) {
13254                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13255                                    allowed = true;
13256                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13257                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13258                                    for (int i = 0; i < count; i++) {
13259                                        PackageParser.Package disabledSysChildPkg =
13260                                                disabledSysParentPs.pkg.childPackages.get(i);
13261                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13262                                                perm)) {
13263                                            allowed = true;
13264                                            break;
13265                                        }
13266                                    }
13267                                }
13268                            }
13269                        }
13270                    }
13271                } else {
13272                    allowed = isPrivilegedApp(pkg);
13273                }
13274            }
13275        }
13276        if (!allowed) {
13277            if (!allowed && (bp.protectionLevel
13278                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13279                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13280                // If this was a previously normal/dangerous permission that got moved
13281                // to a system permission as part of the runtime permission redesign, then
13282                // we still want to blindly grant it to old apps.
13283                allowed = true;
13284            }
13285            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13286                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13287                // If this permission is to be granted to the system installer and
13288                // this app is an installer, then it gets the permission.
13289                allowed = true;
13290            }
13291            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13292                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13293                // If this permission is to be granted to the system verifier and
13294                // this app is a verifier, then it gets the permission.
13295                allowed = true;
13296            }
13297            if (!allowed && (bp.protectionLevel
13298                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13299                    && isSystemApp(pkg)) {
13300                // Any pre-installed system app is allowed to get this permission.
13301                allowed = true;
13302            }
13303            if (!allowed && (bp.protectionLevel
13304                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13305                // For development permissions, a development permission
13306                // is granted only if it was already granted.
13307                allowed = origPermissions.hasInstallPermission(perm);
13308            }
13309            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13310                    && pkg.packageName.equals(mSetupWizardPackage)) {
13311                // If this permission is to be granted to the system setup wizard and
13312                // this app is a setup wizard, then it gets the permission.
13313                allowed = true;
13314            }
13315        }
13316        return allowed;
13317    }
13318
13319    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13320        final int permCount = pkg.requestedPermissions.size();
13321        for (int j = 0; j < permCount; j++) {
13322            String requestedPermission = pkg.requestedPermissions.get(j);
13323            if (permission.equals(requestedPermission)) {
13324                return true;
13325            }
13326        }
13327        return false;
13328    }
13329
13330    final class ActivityIntentResolver
13331            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13332        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13333                boolean defaultOnly, int userId) {
13334            if (!sUserManager.exists(userId)) return null;
13335            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13336            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13337        }
13338
13339        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13340                int userId) {
13341            if (!sUserManager.exists(userId)) return null;
13342            mFlags = flags;
13343            return super.queryIntent(intent, resolvedType,
13344                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13345                    userId);
13346        }
13347
13348        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13349                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13350            if (!sUserManager.exists(userId)) return null;
13351            if (packageActivities == null) {
13352                return null;
13353            }
13354            mFlags = flags;
13355            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13356            final int N = packageActivities.size();
13357            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13358                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13359
13360            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13361            for (int i = 0; i < N; ++i) {
13362                intentFilters = packageActivities.get(i).intents;
13363                if (intentFilters != null && intentFilters.size() > 0) {
13364                    PackageParser.ActivityIntentInfo[] array =
13365                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13366                    intentFilters.toArray(array);
13367                    listCut.add(array);
13368                }
13369            }
13370            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13371        }
13372
13373        /**
13374         * Finds a privileged activity that matches the specified activity names.
13375         */
13376        private PackageParser.Activity findMatchingActivity(
13377                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13378            for (PackageParser.Activity sysActivity : activityList) {
13379                if (sysActivity.info.name.equals(activityInfo.name)) {
13380                    return sysActivity;
13381                }
13382                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13383                    return sysActivity;
13384                }
13385                if (sysActivity.info.targetActivity != null) {
13386                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13387                        return sysActivity;
13388                    }
13389                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13390                        return sysActivity;
13391                    }
13392                }
13393            }
13394            return null;
13395        }
13396
13397        public class IterGenerator<E> {
13398            public Iterator<E> generate(ActivityIntentInfo info) {
13399                return null;
13400            }
13401        }
13402
13403        public class ActionIterGenerator extends IterGenerator<String> {
13404            @Override
13405            public Iterator<String> generate(ActivityIntentInfo info) {
13406                return info.actionsIterator();
13407            }
13408        }
13409
13410        public class CategoriesIterGenerator extends IterGenerator<String> {
13411            @Override
13412            public Iterator<String> generate(ActivityIntentInfo info) {
13413                return info.categoriesIterator();
13414            }
13415        }
13416
13417        public class SchemesIterGenerator extends IterGenerator<String> {
13418            @Override
13419            public Iterator<String> generate(ActivityIntentInfo info) {
13420                return info.schemesIterator();
13421            }
13422        }
13423
13424        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13425            @Override
13426            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13427                return info.authoritiesIterator();
13428            }
13429        }
13430
13431        /**
13432         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13433         * MODIFIED. Do not pass in a list that should not be changed.
13434         */
13435        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13436                IterGenerator<T> generator, Iterator<T> searchIterator) {
13437            // loop through the set of actions; every one must be found in the intent filter
13438            while (searchIterator.hasNext()) {
13439                // we must have at least one filter in the list to consider a match
13440                if (intentList.size() == 0) {
13441                    break;
13442                }
13443
13444                final T searchAction = searchIterator.next();
13445
13446                // loop through the set of intent filters
13447                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13448                while (intentIter.hasNext()) {
13449                    final ActivityIntentInfo intentInfo = intentIter.next();
13450                    boolean selectionFound = false;
13451
13452                    // loop through the intent filter's selection criteria; at least one
13453                    // of them must match the searched criteria
13454                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13455                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13456                        final T intentSelection = intentSelectionIter.next();
13457                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13458                            selectionFound = true;
13459                            break;
13460                        }
13461                    }
13462
13463                    // the selection criteria wasn't found in this filter's set; this filter
13464                    // is not a potential match
13465                    if (!selectionFound) {
13466                        intentIter.remove();
13467                    }
13468                }
13469            }
13470        }
13471
13472        private boolean isProtectedAction(ActivityIntentInfo filter) {
13473            final Iterator<String> actionsIter = filter.actionsIterator();
13474            while (actionsIter != null && actionsIter.hasNext()) {
13475                final String filterAction = actionsIter.next();
13476                if (PROTECTED_ACTIONS.contains(filterAction)) {
13477                    return true;
13478                }
13479            }
13480            return false;
13481        }
13482
13483        /**
13484         * Adjusts the priority of the given intent filter according to policy.
13485         * <p>
13486         * <ul>
13487         * <li>The priority for non privileged applications is capped to '0'</li>
13488         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13489         * <li>The priority for unbundled updates to privileged applications is capped to the
13490         *      priority defined on the system partition</li>
13491         * </ul>
13492         * <p>
13493         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13494         * allowed to obtain any priority on any action.
13495         */
13496        private void adjustPriority(
13497                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13498            // nothing to do; priority is fine as-is
13499            if (intent.getPriority() <= 0) {
13500                return;
13501            }
13502
13503            final ActivityInfo activityInfo = intent.activity.info;
13504            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13505
13506            final boolean privilegedApp =
13507                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13508            if (!privilegedApp) {
13509                // non-privileged applications can never define a priority >0
13510                if (DEBUG_FILTERS) {
13511                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13512                            + " package: " + applicationInfo.packageName
13513                            + " activity: " + intent.activity.className
13514                            + " origPrio: " + intent.getPriority());
13515                }
13516                intent.setPriority(0);
13517                return;
13518            }
13519
13520            if (systemActivities == null) {
13521                // the system package is not disabled; we're parsing the system partition
13522                if (isProtectedAction(intent)) {
13523                    if (mDeferProtectedFilters) {
13524                        // We can't deal with these just yet. No component should ever obtain a
13525                        // >0 priority for a protected actions, with ONE exception -- the setup
13526                        // wizard. The setup wizard, however, cannot be known until we're able to
13527                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13528                        // until all intent filters have been processed. Chicken, meet egg.
13529                        // Let the filter temporarily have a high priority and rectify the
13530                        // priorities after all system packages have been scanned.
13531                        mProtectedFilters.add(intent);
13532                        if (DEBUG_FILTERS) {
13533                            Slog.i(TAG, "Protected action; save for later;"
13534                                    + " package: " + applicationInfo.packageName
13535                                    + " activity: " + intent.activity.className
13536                                    + " origPrio: " + intent.getPriority());
13537                        }
13538                        return;
13539                    } else {
13540                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13541                            Slog.i(TAG, "No setup wizard;"
13542                                + " All protected intents capped to priority 0");
13543                        }
13544                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13545                            if (DEBUG_FILTERS) {
13546                                Slog.i(TAG, "Found setup wizard;"
13547                                    + " allow priority " + intent.getPriority() + ";"
13548                                    + " package: " + intent.activity.info.packageName
13549                                    + " activity: " + intent.activity.className
13550                                    + " priority: " + intent.getPriority());
13551                            }
13552                            // setup wizard gets whatever it wants
13553                            return;
13554                        }
13555                        if (DEBUG_FILTERS) {
13556                            Slog.i(TAG, "Protected action; cap priority to 0;"
13557                                    + " package: " + intent.activity.info.packageName
13558                                    + " activity: " + intent.activity.className
13559                                    + " origPrio: " + intent.getPriority());
13560                        }
13561                        intent.setPriority(0);
13562                        return;
13563                    }
13564                }
13565                // privileged apps on the system image get whatever priority they request
13566                return;
13567            }
13568
13569            // privileged app unbundled update ... try to find the same activity
13570            final PackageParser.Activity foundActivity =
13571                    findMatchingActivity(systemActivities, activityInfo);
13572            if (foundActivity == null) {
13573                // this is a new activity; it cannot obtain >0 priority
13574                if (DEBUG_FILTERS) {
13575                    Slog.i(TAG, "New activity; cap priority to 0;"
13576                            + " package: " + applicationInfo.packageName
13577                            + " activity: " + intent.activity.className
13578                            + " origPrio: " + intent.getPriority());
13579                }
13580                intent.setPriority(0);
13581                return;
13582            }
13583
13584            // found activity, now check for filter equivalence
13585
13586            // a shallow copy is enough; we modify the list, not its contents
13587            final List<ActivityIntentInfo> intentListCopy =
13588                    new ArrayList<>(foundActivity.intents);
13589            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13590
13591            // find matching action subsets
13592            final Iterator<String> actionsIterator = intent.actionsIterator();
13593            if (actionsIterator != null) {
13594                getIntentListSubset(
13595                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13596                if (intentListCopy.size() == 0) {
13597                    // no more intents to match; we're not equivalent
13598                    if (DEBUG_FILTERS) {
13599                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13600                                + " package: " + applicationInfo.packageName
13601                                + " activity: " + intent.activity.className
13602                                + " origPrio: " + intent.getPriority());
13603                    }
13604                    intent.setPriority(0);
13605                    return;
13606                }
13607            }
13608
13609            // find matching category subsets
13610            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13611            if (categoriesIterator != null) {
13612                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13613                        categoriesIterator);
13614                if (intentListCopy.size() == 0) {
13615                    // no more intents to match; we're not equivalent
13616                    if (DEBUG_FILTERS) {
13617                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13618                                + " package: " + applicationInfo.packageName
13619                                + " activity: " + intent.activity.className
13620                                + " origPrio: " + intent.getPriority());
13621                    }
13622                    intent.setPriority(0);
13623                    return;
13624                }
13625            }
13626
13627            // find matching schemes subsets
13628            final Iterator<String> schemesIterator = intent.schemesIterator();
13629            if (schemesIterator != null) {
13630                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13631                        schemesIterator);
13632                if (intentListCopy.size() == 0) {
13633                    // no more intents to match; we're not equivalent
13634                    if (DEBUG_FILTERS) {
13635                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13636                                + " package: " + applicationInfo.packageName
13637                                + " activity: " + intent.activity.className
13638                                + " origPrio: " + intent.getPriority());
13639                    }
13640                    intent.setPriority(0);
13641                    return;
13642                }
13643            }
13644
13645            // find matching authorities subsets
13646            final Iterator<IntentFilter.AuthorityEntry>
13647                    authoritiesIterator = intent.authoritiesIterator();
13648            if (authoritiesIterator != null) {
13649                getIntentListSubset(intentListCopy,
13650                        new AuthoritiesIterGenerator(),
13651                        authoritiesIterator);
13652                if (intentListCopy.size() == 0) {
13653                    // no more intents to match; we're not equivalent
13654                    if (DEBUG_FILTERS) {
13655                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13656                                + " package: " + applicationInfo.packageName
13657                                + " activity: " + intent.activity.className
13658                                + " origPrio: " + intent.getPriority());
13659                    }
13660                    intent.setPriority(0);
13661                    return;
13662                }
13663            }
13664
13665            // we found matching filter(s); app gets the max priority of all intents
13666            int cappedPriority = 0;
13667            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13668                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13669            }
13670            if (intent.getPriority() > cappedPriority) {
13671                if (DEBUG_FILTERS) {
13672                    Slog.i(TAG, "Found matching filter(s);"
13673                            + " cap priority to " + cappedPriority + ";"
13674                            + " package: " + applicationInfo.packageName
13675                            + " activity: " + intent.activity.className
13676                            + " origPrio: " + intent.getPriority());
13677                }
13678                intent.setPriority(cappedPriority);
13679                return;
13680            }
13681            // all this for nothing; the requested priority was <= what was on the system
13682        }
13683
13684        public final void addActivity(PackageParser.Activity a, String type) {
13685            mActivities.put(a.getComponentName(), a);
13686            if (DEBUG_SHOW_INFO)
13687                Log.v(
13688                TAG, "  " + type + " " +
13689                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13690            if (DEBUG_SHOW_INFO)
13691                Log.v(TAG, "    Class=" + a.info.name);
13692            final int NI = a.intents.size();
13693            for (int j=0; j<NI; j++) {
13694                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13695                if ("activity".equals(type)) {
13696                    final PackageSetting ps =
13697                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13698                    final List<PackageParser.Activity> systemActivities =
13699                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13700                    adjustPriority(systemActivities, intent);
13701                }
13702                if (DEBUG_SHOW_INFO) {
13703                    Log.v(TAG, "    IntentFilter:");
13704                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13705                }
13706                if (!intent.debugCheck()) {
13707                    Log.w(TAG, "==> For Activity " + a.info.name);
13708                }
13709                addFilter(intent);
13710            }
13711        }
13712
13713        public final void removeActivity(PackageParser.Activity a, String type) {
13714            mActivities.remove(a.getComponentName());
13715            if (DEBUG_SHOW_INFO) {
13716                Log.v(TAG, "  " + type + " "
13717                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13718                                : a.info.name) + ":");
13719                Log.v(TAG, "    Class=" + a.info.name);
13720            }
13721            final int NI = a.intents.size();
13722            for (int j=0; j<NI; j++) {
13723                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13724                if (DEBUG_SHOW_INFO) {
13725                    Log.v(TAG, "    IntentFilter:");
13726                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13727                }
13728                removeFilter(intent);
13729            }
13730        }
13731
13732        @Override
13733        protected boolean allowFilterResult(
13734                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13735            ActivityInfo filterAi = filter.activity.info;
13736            for (int i=dest.size()-1; i>=0; i--) {
13737                ActivityInfo destAi = dest.get(i).activityInfo;
13738                if (destAi.name == filterAi.name
13739                        && destAi.packageName == filterAi.packageName) {
13740                    return false;
13741                }
13742            }
13743            return true;
13744        }
13745
13746        @Override
13747        protected ActivityIntentInfo[] newArray(int size) {
13748            return new ActivityIntentInfo[size];
13749        }
13750
13751        @Override
13752        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13753            if (!sUserManager.exists(userId)) return true;
13754            PackageParser.Package p = filter.activity.owner;
13755            if (p != null) {
13756                PackageSetting ps = (PackageSetting)p.mExtras;
13757                if (ps != null) {
13758                    // System apps are never considered stopped for purposes of
13759                    // filtering, because there may be no way for the user to
13760                    // actually re-launch them.
13761                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13762                            && ps.getStopped(userId);
13763                }
13764            }
13765            return false;
13766        }
13767
13768        @Override
13769        protected boolean isPackageForFilter(String packageName,
13770                PackageParser.ActivityIntentInfo info) {
13771            return packageName.equals(info.activity.owner.packageName);
13772        }
13773
13774        @Override
13775        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13776                int match, int userId) {
13777            if (!sUserManager.exists(userId)) return null;
13778            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13779                return null;
13780            }
13781            final PackageParser.Activity activity = info.activity;
13782            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13783            if (ps == null) {
13784                return null;
13785            }
13786            final PackageUserState userState = ps.readUserState(userId);
13787            ActivityInfo ai =
13788                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13789            if (ai == null) {
13790                return null;
13791            }
13792            final boolean matchExplicitlyVisibleOnly =
13793                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13794            final boolean matchVisibleToInstantApp =
13795                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13796            final boolean componentVisible =
13797                    matchVisibleToInstantApp
13798                    && info.isVisibleToInstantApp()
13799                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13800            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13801            // throw out filters that aren't visible to ephemeral apps
13802            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13803                return null;
13804            }
13805            // throw out instant app filters if we're not explicitly requesting them
13806            if (!matchInstantApp && userState.instantApp) {
13807                return null;
13808            }
13809            // throw out instant app filters if updates are available; will trigger
13810            // instant app resolution
13811            if (userState.instantApp && ps.isUpdateAvailable()) {
13812                return null;
13813            }
13814            final ResolveInfo res = new ResolveInfo();
13815            res.activityInfo = ai;
13816            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13817                res.filter = info;
13818            }
13819            if (info != null) {
13820                res.handleAllWebDataURI = info.handleAllWebDataURI();
13821            }
13822            res.priority = info.getPriority();
13823            res.preferredOrder = activity.owner.mPreferredOrder;
13824            //System.out.println("Result: " + res.activityInfo.className +
13825            //                   " = " + res.priority);
13826            res.match = match;
13827            res.isDefault = info.hasDefault;
13828            res.labelRes = info.labelRes;
13829            res.nonLocalizedLabel = info.nonLocalizedLabel;
13830            if (userNeedsBadging(userId)) {
13831                res.noResourceId = true;
13832            } else {
13833                res.icon = info.icon;
13834            }
13835            res.iconResourceId = info.icon;
13836            res.system = res.activityInfo.applicationInfo.isSystemApp();
13837            res.isInstantAppAvailable = userState.instantApp;
13838            return res;
13839        }
13840
13841        @Override
13842        protected void sortResults(List<ResolveInfo> results) {
13843            Collections.sort(results, mResolvePrioritySorter);
13844        }
13845
13846        @Override
13847        protected void dumpFilter(PrintWriter out, String prefix,
13848                PackageParser.ActivityIntentInfo filter) {
13849            out.print(prefix); out.print(
13850                    Integer.toHexString(System.identityHashCode(filter.activity)));
13851                    out.print(' ');
13852                    filter.activity.printComponentShortName(out);
13853                    out.print(" filter ");
13854                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13855        }
13856
13857        @Override
13858        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13859            return filter.activity;
13860        }
13861
13862        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13863            PackageParser.Activity activity = (PackageParser.Activity)label;
13864            out.print(prefix); out.print(
13865                    Integer.toHexString(System.identityHashCode(activity)));
13866                    out.print(' ');
13867                    activity.printComponentShortName(out);
13868            if (count > 1) {
13869                out.print(" ("); out.print(count); out.print(" filters)");
13870            }
13871            out.println();
13872        }
13873
13874        // Keys are String (activity class name), values are Activity.
13875        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13876                = new ArrayMap<ComponentName, PackageParser.Activity>();
13877        private int mFlags;
13878    }
13879
13880    private final class ServiceIntentResolver
13881            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13882        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13883                boolean defaultOnly, int userId) {
13884            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13885            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13886        }
13887
13888        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13889                int userId) {
13890            if (!sUserManager.exists(userId)) return null;
13891            mFlags = flags;
13892            return super.queryIntent(intent, resolvedType,
13893                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13894                    userId);
13895        }
13896
13897        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13898                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13899            if (!sUserManager.exists(userId)) return null;
13900            if (packageServices == null) {
13901                return null;
13902            }
13903            mFlags = flags;
13904            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13905            final int N = packageServices.size();
13906            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13907                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13908
13909            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13910            for (int i = 0; i < N; ++i) {
13911                intentFilters = packageServices.get(i).intents;
13912                if (intentFilters != null && intentFilters.size() > 0) {
13913                    PackageParser.ServiceIntentInfo[] array =
13914                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13915                    intentFilters.toArray(array);
13916                    listCut.add(array);
13917                }
13918            }
13919            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13920        }
13921
13922        public final void addService(PackageParser.Service s) {
13923            mServices.put(s.getComponentName(), s);
13924            if (DEBUG_SHOW_INFO) {
13925                Log.v(TAG, "  "
13926                        + (s.info.nonLocalizedLabel != null
13927                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13928                Log.v(TAG, "    Class=" + s.info.name);
13929            }
13930            final int NI = s.intents.size();
13931            int j;
13932            for (j=0; j<NI; j++) {
13933                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13934                if (DEBUG_SHOW_INFO) {
13935                    Log.v(TAG, "    IntentFilter:");
13936                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13937                }
13938                if (!intent.debugCheck()) {
13939                    Log.w(TAG, "==> For Service " + s.info.name);
13940                }
13941                addFilter(intent);
13942            }
13943        }
13944
13945        public final void removeService(PackageParser.Service s) {
13946            mServices.remove(s.getComponentName());
13947            if (DEBUG_SHOW_INFO) {
13948                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13949                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13950                Log.v(TAG, "    Class=" + s.info.name);
13951            }
13952            final int NI = s.intents.size();
13953            int j;
13954            for (j=0; j<NI; j++) {
13955                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13956                if (DEBUG_SHOW_INFO) {
13957                    Log.v(TAG, "    IntentFilter:");
13958                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13959                }
13960                removeFilter(intent);
13961            }
13962        }
13963
13964        @Override
13965        protected boolean allowFilterResult(
13966                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13967            ServiceInfo filterSi = filter.service.info;
13968            for (int i=dest.size()-1; i>=0; i--) {
13969                ServiceInfo destAi = dest.get(i).serviceInfo;
13970                if (destAi.name == filterSi.name
13971                        && destAi.packageName == filterSi.packageName) {
13972                    return false;
13973                }
13974            }
13975            return true;
13976        }
13977
13978        @Override
13979        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13980            return new PackageParser.ServiceIntentInfo[size];
13981        }
13982
13983        @Override
13984        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13985            if (!sUserManager.exists(userId)) return true;
13986            PackageParser.Package p = filter.service.owner;
13987            if (p != null) {
13988                PackageSetting ps = (PackageSetting)p.mExtras;
13989                if (ps != null) {
13990                    // System apps are never considered stopped for purposes of
13991                    // filtering, because there may be no way for the user to
13992                    // actually re-launch them.
13993                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13994                            && ps.getStopped(userId);
13995                }
13996            }
13997            return false;
13998        }
13999
14000        @Override
14001        protected boolean isPackageForFilter(String packageName,
14002                PackageParser.ServiceIntentInfo info) {
14003            return packageName.equals(info.service.owner.packageName);
14004        }
14005
14006        @Override
14007        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14008                int match, int userId) {
14009            if (!sUserManager.exists(userId)) return null;
14010            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14011            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14012                return null;
14013            }
14014            final PackageParser.Service service = info.service;
14015            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14016            if (ps == null) {
14017                return null;
14018            }
14019            final PackageUserState userState = ps.readUserState(userId);
14020            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14021                    userState, userId);
14022            if (si == null) {
14023                return null;
14024            }
14025            final boolean matchVisibleToInstantApp =
14026                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14027            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14028            // throw out filters that aren't visible to ephemeral apps
14029            if (matchVisibleToInstantApp
14030                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14031                return null;
14032            }
14033            // throw out ephemeral filters if we're not explicitly requesting them
14034            if (!isInstantApp && userState.instantApp) {
14035                return null;
14036            }
14037            // throw out instant app filters if updates are available; will trigger
14038            // instant app resolution
14039            if (userState.instantApp && ps.isUpdateAvailable()) {
14040                return null;
14041            }
14042            final ResolveInfo res = new ResolveInfo();
14043            res.serviceInfo = si;
14044            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14045                res.filter = filter;
14046            }
14047            res.priority = info.getPriority();
14048            res.preferredOrder = service.owner.mPreferredOrder;
14049            res.match = match;
14050            res.isDefault = info.hasDefault;
14051            res.labelRes = info.labelRes;
14052            res.nonLocalizedLabel = info.nonLocalizedLabel;
14053            res.icon = info.icon;
14054            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14055            return res;
14056        }
14057
14058        @Override
14059        protected void sortResults(List<ResolveInfo> results) {
14060            Collections.sort(results, mResolvePrioritySorter);
14061        }
14062
14063        @Override
14064        protected void dumpFilter(PrintWriter out, String prefix,
14065                PackageParser.ServiceIntentInfo filter) {
14066            out.print(prefix); out.print(
14067                    Integer.toHexString(System.identityHashCode(filter.service)));
14068                    out.print(' ');
14069                    filter.service.printComponentShortName(out);
14070                    out.print(" filter ");
14071                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14072        }
14073
14074        @Override
14075        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14076            return filter.service;
14077        }
14078
14079        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14080            PackageParser.Service service = (PackageParser.Service)label;
14081            out.print(prefix); out.print(
14082                    Integer.toHexString(System.identityHashCode(service)));
14083                    out.print(' ');
14084                    service.printComponentShortName(out);
14085            if (count > 1) {
14086                out.print(" ("); out.print(count); out.print(" filters)");
14087            }
14088            out.println();
14089        }
14090
14091//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14092//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14093//            final List<ResolveInfo> retList = Lists.newArrayList();
14094//            while (i.hasNext()) {
14095//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14096//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14097//                    retList.add(resolveInfo);
14098//                }
14099//            }
14100//            return retList;
14101//        }
14102
14103        // Keys are String (activity class name), values are Activity.
14104        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14105                = new ArrayMap<ComponentName, PackageParser.Service>();
14106        private int mFlags;
14107    }
14108
14109    private final class ProviderIntentResolver
14110            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14111        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14112                boolean defaultOnly, int userId) {
14113            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14114            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14115        }
14116
14117        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14118                int userId) {
14119            if (!sUserManager.exists(userId))
14120                return null;
14121            mFlags = flags;
14122            return super.queryIntent(intent, resolvedType,
14123                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14124                    userId);
14125        }
14126
14127        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14128                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14129            if (!sUserManager.exists(userId))
14130                return null;
14131            if (packageProviders == null) {
14132                return null;
14133            }
14134            mFlags = flags;
14135            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14136            final int N = packageProviders.size();
14137            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14138                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14139
14140            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14141            for (int i = 0; i < N; ++i) {
14142                intentFilters = packageProviders.get(i).intents;
14143                if (intentFilters != null && intentFilters.size() > 0) {
14144                    PackageParser.ProviderIntentInfo[] array =
14145                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14146                    intentFilters.toArray(array);
14147                    listCut.add(array);
14148                }
14149            }
14150            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14151        }
14152
14153        public final void addProvider(PackageParser.Provider p) {
14154            if (mProviders.containsKey(p.getComponentName())) {
14155                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14156                return;
14157            }
14158
14159            mProviders.put(p.getComponentName(), p);
14160            if (DEBUG_SHOW_INFO) {
14161                Log.v(TAG, "  "
14162                        + (p.info.nonLocalizedLabel != null
14163                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14164                Log.v(TAG, "    Class=" + p.info.name);
14165            }
14166            final int NI = p.intents.size();
14167            int j;
14168            for (j = 0; j < NI; j++) {
14169                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14170                if (DEBUG_SHOW_INFO) {
14171                    Log.v(TAG, "    IntentFilter:");
14172                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14173                }
14174                if (!intent.debugCheck()) {
14175                    Log.w(TAG, "==> For Provider " + p.info.name);
14176                }
14177                addFilter(intent);
14178            }
14179        }
14180
14181        public final void removeProvider(PackageParser.Provider p) {
14182            mProviders.remove(p.getComponentName());
14183            if (DEBUG_SHOW_INFO) {
14184                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14185                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14186                Log.v(TAG, "    Class=" + p.info.name);
14187            }
14188            final int NI = p.intents.size();
14189            int j;
14190            for (j = 0; j < NI; j++) {
14191                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14192                if (DEBUG_SHOW_INFO) {
14193                    Log.v(TAG, "    IntentFilter:");
14194                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14195                }
14196                removeFilter(intent);
14197            }
14198        }
14199
14200        @Override
14201        protected boolean allowFilterResult(
14202                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14203            ProviderInfo filterPi = filter.provider.info;
14204            for (int i = dest.size() - 1; i >= 0; i--) {
14205                ProviderInfo destPi = dest.get(i).providerInfo;
14206                if (destPi.name == filterPi.name
14207                        && destPi.packageName == filterPi.packageName) {
14208                    return false;
14209                }
14210            }
14211            return true;
14212        }
14213
14214        @Override
14215        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14216            return new PackageParser.ProviderIntentInfo[size];
14217        }
14218
14219        @Override
14220        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14221            if (!sUserManager.exists(userId))
14222                return true;
14223            PackageParser.Package p = filter.provider.owner;
14224            if (p != null) {
14225                PackageSetting ps = (PackageSetting) p.mExtras;
14226                if (ps != null) {
14227                    // System apps are never considered stopped for purposes of
14228                    // filtering, because there may be no way for the user to
14229                    // actually re-launch them.
14230                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14231                            && ps.getStopped(userId);
14232                }
14233            }
14234            return false;
14235        }
14236
14237        @Override
14238        protected boolean isPackageForFilter(String packageName,
14239                PackageParser.ProviderIntentInfo info) {
14240            return packageName.equals(info.provider.owner.packageName);
14241        }
14242
14243        @Override
14244        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14245                int match, int userId) {
14246            if (!sUserManager.exists(userId))
14247                return null;
14248            final PackageParser.ProviderIntentInfo info = filter;
14249            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14250                return null;
14251            }
14252            final PackageParser.Provider provider = info.provider;
14253            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14254            if (ps == null) {
14255                return null;
14256            }
14257            final PackageUserState userState = ps.readUserState(userId);
14258            final boolean matchVisibleToInstantApp =
14259                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14260            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14261            // throw out filters that aren't visible to instant applications
14262            if (matchVisibleToInstantApp
14263                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14264                return null;
14265            }
14266            // throw out instant application filters if we're not explicitly requesting them
14267            if (!isInstantApp && userState.instantApp) {
14268                return null;
14269            }
14270            // throw out instant application filters if updates are available; will trigger
14271            // instant application resolution
14272            if (userState.instantApp && ps.isUpdateAvailable()) {
14273                return null;
14274            }
14275            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14276                    userState, userId);
14277            if (pi == null) {
14278                return null;
14279            }
14280            final ResolveInfo res = new ResolveInfo();
14281            res.providerInfo = pi;
14282            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14283                res.filter = filter;
14284            }
14285            res.priority = info.getPriority();
14286            res.preferredOrder = provider.owner.mPreferredOrder;
14287            res.match = match;
14288            res.isDefault = info.hasDefault;
14289            res.labelRes = info.labelRes;
14290            res.nonLocalizedLabel = info.nonLocalizedLabel;
14291            res.icon = info.icon;
14292            res.system = res.providerInfo.applicationInfo.isSystemApp();
14293            return res;
14294        }
14295
14296        @Override
14297        protected void sortResults(List<ResolveInfo> results) {
14298            Collections.sort(results, mResolvePrioritySorter);
14299        }
14300
14301        @Override
14302        protected void dumpFilter(PrintWriter out, String prefix,
14303                PackageParser.ProviderIntentInfo filter) {
14304            out.print(prefix);
14305            out.print(
14306                    Integer.toHexString(System.identityHashCode(filter.provider)));
14307            out.print(' ');
14308            filter.provider.printComponentShortName(out);
14309            out.print(" filter ");
14310            out.println(Integer.toHexString(System.identityHashCode(filter)));
14311        }
14312
14313        @Override
14314        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14315            return filter.provider;
14316        }
14317
14318        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14319            PackageParser.Provider provider = (PackageParser.Provider)label;
14320            out.print(prefix); out.print(
14321                    Integer.toHexString(System.identityHashCode(provider)));
14322                    out.print(' ');
14323                    provider.printComponentShortName(out);
14324            if (count > 1) {
14325                out.print(" ("); out.print(count); out.print(" filters)");
14326            }
14327            out.println();
14328        }
14329
14330        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14331                = new ArrayMap<ComponentName, PackageParser.Provider>();
14332        private int mFlags;
14333    }
14334
14335    static final class EphemeralIntentResolver
14336            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14337        /**
14338         * The result that has the highest defined order. Ordering applies on a
14339         * per-package basis. Mapping is from package name to Pair of order and
14340         * EphemeralResolveInfo.
14341         * <p>
14342         * NOTE: This is implemented as a field variable for convenience and efficiency.
14343         * By having a field variable, we're able to track filter ordering as soon as
14344         * a non-zero order is defined. Otherwise, multiple loops across the result set
14345         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14346         * this needs to be contained entirely within {@link #filterResults}.
14347         */
14348        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14349
14350        @Override
14351        protected AuxiliaryResolveInfo[] newArray(int size) {
14352            return new AuxiliaryResolveInfo[size];
14353        }
14354
14355        @Override
14356        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14357            return true;
14358        }
14359
14360        @Override
14361        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14362                int userId) {
14363            if (!sUserManager.exists(userId)) {
14364                return null;
14365            }
14366            final String packageName = responseObj.resolveInfo.getPackageName();
14367            final Integer order = responseObj.getOrder();
14368            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14369                    mOrderResult.get(packageName);
14370            // ordering is enabled and this item's order isn't high enough
14371            if (lastOrderResult != null && lastOrderResult.first >= order) {
14372                return null;
14373            }
14374            final InstantAppResolveInfo res = responseObj.resolveInfo;
14375            if (order > 0) {
14376                // non-zero order, enable ordering
14377                mOrderResult.put(packageName, new Pair<>(order, res));
14378            }
14379            return responseObj;
14380        }
14381
14382        @Override
14383        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14384            // only do work if ordering is enabled [most of the time it won't be]
14385            if (mOrderResult.size() == 0) {
14386                return;
14387            }
14388            int resultSize = results.size();
14389            for (int i = 0; i < resultSize; i++) {
14390                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14391                final String packageName = info.getPackageName();
14392                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14393                if (savedInfo == null) {
14394                    // package doesn't having ordering
14395                    continue;
14396                }
14397                if (savedInfo.second == info) {
14398                    // circled back to the highest ordered item; remove from order list
14399                    mOrderResult.remove(packageName);
14400                    if (mOrderResult.size() == 0) {
14401                        // no more ordered items
14402                        break;
14403                    }
14404                    continue;
14405                }
14406                // item has a worse order, remove it from the result list
14407                results.remove(i);
14408                resultSize--;
14409                i--;
14410            }
14411        }
14412    }
14413
14414    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14415            new Comparator<ResolveInfo>() {
14416        public int compare(ResolveInfo r1, ResolveInfo r2) {
14417            int v1 = r1.priority;
14418            int v2 = r2.priority;
14419            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14420            if (v1 != v2) {
14421                return (v1 > v2) ? -1 : 1;
14422            }
14423            v1 = r1.preferredOrder;
14424            v2 = r2.preferredOrder;
14425            if (v1 != v2) {
14426                return (v1 > v2) ? -1 : 1;
14427            }
14428            if (r1.isDefault != r2.isDefault) {
14429                return r1.isDefault ? -1 : 1;
14430            }
14431            v1 = r1.match;
14432            v2 = r2.match;
14433            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14434            if (v1 != v2) {
14435                return (v1 > v2) ? -1 : 1;
14436            }
14437            if (r1.system != r2.system) {
14438                return r1.system ? -1 : 1;
14439            }
14440            if (r1.activityInfo != null) {
14441                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14442            }
14443            if (r1.serviceInfo != null) {
14444                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14445            }
14446            if (r1.providerInfo != null) {
14447                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14448            }
14449            return 0;
14450        }
14451    };
14452
14453    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14454            new Comparator<ProviderInfo>() {
14455        public int compare(ProviderInfo p1, ProviderInfo p2) {
14456            final int v1 = p1.initOrder;
14457            final int v2 = p2.initOrder;
14458            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14459        }
14460    };
14461
14462    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14463            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14464            final int[] userIds) {
14465        mHandler.post(new Runnable() {
14466            @Override
14467            public void run() {
14468                try {
14469                    final IActivityManager am = ActivityManager.getService();
14470                    if (am == null) return;
14471                    final int[] resolvedUserIds;
14472                    if (userIds == null) {
14473                        resolvedUserIds = am.getRunningUserIds();
14474                    } else {
14475                        resolvedUserIds = userIds;
14476                    }
14477                    for (int id : resolvedUserIds) {
14478                        final Intent intent = new Intent(action,
14479                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14480                        if (extras != null) {
14481                            intent.putExtras(extras);
14482                        }
14483                        if (targetPkg != null) {
14484                            intent.setPackage(targetPkg);
14485                        }
14486                        // Modify the UID when posting to other users
14487                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14488                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14489                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14490                            intent.putExtra(Intent.EXTRA_UID, uid);
14491                        }
14492                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14493                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14494                        if (DEBUG_BROADCASTS) {
14495                            RuntimeException here = new RuntimeException("here");
14496                            here.fillInStackTrace();
14497                            Slog.d(TAG, "Sending to user " + id + ": "
14498                                    + intent.toShortString(false, true, false, false)
14499                                    + " " + intent.getExtras(), here);
14500                        }
14501                        am.broadcastIntent(null, intent, null, finishedReceiver,
14502                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14503                                null, finishedReceiver != null, false, id);
14504                    }
14505                } catch (RemoteException ex) {
14506                }
14507            }
14508        });
14509    }
14510
14511    /**
14512     * Check if the external storage media is available. This is true if there
14513     * is a mounted external storage medium or if the external storage is
14514     * emulated.
14515     */
14516    private boolean isExternalMediaAvailable() {
14517        return mMediaMounted || Environment.isExternalStorageEmulated();
14518    }
14519
14520    @Override
14521    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14522        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14523            return null;
14524        }
14525        // writer
14526        synchronized (mPackages) {
14527            if (!isExternalMediaAvailable()) {
14528                // If the external storage is no longer mounted at this point,
14529                // the caller may not have been able to delete all of this
14530                // packages files and can not delete any more.  Bail.
14531                return null;
14532            }
14533            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14534            if (lastPackage != null) {
14535                pkgs.remove(lastPackage);
14536            }
14537            if (pkgs.size() > 0) {
14538                return pkgs.get(0);
14539            }
14540        }
14541        return null;
14542    }
14543
14544    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14545        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14546                userId, andCode ? 1 : 0, packageName);
14547        if (mSystemReady) {
14548            msg.sendToTarget();
14549        } else {
14550            if (mPostSystemReadyMessages == null) {
14551                mPostSystemReadyMessages = new ArrayList<>();
14552            }
14553            mPostSystemReadyMessages.add(msg);
14554        }
14555    }
14556
14557    void startCleaningPackages() {
14558        // reader
14559        if (!isExternalMediaAvailable()) {
14560            return;
14561        }
14562        synchronized (mPackages) {
14563            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14564                return;
14565            }
14566        }
14567        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14568        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14569        IActivityManager am = ActivityManager.getService();
14570        if (am != null) {
14571            int dcsUid = -1;
14572            synchronized (mPackages) {
14573                if (!mDefaultContainerWhitelisted) {
14574                    mDefaultContainerWhitelisted = true;
14575                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14576                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14577                }
14578            }
14579            try {
14580                if (dcsUid > 0) {
14581                    am.backgroundWhitelistUid(dcsUid);
14582                }
14583                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14584                        UserHandle.USER_SYSTEM);
14585            } catch (RemoteException e) {
14586            }
14587        }
14588    }
14589
14590    @Override
14591    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14592            int installFlags, String installerPackageName, int userId) {
14593        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14594
14595        final int callingUid = Binder.getCallingUid();
14596        enforceCrossUserPermission(callingUid, userId,
14597                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14598
14599        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14600            try {
14601                if (observer != null) {
14602                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14603                }
14604            } catch (RemoteException re) {
14605            }
14606            return;
14607        }
14608
14609        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14610            installFlags |= PackageManager.INSTALL_FROM_ADB;
14611
14612        } else {
14613            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14614            // about installerPackageName.
14615
14616            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14617            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14618        }
14619
14620        UserHandle user;
14621        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14622            user = UserHandle.ALL;
14623        } else {
14624            user = new UserHandle(userId);
14625        }
14626
14627        // Only system components can circumvent runtime permissions when installing.
14628        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14629                && mContext.checkCallingOrSelfPermission(Manifest.permission
14630                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14631            throw new SecurityException("You need the "
14632                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14633                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14634        }
14635
14636        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14637                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14638            throw new IllegalArgumentException(
14639                    "New installs into ASEC containers no longer supported");
14640        }
14641
14642        final File originFile = new File(originPath);
14643        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14644
14645        final Message msg = mHandler.obtainMessage(INIT_COPY);
14646        final VerificationInfo verificationInfo = new VerificationInfo(
14647                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14648        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14649                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14650                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14651                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14652        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14653        msg.obj = params;
14654
14655        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14656                System.identityHashCode(msg.obj));
14657        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14658                System.identityHashCode(msg.obj));
14659
14660        mHandler.sendMessage(msg);
14661    }
14662
14663
14664    /**
14665     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14666     * it is acting on behalf on an enterprise or the user).
14667     *
14668     * Note that the ordering of the conditionals in this method is important. The checks we perform
14669     * are as follows, in this order:
14670     *
14671     * 1) If the install is being performed by a system app, we can trust the app to have set the
14672     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14673     *    what it is.
14674     * 2) If the install is being performed by a device or profile owner app, the install reason
14675     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14676     *    set the install reason correctly. If the app targets an older SDK version where install
14677     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14678     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14679     * 3) In all other cases, the install is being performed by a regular app that is neither part
14680     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14681     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14682     *    set to enterprise policy and if so, change it to unknown instead.
14683     */
14684    private int fixUpInstallReason(String installerPackageName, int installerUid,
14685            int installReason) {
14686        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14687                == PERMISSION_GRANTED) {
14688            // If the install is being performed by a system app, we trust that app to have set the
14689            // install reason correctly.
14690            return installReason;
14691        }
14692
14693        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14694            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14695        if (dpm != null) {
14696            ComponentName owner = null;
14697            try {
14698                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14699                if (owner == null) {
14700                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14701                }
14702            } catch (RemoteException e) {
14703            }
14704            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14705                // If the install is being performed by a device or profile owner, the install
14706                // reason should be enterprise policy.
14707                return PackageManager.INSTALL_REASON_POLICY;
14708            }
14709        }
14710
14711        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14712            // If the install is being performed by a regular app (i.e. neither system app nor
14713            // device or profile owner), we have no reason to believe that the app is acting on
14714            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14715            // change it to unknown instead.
14716            return PackageManager.INSTALL_REASON_UNKNOWN;
14717        }
14718
14719        // If the install is being performed by a regular app and the install reason was set to any
14720        // value but enterprise policy, leave the install reason unchanged.
14721        return installReason;
14722    }
14723
14724    void installStage(String packageName, File stagedDir, String stagedCid,
14725            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14726            String installerPackageName, int installerUid, UserHandle user,
14727            Certificate[][] certificates) {
14728        if (DEBUG_EPHEMERAL) {
14729            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14730                Slog.d(TAG, "Ephemeral install of " + packageName);
14731            }
14732        }
14733        final VerificationInfo verificationInfo = new VerificationInfo(
14734                sessionParams.originatingUri, sessionParams.referrerUri,
14735                sessionParams.originatingUid, installerUid);
14736
14737        final OriginInfo origin;
14738        if (stagedDir != null) {
14739            origin = OriginInfo.fromStagedFile(stagedDir);
14740        } else {
14741            origin = OriginInfo.fromStagedContainer(stagedCid);
14742        }
14743
14744        final Message msg = mHandler.obtainMessage(INIT_COPY);
14745        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14746                sessionParams.installReason);
14747        final InstallParams params = new InstallParams(origin, null, observer,
14748                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14749                verificationInfo, user, sessionParams.abiOverride,
14750                sessionParams.grantedRuntimePermissions, certificates, installReason);
14751        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14752        msg.obj = params;
14753
14754        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14755                System.identityHashCode(msg.obj));
14756        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14757                System.identityHashCode(msg.obj));
14758
14759        mHandler.sendMessage(msg);
14760    }
14761
14762    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14763            int userId) {
14764        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14765        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14766                false /*startReceiver*/, pkgSetting.appId, userId);
14767
14768        // Send a session commit broadcast
14769        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14770        info.installReason = pkgSetting.getInstallReason(userId);
14771        info.appPackageName = packageName;
14772        sendSessionCommitBroadcast(info, userId);
14773    }
14774
14775    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14776            boolean includeStopped, int appId, int... userIds) {
14777        if (ArrayUtils.isEmpty(userIds)) {
14778            return;
14779        }
14780        Bundle extras = new Bundle(1);
14781        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14782        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14783
14784        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14785                packageName, extras, 0, null, null, userIds);
14786        if (sendBootCompleted) {
14787            mHandler.post(() -> {
14788                        for (int userId : userIds) {
14789                            sendBootCompletedBroadcastToSystemApp(
14790                                    packageName, includeStopped, userId);
14791                        }
14792                    }
14793            );
14794        }
14795    }
14796
14797    /**
14798     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14799     * automatically without needing an explicit launch.
14800     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14801     */
14802    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14803            int userId) {
14804        // If user is not running, the app didn't miss any broadcast
14805        if (!mUserManagerInternal.isUserRunning(userId)) {
14806            return;
14807        }
14808        final IActivityManager am = ActivityManager.getService();
14809        try {
14810            // Deliver LOCKED_BOOT_COMPLETED first
14811            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14812                    .setPackage(packageName);
14813            if (includeStopped) {
14814                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14815            }
14816            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14817            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14818                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14819
14820            // Deliver BOOT_COMPLETED only if user is unlocked
14821            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14822                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14823                if (includeStopped) {
14824                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14825                }
14826                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14827                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14828            }
14829        } catch (RemoteException e) {
14830            throw e.rethrowFromSystemServer();
14831        }
14832    }
14833
14834    @Override
14835    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14836            int userId) {
14837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14838        PackageSetting pkgSetting;
14839        final int callingUid = Binder.getCallingUid();
14840        enforceCrossUserPermission(callingUid, userId,
14841                true /* requireFullPermission */, true /* checkShell */,
14842                "setApplicationHiddenSetting for user " + userId);
14843
14844        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14845            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14846            return false;
14847        }
14848
14849        long callingId = Binder.clearCallingIdentity();
14850        try {
14851            boolean sendAdded = false;
14852            boolean sendRemoved = false;
14853            // writer
14854            synchronized (mPackages) {
14855                pkgSetting = mSettings.mPackages.get(packageName);
14856                if (pkgSetting == null) {
14857                    return false;
14858                }
14859                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14860                    return false;
14861                }
14862                // Do not allow "android" is being disabled
14863                if ("android".equals(packageName)) {
14864                    Slog.w(TAG, "Cannot hide package: android");
14865                    return false;
14866                }
14867                // Cannot hide static shared libs as they are considered
14868                // a part of the using app (emulating static linking). Also
14869                // static libs are installed always on internal storage.
14870                PackageParser.Package pkg = mPackages.get(packageName);
14871                if (pkg != null && pkg.staticSharedLibName != null) {
14872                    Slog.w(TAG, "Cannot hide package: " + packageName
14873                            + " providing static shared library: "
14874                            + pkg.staticSharedLibName);
14875                    return false;
14876                }
14877                // Only allow protected packages to hide themselves.
14878                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14879                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14880                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14881                    return false;
14882                }
14883
14884                if (pkgSetting.getHidden(userId) != hidden) {
14885                    pkgSetting.setHidden(hidden, userId);
14886                    mSettings.writePackageRestrictionsLPr(userId);
14887                    if (hidden) {
14888                        sendRemoved = true;
14889                    } else {
14890                        sendAdded = true;
14891                    }
14892                }
14893            }
14894            if (sendAdded) {
14895                sendPackageAddedForUser(packageName, pkgSetting, userId);
14896                return true;
14897            }
14898            if (sendRemoved) {
14899                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14900                        "hiding pkg");
14901                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14902                return true;
14903            }
14904        } finally {
14905            Binder.restoreCallingIdentity(callingId);
14906        }
14907        return false;
14908    }
14909
14910    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14911            int userId) {
14912        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14913        info.removedPackage = packageName;
14914        info.installerPackageName = pkgSetting.installerPackageName;
14915        info.removedUsers = new int[] {userId};
14916        info.broadcastUsers = new int[] {userId};
14917        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14918        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14919    }
14920
14921    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14922        if (pkgList.length > 0) {
14923            Bundle extras = new Bundle(1);
14924            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14925
14926            sendPackageBroadcast(
14927                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14928                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14929                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14930                    new int[] {userId});
14931        }
14932    }
14933
14934    /**
14935     * Returns true if application is not found or there was an error. Otherwise it returns
14936     * the hidden state of the package for the given user.
14937     */
14938    @Override
14939    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14941        final int callingUid = Binder.getCallingUid();
14942        enforceCrossUserPermission(callingUid, userId,
14943                true /* requireFullPermission */, false /* checkShell */,
14944                "getApplicationHidden for user " + userId);
14945        PackageSetting ps;
14946        long callingId = Binder.clearCallingIdentity();
14947        try {
14948            // writer
14949            synchronized (mPackages) {
14950                ps = mSettings.mPackages.get(packageName);
14951                if (ps == null) {
14952                    return true;
14953                }
14954                if (filterAppAccessLPr(ps, callingUid, userId)) {
14955                    return true;
14956                }
14957                return ps.getHidden(userId);
14958            }
14959        } finally {
14960            Binder.restoreCallingIdentity(callingId);
14961        }
14962    }
14963
14964    /**
14965     * @hide
14966     */
14967    @Override
14968    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14969            int installReason) {
14970        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14971                null);
14972        PackageSetting pkgSetting;
14973        final int callingUid = Binder.getCallingUid();
14974        enforceCrossUserPermission(callingUid, userId,
14975                true /* requireFullPermission */, true /* checkShell */,
14976                "installExistingPackage for user " + userId);
14977        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14978            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14979        }
14980
14981        long callingId = Binder.clearCallingIdentity();
14982        try {
14983            boolean installed = false;
14984            final boolean instantApp =
14985                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14986            final boolean fullApp =
14987                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14988
14989            // writer
14990            synchronized (mPackages) {
14991                pkgSetting = mSettings.mPackages.get(packageName);
14992                if (pkgSetting == null) {
14993                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14994                }
14995                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14996                    // only allow the existing package to be used if it's installed as a full
14997                    // application for at least one user
14998                    boolean installAllowed = false;
14999                    for (int checkUserId : sUserManager.getUserIds()) {
15000                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15001                        if (installAllowed) {
15002                            break;
15003                        }
15004                    }
15005                    if (!installAllowed) {
15006                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15007                    }
15008                }
15009                if (!pkgSetting.getInstalled(userId)) {
15010                    pkgSetting.setInstalled(true, userId);
15011                    pkgSetting.setHidden(false, userId);
15012                    pkgSetting.setInstallReason(installReason, userId);
15013                    mSettings.writePackageRestrictionsLPr(userId);
15014                    mSettings.writeKernelMappingLPr(pkgSetting);
15015                    installed = true;
15016                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15017                    // upgrade app from instant to full; we don't allow app downgrade
15018                    installed = true;
15019                }
15020                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15021            }
15022
15023            if (installed) {
15024                if (pkgSetting.pkg != null) {
15025                    synchronized (mInstallLock) {
15026                        // We don't need to freeze for a brand new install
15027                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15028                    }
15029                }
15030                sendPackageAddedForUser(packageName, pkgSetting, userId);
15031                synchronized (mPackages) {
15032                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15033                }
15034            }
15035        } finally {
15036            Binder.restoreCallingIdentity(callingId);
15037        }
15038
15039        return PackageManager.INSTALL_SUCCEEDED;
15040    }
15041
15042    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15043            boolean instantApp, boolean fullApp) {
15044        // no state specified; do nothing
15045        if (!instantApp && !fullApp) {
15046            return;
15047        }
15048        if (userId != UserHandle.USER_ALL) {
15049            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15050                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15051            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15052                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15053            }
15054        } else {
15055            for (int currentUserId : sUserManager.getUserIds()) {
15056                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15057                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15058                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15059                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15060                }
15061            }
15062        }
15063    }
15064
15065    boolean isUserRestricted(int userId, String restrictionKey) {
15066        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15067        if (restrictions.getBoolean(restrictionKey, false)) {
15068            Log.w(TAG, "User is restricted: " + restrictionKey);
15069            return true;
15070        }
15071        return false;
15072    }
15073
15074    @Override
15075    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15076            int userId) {
15077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15078        final int callingUid = Binder.getCallingUid();
15079        enforceCrossUserPermission(callingUid, userId,
15080                true /* requireFullPermission */, true /* checkShell */,
15081                "setPackagesSuspended for user " + userId);
15082
15083        if (ArrayUtils.isEmpty(packageNames)) {
15084            return packageNames;
15085        }
15086
15087        // List of package names for whom the suspended state has changed.
15088        List<String> changedPackages = new ArrayList<>(packageNames.length);
15089        // List of package names for whom the suspended state is not set as requested in this
15090        // method.
15091        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15092        long callingId = Binder.clearCallingIdentity();
15093        try {
15094            for (int i = 0; i < packageNames.length; i++) {
15095                String packageName = packageNames[i];
15096                boolean changed = false;
15097                final int appId;
15098                synchronized (mPackages) {
15099                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15100                    if (pkgSetting == null
15101                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15102                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15103                                + "\". Skipping suspending/un-suspending.");
15104                        unactionedPackages.add(packageName);
15105                        continue;
15106                    }
15107                    appId = pkgSetting.appId;
15108                    if (pkgSetting.getSuspended(userId) != suspended) {
15109                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15110                            unactionedPackages.add(packageName);
15111                            continue;
15112                        }
15113                        pkgSetting.setSuspended(suspended, userId);
15114                        mSettings.writePackageRestrictionsLPr(userId);
15115                        changed = true;
15116                        changedPackages.add(packageName);
15117                    }
15118                }
15119
15120                if (changed && suspended) {
15121                    killApplication(packageName, UserHandle.getUid(userId, appId),
15122                            "suspending package");
15123                }
15124            }
15125        } finally {
15126            Binder.restoreCallingIdentity(callingId);
15127        }
15128
15129        if (!changedPackages.isEmpty()) {
15130            sendPackagesSuspendedForUser(changedPackages.toArray(
15131                    new String[changedPackages.size()]), userId, suspended);
15132        }
15133
15134        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15135    }
15136
15137    @Override
15138    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15139        final int callingUid = Binder.getCallingUid();
15140        enforceCrossUserPermission(callingUid, userId,
15141                true /* requireFullPermission */, false /* checkShell */,
15142                "isPackageSuspendedForUser for user " + userId);
15143        synchronized (mPackages) {
15144            final PackageSetting ps = mSettings.mPackages.get(packageName);
15145            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15146                throw new IllegalArgumentException("Unknown target package: " + packageName);
15147            }
15148            return ps.getSuspended(userId);
15149        }
15150    }
15151
15152    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15153        if (isPackageDeviceAdmin(packageName, userId)) {
15154            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15155                    + "\": has an active device admin");
15156            return false;
15157        }
15158
15159        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15160        if (packageName.equals(activeLauncherPackageName)) {
15161            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15162                    + "\": contains the active launcher");
15163            return false;
15164        }
15165
15166        if (packageName.equals(mRequiredInstallerPackage)) {
15167            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15168                    + "\": required for package installation");
15169            return false;
15170        }
15171
15172        if (packageName.equals(mRequiredUninstallerPackage)) {
15173            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15174                    + "\": required for package uninstallation");
15175            return false;
15176        }
15177
15178        if (packageName.equals(mRequiredVerifierPackage)) {
15179            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15180                    + "\": required for package verification");
15181            return false;
15182        }
15183
15184        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15185            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15186                    + "\": is the default dialer");
15187            return false;
15188        }
15189
15190        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15191            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15192                    + "\": protected package");
15193            return false;
15194        }
15195
15196        // Cannot suspend static shared libs as they are considered
15197        // a part of the using app (emulating static linking). Also
15198        // static libs are installed always on internal storage.
15199        PackageParser.Package pkg = mPackages.get(packageName);
15200        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15201            Slog.w(TAG, "Cannot suspend package: " + packageName
15202                    + " providing static shared library: "
15203                    + pkg.staticSharedLibName);
15204            return false;
15205        }
15206
15207        return true;
15208    }
15209
15210    private String getActiveLauncherPackageName(int userId) {
15211        Intent intent = new Intent(Intent.ACTION_MAIN);
15212        intent.addCategory(Intent.CATEGORY_HOME);
15213        ResolveInfo resolveInfo = resolveIntent(
15214                intent,
15215                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15216                PackageManager.MATCH_DEFAULT_ONLY,
15217                userId);
15218
15219        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15220    }
15221
15222    private String getDefaultDialerPackageName(int userId) {
15223        synchronized (mPackages) {
15224            return mSettings.getDefaultDialerPackageNameLPw(userId);
15225        }
15226    }
15227
15228    @Override
15229    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15230        mContext.enforceCallingOrSelfPermission(
15231                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15232                "Only package verification agents can verify applications");
15233
15234        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15235        final PackageVerificationResponse response = new PackageVerificationResponse(
15236                verificationCode, Binder.getCallingUid());
15237        msg.arg1 = id;
15238        msg.obj = response;
15239        mHandler.sendMessage(msg);
15240    }
15241
15242    @Override
15243    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15244            long millisecondsToDelay) {
15245        mContext.enforceCallingOrSelfPermission(
15246                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15247                "Only package verification agents can extend verification timeouts");
15248
15249        final PackageVerificationState state = mPendingVerification.get(id);
15250        final PackageVerificationResponse response = new PackageVerificationResponse(
15251                verificationCodeAtTimeout, Binder.getCallingUid());
15252
15253        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15254            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15255        }
15256        if (millisecondsToDelay < 0) {
15257            millisecondsToDelay = 0;
15258        }
15259        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15260                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15261            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15262        }
15263
15264        if ((state != null) && !state.timeoutExtended()) {
15265            state.extendTimeout();
15266
15267            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15268            msg.arg1 = id;
15269            msg.obj = response;
15270            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15271        }
15272    }
15273
15274    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15275            int verificationCode, UserHandle user) {
15276        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15277        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15278        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15279        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15280        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15281
15282        mContext.sendBroadcastAsUser(intent, user,
15283                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15284    }
15285
15286    private ComponentName matchComponentForVerifier(String packageName,
15287            List<ResolveInfo> receivers) {
15288        ActivityInfo targetReceiver = null;
15289
15290        final int NR = receivers.size();
15291        for (int i = 0; i < NR; i++) {
15292            final ResolveInfo info = receivers.get(i);
15293            if (info.activityInfo == null) {
15294                continue;
15295            }
15296
15297            if (packageName.equals(info.activityInfo.packageName)) {
15298                targetReceiver = info.activityInfo;
15299                break;
15300            }
15301        }
15302
15303        if (targetReceiver == null) {
15304            return null;
15305        }
15306
15307        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15308    }
15309
15310    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15311            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15312        if (pkgInfo.verifiers.length == 0) {
15313            return null;
15314        }
15315
15316        final int N = pkgInfo.verifiers.length;
15317        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15318        for (int i = 0; i < N; i++) {
15319            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15320
15321            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15322                    receivers);
15323            if (comp == null) {
15324                continue;
15325            }
15326
15327            final int verifierUid = getUidForVerifier(verifierInfo);
15328            if (verifierUid == -1) {
15329                continue;
15330            }
15331
15332            if (DEBUG_VERIFY) {
15333                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15334                        + " with the correct signature");
15335            }
15336            sufficientVerifiers.add(comp);
15337            verificationState.addSufficientVerifier(verifierUid);
15338        }
15339
15340        return sufficientVerifiers;
15341    }
15342
15343    private int getUidForVerifier(VerifierInfo verifierInfo) {
15344        synchronized (mPackages) {
15345            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15346            if (pkg == null) {
15347                return -1;
15348            } else if (pkg.mSignatures.length != 1) {
15349                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15350                        + " has more than one signature; ignoring");
15351                return -1;
15352            }
15353
15354            /*
15355             * If the public key of the package's signature does not match
15356             * our expected public key, then this is a different package and
15357             * we should skip.
15358             */
15359
15360            final byte[] expectedPublicKey;
15361            try {
15362                final Signature verifierSig = pkg.mSignatures[0];
15363                final PublicKey publicKey = verifierSig.getPublicKey();
15364                expectedPublicKey = publicKey.getEncoded();
15365            } catch (CertificateException e) {
15366                return -1;
15367            }
15368
15369            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15370
15371            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15372                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15373                        + " does not have the expected public key; ignoring");
15374                return -1;
15375            }
15376
15377            return pkg.applicationInfo.uid;
15378        }
15379    }
15380
15381    @Override
15382    public void finishPackageInstall(int token, boolean didLaunch) {
15383        enforceSystemOrRoot("Only the system is allowed to finish installs");
15384
15385        if (DEBUG_INSTALL) {
15386            Slog.v(TAG, "BM finishing package install for " + token);
15387        }
15388        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15389
15390        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15391        mHandler.sendMessage(msg);
15392    }
15393
15394    /**
15395     * Get the verification agent timeout.  Used for both the APK verifier and the
15396     * intent filter verifier.
15397     *
15398     * @return verification timeout in milliseconds
15399     */
15400    private long getVerificationTimeout() {
15401        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15402                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15403                DEFAULT_VERIFICATION_TIMEOUT);
15404    }
15405
15406    /**
15407     * Get the default verification agent response code.
15408     *
15409     * @return default verification response code
15410     */
15411    private int getDefaultVerificationResponse(UserHandle user) {
15412        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15413            return PackageManager.VERIFICATION_REJECT;
15414        }
15415        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15416                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15417                DEFAULT_VERIFICATION_RESPONSE);
15418    }
15419
15420    /**
15421     * Check whether or not package verification has been enabled.
15422     *
15423     * @return true if verification should be performed
15424     */
15425    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15426        if (!DEFAULT_VERIFY_ENABLE) {
15427            return false;
15428        }
15429
15430        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15431
15432        // Check if installing from ADB
15433        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15434            // Do not run verification in a test harness environment
15435            if (ActivityManager.isRunningInTestHarness()) {
15436                return false;
15437            }
15438            if (ensureVerifyAppsEnabled) {
15439                return true;
15440            }
15441            // Check if the developer does not want package verification for ADB installs
15442            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15443                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15444                return false;
15445            }
15446        } else {
15447            // only when not installed from ADB, skip verification for instant apps when
15448            // the installer and verifier are the same.
15449            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15450                if (mInstantAppInstallerActivity != null
15451                        && mInstantAppInstallerActivity.packageName.equals(
15452                                mRequiredVerifierPackage)) {
15453                    try {
15454                        mContext.getSystemService(AppOpsManager.class)
15455                                .checkPackage(installerUid, mRequiredVerifierPackage);
15456                        if (DEBUG_VERIFY) {
15457                            Slog.i(TAG, "disable verification for instant app");
15458                        }
15459                        return false;
15460                    } catch (SecurityException ignore) { }
15461                }
15462            }
15463        }
15464
15465        if (ensureVerifyAppsEnabled) {
15466            return true;
15467        }
15468
15469        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15470                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15471    }
15472
15473    @Override
15474    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15475            throws RemoteException {
15476        mContext.enforceCallingOrSelfPermission(
15477                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15478                "Only intentfilter verification agents can verify applications");
15479
15480        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15481        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15482                Binder.getCallingUid(), verificationCode, failedDomains);
15483        msg.arg1 = id;
15484        msg.obj = response;
15485        mHandler.sendMessage(msg);
15486    }
15487
15488    @Override
15489    public int getIntentVerificationStatus(String packageName, int userId) {
15490        final int callingUid = Binder.getCallingUid();
15491        if (UserHandle.getUserId(callingUid) != userId) {
15492            mContext.enforceCallingOrSelfPermission(
15493                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15494                    "getIntentVerificationStatus" + userId);
15495        }
15496        if (getInstantAppPackageName(callingUid) != null) {
15497            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15498        }
15499        synchronized (mPackages) {
15500            final PackageSetting ps = mSettings.mPackages.get(packageName);
15501            if (ps == null
15502                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15503                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15504            }
15505            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15506        }
15507    }
15508
15509    @Override
15510    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15511        mContext.enforceCallingOrSelfPermission(
15512                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15513
15514        boolean result = false;
15515        synchronized (mPackages) {
15516            final PackageSetting ps = mSettings.mPackages.get(packageName);
15517            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15518                return false;
15519            }
15520            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15521        }
15522        if (result) {
15523            scheduleWritePackageRestrictionsLocked(userId);
15524        }
15525        return result;
15526    }
15527
15528    @Override
15529    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15530            String packageName) {
15531        final int callingUid = Binder.getCallingUid();
15532        if (getInstantAppPackageName(callingUid) != null) {
15533            return ParceledListSlice.emptyList();
15534        }
15535        synchronized (mPackages) {
15536            final PackageSetting ps = mSettings.mPackages.get(packageName);
15537            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15538                return ParceledListSlice.emptyList();
15539            }
15540            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15541        }
15542    }
15543
15544    @Override
15545    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15546        if (TextUtils.isEmpty(packageName)) {
15547            return ParceledListSlice.emptyList();
15548        }
15549        final int callingUid = Binder.getCallingUid();
15550        final int callingUserId = UserHandle.getUserId(callingUid);
15551        synchronized (mPackages) {
15552            PackageParser.Package pkg = mPackages.get(packageName);
15553            if (pkg == null || pkg.activities == null) {
15554                return ParceledListSlice.emptyList();
15555            }
15556            if (pkg.mExtras == null) {
15557                return ParceledListSlice.emptyList();
15558            }
15559            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15560            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15561                return ParceledListSlice.emptyList();
15562            }
15563            final int count = pkg.activities.size();
15564            ArrayList<IntentFilter> result = new ArrayList<>();
15565            for (int n=0; n<count; n++) {
15566                PackageParser.Activity activity = pkg.activities.get(n);
15567                if (activity.intents != null && activity.intents.size() > 0) {
15568                    result.addAll(activity.intents);
15569                }
15570            }
15571            return new ParceledListSlice<>(result);
15572        }
15573    }
15574
15575    @Override
15576    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15577        mContext.enforceCallingOrSelfPermission(
15578                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15579        if (UserHandle.getCallingUserId() != userId) {
15580            mContext.enforceCallingOrSelfPermission(
15581                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15582        }
15583
15584        synchronized (mPackages) {
15585            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15586            if (packageName != null) {
15587                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15588                        packageName, userId);
15589            }
15590            return result;
15591        }
15592    }
15593
15594    @Override
15595    public String getDefaultBrowserPackageName(int userId) {
15596        if (UserHandle.getCallingUserId() != userId) {
15597            mContext.enforceCallingOrSelfPermission(
15598                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15599        }
15600        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15601            return null;
15602        }
15603        synchronized (mPackages) {
15604            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15605        }
15606    }
15607
15608    /**
15609     * Get the "allow unknown sources" setting.
15610     *
15611     * @return the current "allow unknown sources" setting
15612     */
15613    private int getUnknownSourcesSettings() {
15614        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15615                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15616                -1);
15617    }
15618
15619    @Override
15620    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15621        final int callingUid = Binder.getCallingUid();
15622        if (getInstantAppPackageName(callingUid) != null) {
15623            return;
15624        }
15625        // writer
15626        synchronized (mPackages) {
15627            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15628            if (targetPackageSetting == null
15629                    || filterAppAccessLPr(
15630                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15631                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15632            }
15633
15634            PackageSetting installerPackageSetting;
15635            if (installerPackageName != null) {
15636                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15637                if (installerPackageSetting == null) {
15638                    throw new IllegalArgumentException("Unknown installer package: "
15639                            + installerPackageName);
15640                }
15641            } else {
15642                installerPackageSetting = null;
15643            }
15644
15645            Signature[] callerSignature;
15646            Object obj = mSettings.getUserIdLPr(callingUid);
15647            if (obj != null) {
15648                if (obj instanceof SharedUserSetting) {
15649                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15650                } else if (obj instanceof PackageSetting) {
15651                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15652                } else {
15653                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15654                }
15655            } else {
15656                throw new SecurityException("Unknown calling UID: " + callingUid);
15657            }
15658
15659            // Verify: can't set installerPackageName to a package that is
15660            // not signed with the same cert as the caller.
15661            if (installerPackageSetting != null) {
15662                if (compareSignatures(callerSignature,
15663                        installerPackageSetting.signatures.mSignatures)
15664                        != PackageManager.SIGNATURE_MATCH) {
15665                    throw new SecurityException(
15666                            "Caller does not have same cert as new installer package "
15667                            + installerPackageName);
15668                }
15669            }
15670
15671            // Verify: if target already has an installer package, it must
15672            // be signed with the same cert as the caller.
15673            if (targetPackageSetting.installerPackageName != null) {
15674                PackageSetting setting = mSettings.mPackages.get(
15675                        targetPackageSetting.installerPackageName);
15676                // If the currently set package isn't valid, then it's always
15677                // okay to change it.
15678                if (setting != null) {
15679                    if (compareSignatures(callerSignature,
15680                            setting.signatures.mSignatures)
15681                            != PackageManager.SIGNATURE_MATCH) {
15682                        throw new SecurityException(
15683                                "Caller does not have same cert as old installer package "
15684                                + targetPackageSetting.installerPackageName);
15685                    }
15686                }
15687            }
15688
15689            // Okay!
15690            targetPackageSetting.installerPackageName = installerPackageName;
15691            if (installerPackageName != null) {
15692                mSettings.mInstallerPackages.add(installerPackageName);
15693            }
15694            scheduleWriteSettingsLocked();
15695        }
15696    }
15697
15698    @Override
15699    public void setApplicationCategoryHint(String packageName, int categoryHint,
15700            String callerPackageName) {
15701        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15702            throw new SecurityException("Instant applications don't have access to this method");
15703        }
15704        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15705                callerPackageName);
15706        synchronized (mPackages) {
15707            PackageSetting ps = mSettings.mPackages.get(packageName);
15708            if (ps == null) {
15709                throw new IllegalArgumentException("Unknown target package " + packageName);
15710            }
15711            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15712                throw new IllegalArgumentException("Unknown target package " + packageName);
15713            }
15714            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15715                throw new IllegalArgumentException("Calling package " + callerPackageName
15716                        + " is not installer for " + packageName);
15717            }
15718
15719            if (ps.categoryHint != categoryHint) {
15720                ps.categoryHint = categoryHint;
15721                scheduleWriteSettingsLocked();
15722            }
15723        }
15724    }
15725
15726    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15727        // Queue up an async operation since the package installation may take a little while.
15728        mHandler.post(new Runnable() {
15729            public void run() {
15730                mHandler.removeCallbacks(this);
15731                 // Result object to be returned
15732                PackageInstalledInfo res = new PackageInstalledInfo();
15733                res.setReturnCode(currentStatus);
15734                res.uid = -1;
15735                res.pkg = null;
15736                res.removedInfo = null;
15737                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15738                    args.doPreInstall(res.returnCode);
15739                    synchronized (mInstallLock) {
15740                        installPackageTracedLI(args, res);
15741                    }
15742                    args.doPostInstall(res.returnCode, res.uid);
15743                }
15744
15745                // A restore should be performed at this point if (a) the install
15746                // succeeded, (b) the operation is not an update, and (c) the new
15747                // package has not opted out of backup participation.
15748                final boolean update = res.removedInfo != null
15749                        && res.removedInfo.removedPackage != null;
15750                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15751                boolean doRestore = !update
15752                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15753
15754                // Set up the post-install work request bookkeeping.  This will be used
15755                // and cleaned up by the post-install event handling regardless of whether
15756                // there's a restore pass performed.  Token values are >= 1.
15757                int token;
15758                if (mNextInstallToken < 0) mNextInstallToken = 1;
15759                token = mNextInstallToken++;
15760
15761                PostInstallData data = new PostInstallData(args, res);
15762                mRunningInstalls.put(token, data);
15763                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15764
15765                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15766                    // Pass responsibility to the Backup Manager.  It will perform a
15767                    // restore if appropriate, then pass responsibility back to the
15768                    // Package Manager to run the post-install observer callbacks
15769                    // and broadcasts.
15770                    IBackupManager bm = IBackupManager.Stub.asInterface(
15771                            ServiceManager.getService(Context.BACKUP_SERVICE));
15772                    if (bm != null) {
15773                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15774                                + " to BM for possible restore");
15775                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15776                        try {
15777                            // TODO: http://b/22388012
15778                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15779                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15780                            } else {
15781                                doRestore = false;
15782                            }
15783                        } catch (RemoteException e) {
15784                            // can't happen; the backup manager is local
15785                        } catch (Exception e) {
15786                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15787                            doRestore = false;
15788                        }
15789                    } else {
15790                        Slog.e(TAG, "Backup Manager not found!");
15791                        doRestore = false;
15792                    }
15793                }
15794
15795                if (!doRestore) {
15796                    // No restore possible, or the Backup Manager was mysteriously not
15797                    // available -- just fire the post-install work request directly.
15798                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15799
15800                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15801
15802                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15803                    mHandler.sendMessage(msg);
15804                }
15805            }
15806        });
15807    }
15808
15809    /**
15810     * Callback from PackageSettings whenever an app is first transitioned out of the
15811     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15812     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15813     * here whether the app is the target of an ongoing install, and only send the
15814     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15815     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15816     * handling.
15817     */
15818    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15819        // Serialize this with the rest of the install-process message chain.  In the
15820        // restore-at-install case, this Runnable will necessarily run before the
15821        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15822        // are coherent.  In the non-restore case, the app has already completed install
15823        // and been launched through some other means, so it is not in a problematic
15824        // state for observers to see the FIRST_LAUNCH signal.
15825        mHandler.post(new Runnable() {
15826            @Override
15827            public void run() {
15828                for (int i = 0; i < mRunningInstalls.size(); i++) {
15829                    final PostInstallData data = mRunningInstalls.valueAt(i);
15830                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15831                        continue;
15832                    }
15833                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15834                        // right package; but is it for the right user?
15835                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15836                            if (userId == data.res.newUsers[uIndex]) {
15837                                if (DEBUG_BACKUP) {
15838                                    Slog.i(TAG, "Package " + pkgName
15839                                            + " being restored so deferring FIRST_LAUNCH");
15840                                }
15841                                return;
15842                            }
15843                        }
15844                    }
15845                }
15846                // didn't find it, so not being restored
15847                if (DEBUG_BACKUP) {
15848                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15849                }
15850                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15851            }
15852        });
15853    }
15854
15855    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15856        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15857                installerPkg, null, userIds);
15858    }
15859
15860    private abstract class HandlerParams {
15861        private static final int MAX_RETRIES = 4;
15862
15863        /**
15864         * Number of times startCopy() has been attempted and had a non-fatal
15865         * error.
15866         */
15867        private int mRetries = 0;
15868
15869        /** User handle for the user requesting the information or installation. */
15870        private final UserHandle mUser;
15871        String traceMethod;
15872        int traceCookie;
15873
15874        HandlerParams(UserHandle user) {
15875            mUser = user;
15876        }
15877
15878        UserHandle getUser() {
15879            return mUser;
15880        }
15881
15882        HandlerParams setTraceMethod(String traceMethod) {
15883            this.traceMethod = traceMethod;
15884            return this;
15885        }
15886
15887        HandlerParams setTraceCookie(int traceCookie) {
15888            this.traceCookie = traceCookie;
15889            return this;
15890        }
15891
15892        final boolean startCopy() {
15893            boolean res;
15894            try {
15895                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15896
15897                if (++mRetries > MAX_RETRIES) {
15898                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15899                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15900                    handleServiceError();
15901                    return false;
15902                } else {
15903                    handleStartCopy();
15904                    res = true;
15905                }
15906            } catch (RemoteException e) {
15907                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15908                mHandler.sendEmptyMessage(MCS_RECONNECT);
15909                res = false;
15910            }
15911            handleReturnCode();
15912            return res;
15913        }
15914
15915        final void serviceError() {
15916            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15917            handleServiceError();
15918            handleReturnCode();
15919        }
15920
15921        abstract void handleStartCopy() throws RemoteException;
15922        abstract void handleServiceError();
15923        abstract void handleReturnCode();
15924    }
15925
15926    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15927        for (File path : paths) {
15928            try {
15929                mcs.clearDirectory(path.getAbsolutePath());
15930            } catch (RemoteException e) {
15931            }
15932        }
15933    }
15934
15935    static class OriginInfo {
15936        /**
15937         * Location where install is coming from, before it has been
15938         * copied/renamed into place. This could be a single monolithic APK
15939         * file, or a cluster directory. This location may be untrusted.
15940         */
15941        final File file;
15942        final String cid;
15943
15944        /**
15945         * Flag indicating that {@link #file} or {@link #cid} has already been
15946         * staged, meaning downstream users don't need to defensively copy the
15947         * contents.
15948         */
15949        final boolean staged;
15950
15951        /**
15952         * Flag indicating that {@link #file} or {@link #cid} is an already
15953         * installed app that is being moved.
15954         */
15955        final boolean existing;
15956
15957        final String resolvedPath;
15958        final File resolvedFile;
15959
15960        static OriginInfo fromNothing() {
15961            return new OriginInfo(null, null, false, false);
15962        }
15963
15964        static OriginInfo fromUntrustedFile(File file) {
15965            return new OriginInfo(file, null, false, false);
15966        }
15967
15968        static OriginInfo fromExistingFile(File file) {
15969            return new OriginInfo(file, null, false, true);
15970        }
15971
15972        static OriginInfo fromStagedFile(File file) {
15973            return new OriginInfo(file, null, true, false);
15974        }
15975
15976        static OriginInfo fromStagedContainer(String cid) {
15977            return new OriginInfo(null, cid, true, false);
15978        }
15979
15980        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15981            this.file = file;
15982            this.cid = cid;
15983            this.staged = staged;
15984            this.existing = existing;
15985
15986            if (cid != null) {
15987                resolvedPath = PackageHelper.getSdDir(cid);
15988                resolvedFile = new File(resolvedPath);
15989            } else if (file != null) {
15990                resolvedPath = file.getAbsolutePath();
15991                resolvedFile = file;
15992            } else {
15993                resolvedPath = null;
15994                resolvedFile = null;
15995            }
15996        }
15997    }
15998
15999    static class MoveInfo {
16000        final int moveId;
16001        final String fromUuid;
16002        final String toUuid;
16003        final String packageName;
16004        final String dataAppName;
16005        final int appId;
16006        final String seinfo;
16007        final int targetSdkVersion;
16008
16009        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16010                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16011            this.moveId = moveId;
16012            this.fromUuid = fromUuid;
16013            this.toUuid = toUuid;
16014            this.packageName = packageName;
16015            this.dataAppName = dataAppName;
16016            this.appId = appId;
16017            this.seinfo = seinfo;
16018            this.targetSdkVersion = targetSdkVersion;
16019        }
16020    }
16021
16022    static class VerificationInfo {
16023        /** A constant used to indicate that a uid value is not present. */
16024        public static final int NO_UID = -1;
16025
16026        /** URI referencing where the package was downloaded from. */
16027        final Uri originatingUri;
16028
16029        /** HTTP referrer URI associated with the originatingURI. */
16030        final Uri referrer;
16031
16032        /** UID of the application that the install request originated from. */
16033        final int originatingUid;
16034
16035        /** UID of application requesting the install */
16036        final int installerUid;
16037
16038        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16039            this.originatingUri = originatingUri;
16040            this.referrer = referrer;
16041            this.originatingUid = originatingUid;
16042            this.installerUid = installerUid;
16043        }
16044    }
16045
16046    class InstallParams extends HandlerParams {
16047        final OriginInfo origin;
16048        final MoveInfo move;
16049        final IPackageInstallObserver2 observer;
16050        int installFlags;
16051        final String installerPackageName;
16052        final String volumeUuid;
16053        private InstallArgs mArgs;
16054        private int mRet;
16055        final String packageAbiOverride;
16056        final String[] grantedRuntimePermissions;
16057        final VerificationInfo verificationInfo;
16058        final Certificate[][] certificates;
16059        final int installReason;
16060
16061        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16062                int installFlags, String installerPackageName, String volumeUuid,
16063                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16064                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16065            super(user);
16066            this.origin = origin;
16067            this.move = move;
16068            this.observer = observer;
16069            this.installFlags = installFlags;
16070            this.installerPackageName = installerPackageName;
16071            this.volumeUuid = volumeUuid;
16072            this.verificationInfo = verificationInfo;
16073            this.packageAbiOverride = packageAbiOverride;
16074            this.grantedRuntimePermissions = grantedPermissions;
16075            this.certificates = certificates;
16076            this.installReason = installReason;
16077        }
16078
16079        @Override
16080        public String toString() {
16081            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16082                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16083        }
16084
16085        private int installLocationPolicy(PackageInfoLite pkgLite) {
16086            String packageName = pkgLite.packageName;
16087            int installLocation = pkgLite.installLocation;
16088            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16089            // reader
16090            synchronized (mPackages) {
16091                // Currently installed package which the new package is attempting to replace or
16092                // null if no such package is installed.
16093                PackageParser.Package installedPkg = mPackages.get(packageName);
16094                // Package which currently owns the data which the new package will own if installed.
16095                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16096                // will be null whereas dataOwnerPkg will contain information about the package
16097                // which was uninstalled while keeping its data.
16098                PackageParser.Package dataOwnerPkg = installedPkg;
16099                if (dataOwnerPkg  == null) {
16100                    PackageSetting ps = mSettings.mPackages.get(packageName);
16101                    if (ps != null) {
16102                        dataOwnerPkg = ps.pkg;
16103                    }
16104                }
16105
16106                if (dataOwnerPkg != null) {
16107                    // If installed, the package will get access to data left on the device by its
16108                    // predecessor. As a security measure, this is permited only if this is not a
16109                    // version downgrade or if the predecessor package is marked as debuggable and
16110                    // a downgrade is explicitly requested.
16111                    //
16112                    // On debuggable platform builds, downgrades are permitted even for
16113                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16114                    // not offer security guarantees and thus it's OK to disable some security
16115                    // mechanisms to make debugging/testing easier on those builds. However, even on
16116                    // debuggable builds downgrades of packages are permitted only if requested via
16117                    // installFlags. This is because we aim to keep the behavior of debuggable
16118                    // platform builds as close as possible to the behavior of non-debuggable
16119                    // platform builds.
16120                    final boolean downgradeRequested =
16121                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16122                    final boolean packageDebuggable =
16123                                (dataOwnerPkg.applicationInfo.flags
16124                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16125                    final boolean downgradePermitted =
16126                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16127                    if (!downgradePermitted) {
16128                        try {
16129                            checkDowngrade(dataOwnerPkg, pkgLite);
16130                        } catch (PackageManagerException e) {
16131                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16132                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16133                        }
16134                    }
16135                }
16136
16137                if (installedPkg != null) {
16138                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16139                        // Check for updated system application.
16140                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16141                            if (onSd) {
16142                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16143                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16144                            }
16145                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16146                        } else {
16147                            if (onSd) {
16148                                // Install flag overrides everything.
16149                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16150                            }
16151                            // If current upgrade specifies particular preference
16152                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16153                                // Application explicitly specified internal.
16154                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16155                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16156                                // App explictly prefers external. Let policy decide
16157                            } else {
16158                                // Prefer previous location
16159                                if (isExternal(installedPkg)) {
16160                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16161                                }
16162                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16163                            }
16164                        }
16165                    } else {
16166                        // Invalid install. Return error code
16167                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16168                    }
16169                }
16170            }
16171            // All the special cases have been taken care of.
16172            // Return result based on recommended install location.
16173            if (onSd) {
16174                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16175            }
16176            return pkgLite.recommendedInstallLocation;
16177        }
16178
16179        /*
16180         * Invoke remote method to get package information and install
16181         * location values. Override install location based on default
16182         * policy if needed and then create install arguments based
16183         * on the install location.
16184         */
16185        public void handleStartCopy() throws RemoteException {
16186            int ret = PackageManager.INSTALL_SUCCEEDED;
16187
16188            // If we're already staged, we've firmly committed to an install location
16189            if (origin.staged) {
16190                if (origin.file != null) {
16191                    installFlags |= PackageManager.INSTALL_INTERNAL;
16192                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16193                } else if (origin.cid != null) {
16194                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16195                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16196                } else {
16197                    throw new IllegalStateException("Invalid stage location");
16198                }
16199            }
16200
16201            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16202            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16203            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16204            PackageInfoLite pkgLite = null;
16205
16206            if (onInt && onSd) {
16207                // Check if both bits are set.
16208                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16209                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16210            } else if (onSd && ephemeral) {
16211                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16212                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16213            } else {
16214                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16215                        packageAbiOverride);
16216
16217                if (DEBUG_EPHEMERAL && ephemeral) {
16218                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16219                }
16220
16221                /*
16222                 * If we have too little free space, try to free cache
16223                 * before giving up.
16224                 */
16225                if (!origin.staged && pkgLite.recommendedInstallLocation
16226                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16227                    // TODO: focus freeing disk space on the target device
16228                    final StorageManager storage = StorageManager.from(mContext);
16229                    final long lowThreshold = storage.getStorageLowBytes(
16230                            Environment.getDataDirectory());
16231
16232                    final long sizeBytes = mContainerService.calculateInstalledSize(
16233                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16234
16235                    try {
16236                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16237                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16238                                installFlags, packageAbiOverride);
16239                    } catch (InstallerException e) {
16240                        Slog.w(TAG, "Failed to free cache", e);
16241                    }
16242
16243                    /*
16244                     * The cache free must have deleted the file we
16245                     * downloaded to install.
16246                     *
16247                     * TODO: fix the "freeCache" call to not delete
16248                     *       the file we care about.
16249                     */
16250                    if (pkgLite.recommendedInstallLocation
16251                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16252                        pkgLite.recommendedInstallLocation
16253                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16254                    }
16255                }
16256            }
16257
16258            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16259                int loc = pkgLite.recommendedInstallLocation;
16260                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16261                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16262                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16263                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16264                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16265                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16266                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16267                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16268                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16269                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16270                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16271                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16272                } else {
16273                    // Override with defaults if needed.
16274                    loc = installLocationPolicy(pkgLite);
16275                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16276                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16277                    } else if (!onSd && !onInt) {
16278                        // Override install location with flags
16279                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16280                            // Set the flag to install on external media.
16281                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16282                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16283                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16284                            if (DEBUG_EPHEMERAL) {
16285                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16286                            }
16287                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16288                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16289                                    |PackageManager.INSTALL_INTERNAL);
16290                        } else {
16291                            // Make sure the flag for installing on external
16292                            // media is unset
16293                            installFlags |= PackageManager.INSTALL_INTERNAL;
16294                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16295                        }
16296                    }
16297                }
16298            }
16299
16300            final InstallArgs args = createInstallArgs(this);
16301            mArgs = args;
16302
16303            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16304                // TODO: http://b/22976637
16305                // Apps installed for "all" users use the device owner to verify the app
16306                UserHandle verifierUser = getUser();
16307                if (verifierUser == UserHandle.ALL) {
16308                    verifierUser = UserHandle.SYSTEM;
16309                }
16310
16311                /*
16312                 * Determine if we have any installed package verifiers. If we
16313                 * do, then we'll defer to them to verify the packages.
16314                 */
16315                final int requiredUid = mRequiredVerifierPackage == null ? -1
16316                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16317                                verifierUser.getIdentifier());
16318                final int installerUid =
16319                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16320                if (!origin.existing && requiredUid != -1
16321                        && isVerificationEnabled(
16322                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16323                    final Intent verification = new Intent(
16324                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16325                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16326                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16327                            PACKAGE_MIME_TYPE);
16328                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16329
16330                    // Query all live verifiers based on current user state
16331                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16332                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16333                            false /*allowDynamicSplits*/);
16334
16335                    if (DEBUG_VERIFY) {
16336                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16337                                + verification.toString() + " with " + pkgLite.verifiers.length
16338                                + " optional verifiers");
16339                    }
16340
16341                    final int verificationId = mPendingVerificationToken++;
16342
16343                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16344
16345                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16346                            installerPackageName);
16347
16348                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16349                            installFlags);
16350
16351                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16352                            pkgLite.packageName);
16353
16354                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16355                            pkgLite.versionCode);
16356
16357                    if (verificationInfo != null) {
16358                        if (verificationInfo.originatingUri != null) {
16359                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16360                                    verificationInfo.originatingUri);
16361                        }
16362                        if (verificationInfo.referrer != null) {
16363                            verification.putExtra(Intent.EXTRA_REFERRER,
16364                                    verificationInfo.referrer);
16365                        }
16366                        if (verificationInfo.originatingUid >= 0) {
16367                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16368                                    verificationInfo.originatingUid);
16369                        }
16370                        if (verificationInfo.installerUid >= 0) {
16371                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16372                                    verificationInfo.installerUid);
16373                        }
16374                    }
16375
16376                    final PackageVerificationState verificationState = new PackageVerificationState(
16377                            requiredUid, args);
16378
16379                    mPendingVerification.append(verificationId, verificationState);
16380
16381                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16382                            receivers, verificationState);
16383
16384                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16385                    final long idleDuration = getVerificationTimeout();
16386
16387                    /*
16388                     * If any sufficient verifiers were listed in the package
16389                     * manifest, attempt to ask them.
16390                     */
16391                    if (sufficientVerifiers != null) {
16392                        final int N = sufficientVerifiers.size();
16393                        if (N == 0) {
16394                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16395                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16396                        } else {
16397                            for (int i = 0; i < N; i++) {
16398                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16399                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16400                                        verifierComponent.getPackageName(), idleDuration,
16401                                        verifierUser.getIdentifier(), false, "package verifier");
16402
16403                                final Intent sufficientIntent = new Intent(verification);
16404                                sufficientIntent.setComponent(verifierComponent);
16405                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16406                            }
16407                        }
16408                    }
16409
16410                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16411                            mRequiredVerifierPackage, receivers);
16412                    if (ret == PackageManager.INSTALL_SUCCEEDED
16413                            && mRequiredVerifierPackage != null) {
16414                        Trace.asyncTraceBegin(
16415                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16416                        /*
16417                         * Send the intent to the required verification agent,
16418                         * but only start the verification timeout after the
16419                         * target BroadcastReceivers have run.
16420                         */
16421                        verification.setComponent(requiredVerifierComponent);
16422                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16423                                mRequiredVerifierPackage, idleDuration,
16424                                verifierUser.getIdentifier(), false, "package verifier");
16425                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16426                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16427                                new BroadcastReceiver() {
16428                                    @Override
16429                                    public void onReceive(Context context, Intent intent) {
16430                                        final Message msg = mHandler
16431                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16432                                        msg.arg1 = verificationId;
16433                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16434                                    }
16435                                }, null, 0, null, null);
16436
16437                        /*
16438                         * We don't want the copy to proceed until verification
16439                         * succeeds, so null out this field.
16440                         */
16441                        mArgs = null;
16442                    }
16443                } else {
16444                    /*
16445                     * No package verification is enabled, so immediately start
16446                     * the remote call to initiate copy using temporary file.
16447                     */
16448                    ret = args.copyApk(mContainerService, true);
16449                }
16450            }
16451
16452            mRet = ret;
16453        }
16454
16455        @Override
16456        void handleReturnCode() {
16457            // If mArgs is null, then MCS couldn't be reached. When it
16458            // reconnects, it will try again to install. At that point, this
16459            // will succeed.
16460            if (mArgs != null) {
16461                processPendingInstall(mArgs, mRet);
16462            }
16463        }
16464
16465        @Override
16466        void handleServiceError() {
16467            mArgs = createInstallArgs(this);
16468            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16469        }
16470
16471        public boolean isForwardLocked() {
16472            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16473        }
16474    }
16475
16476    /**
16477     * Used during creation of InstallArgs
16478     *
16479     * @param installFlags package installation flags
16480     * @return true if should be installed on external storage
16481     */
16482    private static boolean installOnExternalAsec(int installFlags) {
16483        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16484            return false;
16485        }
16486        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16487            return true;
16488        }
16489        return false;
16490    }
16491
16492    /**
16493     * Used during creation of InstallArgs
16494     *
16495     * @param installFlags package installation flags
16496     * @return true if should be installed as forward locked
16497     */
16498    private static boolean installForwardLocked(int installFlags) {
16499        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16500    }
16501
16502    private InstallArgs createInstallArgs(InstallParams params) {
16503        if (params.move != null) {
16504            return new MoveInstallArgs(params);
16505        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16506            return new AsecInstallArgs(params);
16507        } else {
16508            return new FileInstallArgs(params);
16509        }
16510    }
16511
16512    /**
16513     * Create args that describe an existing installed package. Typically used
16514     * when cleaning up old installs, or used as a move source.
16515     */
16516    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16517            String resourcePath, String[] instructionSets) {
16518        final boolean isInAsec;
16519        if (installOnExternalAsec(installFlags)) {
16520            /* Apps on SD card are always in ASEC containers. */
16521            isInAsec = true;
16522        } else if (installForwardLocked(installFlags)
16523                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16524            /*
16525             * Forward-locked apps are only in ASEC containers if they're the
16526             * new style
16527             */
16528            isInAsec = true;
16529        } else {
16530            isInAsec = false;
16531        }
16532
16533        if (isInAsec) {
16534            return new AsecInstallArgs(codePath, instructionSets,
16535                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16536        } else {
16537            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16538        }
16539    }
16540
16541    static abstract class InstallArgs {
16542        /** @see InstallParams#origin */
16543        final OriginInfo origin;
16544        /** @see InstallParams#move */
16545        final MoveInfo move;
16546
16547        final IPackageInstallObserver2 observer;
16548        // Always refers to PackageManager flags only
16549        final int installFlags;
16550        final String installerPackageName;
16551        final String volumeUuid;
16552        final UserHandle user;
16553        final String abiOverride;
16554        final String[] installGrantPermissions;
16555        /** If non-null, drop an async trace when the install completes */
16556        final String traceMethod;
16557        final int traceCookie;
16558        final Certificate[][] certificates;
16559        final int installReason;
16560
16561        // The list of instruction sets supported by this app. This is currently
16562        // only used during the rmdex() phase to clean up resources. We can get rid of this
16563        // if we move dex files under the common app path.
16564        /* nullable */ String[] instructionSets;
16565
16566        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16567                int installFlags, String installerPackageName, String volumeUuid,
16568                UserHandle user, String[] instructionSets,
16569                String abiOverride, String[] installGrantPermissions,
16570                String traceMethod, int traceCookie, Certificate[][] certificates,
16571                int installReason) {
16572            this.origin = origin;
16573            this.move = move;
16574            this.installFlags = installFlags;
16575            this.observer = observer;
16576            this.installerPackageName = installerPackageName;
16577            this.volumeUuid = volumeUuid;
16578            this.user = user;
16579            this.instructionSets = instructionSets;
16580            this.abiOverride = abiOverride;
16581            this.installGrantPermissions = installGrantPermissions;
16582            this.traceMethod = traceMethod;
16583            this.traceCookie = traceCookie;
16584            this.certificates = certificates;
16585            this.installReason = installReason;
16586        }
16587
16588        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16589        abstract int doPreInstall(int status);
16590
16591        /**
16592         * Rename package into final resting place. All paths on the given
16593         * scanned package should be updated to reflect the rename.
16594         */
16595        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16596        abstract int doPostInstall(int status, int uid);
16597
16598        /** @see PackageSettingBase#codePathString */
16599        abstract String getCodePath();
16600        /** @see PackageSettingBase#resourcePathString */
16601        abstract String getResourcePath();
16602
16603        // Need installer lock especially for dex file removal.
16604        abstract void cleanUpResourcesLI();
16605        abstract boolean doPostDeleteLI(boolean delete);
16606
16607        /**
16608         * Called before the source arguments are copied. This is used mostly
16609         * for MoveParams when it needs to read the source file to put it in the
16610         * destination.
16611         */
16612        int doPreCopy() {
16613            return PackageManager.INSTALL_SUCCEEDED;
16614        }
16615
16616        /**
16617         * Called after the source arguments are copied. This is used mostly for
16618         * MoveParams when it needs to read the source file to put it in the
16619         * destination.
16620         */
16621        int doPostCopy(int uid) {
16622            return PackageManager.INSTALL_SUCCEEDED;
16623        }
16624
16625        protected boolean isFwdLocked() {
16626            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16627        }
16628
16629        protected boolean isExternalAsec() {
16630            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16631        }
16632
16633        protected boolean isEphemeral() {
16634            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16635        }
16636
16637        UserHandle getUser() {
16638            return user;
16639        }
16640    }
16641
16642    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16643        if (!allCodePaths.isEmpty()) {
16644            if (instructionSets == null) {
16645                throw new IllegalStateException("instructionSet == null");
16646            }
16647            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16648            for (String codePath : allCodePaths) {
16649                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16650                    try {
16651                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16652                    } catch (InstallerException ignored) {
16653                    }
16654                }
16655            }
16656        }
16657    }
16658
16659    /**
16660     * Logic to handle installation of non-ASEC applications, including copying
16661     * and renaming logic.
16662     */
16663    class FileInstallArgs extends InstallArgs {
16664        private File codeFile;
16665        private File resourceFile;
16666
16667        // Example topology:
16668        // /data/app/com.example/base.apk
16669        // /data/app/com.example/split_foo.apk
16670        // /data/app/com.example/lib/arm/libfoo.so
16671        // /data/app/com.example/lib/arm64/libfoo.so
16672        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16673
16674        /** New install */
16675        FileInstallArgs(InstallParams params) {
16676            super(params.origin, params.move, params.observer, params.installFlags,
16677                    params.installerPackageName, params.volumeUuid,
16678                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16679                    params.grantedRuntimePermissions,
16680                    params.traceMethod, params.traceCookie, params.certificates,
16681                    params.installReason);
16682            if (isFwdLocked()) {
16683                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16684            }
16685        }
16686
16687        /** Existing install */
16688        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16689            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16690                    null, null, null, 0, null /*certificates*/,
16691                    PackageManager.INSTALL_REASON_UNKNOWN);
16692            this.codeFile = (codePath != null) ? new File(codePath) : null;
16693            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16694        }
16695
16696        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16697            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16698            try {
16699                return doCopyApk(imcs, temp);
16700            } finally {
16701                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16702            }
16703        }
16704
16705        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16706            if (origin.staged) {
16707                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16708                codeFile = origin.file;
16709                resourceFile = origin.file;
16710                return PackageManager.INSTALL_SUCCEEDED;
16711            }
16712
16713            try {
16714                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16715                final File tempDir =
16716                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16717                codeFile = tempDir;
16718                resourceFile = tempDir;
16719            } catch (IOException e) {
16720                Slog.w(TAG, "Failed to create copy file: " + e);
16721                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16722            }
16723
16724            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16725                @Override
16726                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16727                    if (!FileUtils.isValidExtFilename(name)) {
16728                        throw new IllegalArgumentException("Invalid filename: " + name);
16729                    }
16730                    try {
16731                        final File file = new File(codeFile, name);
16732                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16733                                O_RDWR | O_CREAT, 0644);
16734                        Os.chmod(file.getAbsolutePath(), 0644);
16735                        return new ParcelFileDescriptor(fd);
16736                    } catch (ErrnoException e) {
16737                        throw new RemoteException("Failed to open: " + e.getMessage());
16738                    }
16739                }
16740            };
16741
16742            int ret = PackageManager.INSTALL_SUCCEEDED;
16743            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16744            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16745                Slog.e(TAG, "Failed to copy package");
16746                return ret;
16747            }
16748
16749            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16750            NativeLibraryHelper.Handle handle = null;
16751            try {
16752                handle = NativeLibraryHelper.Handle.create(codeFile);
16753                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16754                        abiOverride);
16755            } catch (IOException e) {
16756                Slog.e(TAG, "Copying native libraries failed", e);
16757                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16758            } finally {
16759                IoUtils.closeQuietly(handle);
16760            }
16761
16762            return ret;
16763        }
16764
16765        int doPreInstall(int status) {
16766            if (status != PackageManager.INSTALL_SUCCEEDED) {
16767                cleanUp();
16768            }
16769            return status;
16770        }
16771
16772        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16773            if (status != PackageManager.INSTALL_SUCCEEDED) {
16774                cleanUp();
16775                return false;
16776            }
16777
16778            final File targetDir = codeFile.getParentFile();
16779            final File beforeCodeFile = codeFile;
16780            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16781
16782            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16783            try {
16784                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16785            } catch (ErrnoException e) {
16786                Slog.w(TAG, "Failed to rename", e);
16787                return false;
16788            }
16789
16790            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16791                Slog.w(TAG, "Failed to restorecon");
16792                return false;
16793            }
16794
16795            // Reflect the rename internally
16796            codeFile = afterCodeFile;
16797            resourceFile = afterCodeFile;
16798
16799            // Reflect the rename in scanned details
16800            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16801            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16802                    afterCodeFile, pkg.baseCodePath));
16803            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16804                    afterCodeFile, pkg.splitCodePaths));
16805
16806            // Reflect the rename in app info
16807            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16808            pkg.setApplicationInfoCodePath(pkg.codePath);
16809            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16810            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16811            pkg.setApplicationInfoResourcePath(pkg.codePath);
16812            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16813            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16814
16815            return true;
16816        }
16817
16818        int doPostInstall(int status, int uid) {
16819            if (status != PackageManager.INSTALL_SUCCEEDED) {
16820                cleanUp();
16821            }
16822            return status;
16823        }
16824
16825        @Override
16826        String getCodePath() {
16827            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16828        }
16829
16830        @Override
16831        String getResourcePath() {
16832            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16833        }
16834
16835        private boolean cleanUp() {
16836            if (codeFile == null || !codeFile.exists()) {
16837                return false;
16838            }
16839
16840            removeCodePathLI(codeFile);
16841
16842            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16843                resourceFile.delete();
16844            }
16845
16846            return true;
16847        }
16848
16849        void cleanUpResourcesLI() {
16850            // Try enumerating all code paths before deleting
16851            List<String> allCodePaths = Collections.EMPTY_LIST;
16852            if (codeFile != null && codeFile.exists()) {
16853                try {
16854                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16855                    allCodePaths = pkg.getAllCodePaths();
16856                } catch (PackageParserException e) {
16857                    // Ignored; we tried our best
16858                }
16859            }
16860
16861            cleanUp();
16862            removeDexFiles(allCodePaths, instructionSets);
16863        }
16864
16865        boolean doPostDeleteLI(boolean delete) {
16866            // XXX err, shouldn't we respect the delete flag?
16867            cleanUpResourcesLI();
16868            return true;
16869        }
16870    }
16871
16872    private boolean isAsecExternal(String cid) {
16873        final String asecPath = PackageHelper.getSdFilesystem(cid);
16874        return !asecPath.startsWith(mAsecInternalPath);
16875    }
16876
16877    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16878            PackageManagerException {
16879        if (copyRet < 0) {
16880            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16881                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16882                throw new PackageManagerException(copyRet, message);
16883            }
16884        }
16885    }
16886
16887    /**
16888     * Extract the StorageManagerService "container ID" from the full code path of an
16889     * .apk.
16890     */
16891    static String cidFromCodePath(String fullCodePath) {
16892        int eidx = fullCodePath.lastIndexOf("/");
16893        String subStr1 = fullCodePath.substring(0, eidx);
16894        int sidx = subStr1.lastIndexOf("/");
16895        return subStr1.substring(sidx+1, eidx);
16896    }
16897
16898    /**
16899     * Logic to handle installation of ASEC applications, including copying and
16900     * renaming logic.
16901     */
16902    class AsecInstallArgs extends InstallArgs {
16903        static final String RES_FILE_NAME = "pkg.apk";
16904        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16905
16906        String cid;
16907        String packagePath;
16908        String resourcePath;
16909
16910        /** New install */
16911        AsecInstallArgs(InstallParams params) {
16912            super(params.origin, params.move, params.observer, params.installFlags,
16913                    params.installerPackageName, params.volumeUuid,
16914                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16915                    params.grantedRuntimePermissions,
16916                    params.traceMethod, params.traceCookie, params.certificates,
16917                    params.installReason);
16918        }
16919
16920        /** Existing install */
16921        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16922                        boolean isExternal, boolean isForwardLocked) {
16923            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16924                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16925                    instructionSets, null, null, null, 0, null /*certificates*/,
16926                    PackageManager.INSTALL_REASON_UNKNOWN);
16927            // Hackily pretend we're still looking at a full code path
16928            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16929                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16930            }
16931
16932            // Extract cid from fullCodePath
16933            int eidx = fullCodePath.lastIndexOf("/");
16934            String subStr1 = fullCodePath.substring(0, eidx);
16935            int sidx = subStr1.lastIndexOf("/");
16936            cid = subStr1.substring(sidx+1, eidx);
16937            setMountPath(subStr1);
16938        }
16939
16940        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16941            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16942                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16943                    instructionSets, null, null, null, 0, null /*certificates*/,
16944                    PackageManager.INSTALL_REASON_UNKNOWN);
16945            this.cid = cid;
16946            setMountPath(PackageHelper.getSdDir(cid));
16947        }
16948
16949        void createCopyFile() {
16950            cid = mInstallerService.allocateExternalStageCidLegacy();
16951        }
16952
16953        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16954            if (origin.staged && origin.cid != null) {
16955                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16956                cid = origin.cid;
16957                setMountPath(PackageHelper.getSdDir(cid));
16958                return PackageManager.INSTALL_SUCCEEDED;
16959            }
16960
16961            if (temp) {
16962                createCopyFile();
16963            } else {
16964                /*
16965                 * Pre-emptively destroy the container since it's destroyed if
16966                 * copying fails due to it existing anyway.
16967                 */
16968                PackageHelper.destroySdDir(cid);
16969            }
16970
16971            final String newMountPath = imcs.copyPackageToContainer(
16972                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16973                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16974
16975            if (newMountPath != null) {
16976                setMountPath(newMountPath);
16977                return PackageManager.INSTALL_SUCCEEDED;
16978            } else {
16979                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16980            }
16981        }
16982
16983        @Override
16984        String getCodePath() {
16985            return packagePath;
16986        }
16987
16988        @Override
16989        String getResourcePath() {
16990            return resourcePath;
16991        }
16992
16993        int doPreInstall(int status) {
16994            if (status != PackageManager.INSTALL_SUCCEEDED) {
16995                // Destroy container
16996                PackageHelper.destroySdDir(cid);
16997            } else {
16998                boolean mounted = PackageHelper.isContainerMounted(cid);
16999                if (!mounted) {
17000                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17001                            Process.SYSTEM_UID);
17002                    if (newMountPath != null) {
17003                        setMountPath(newMountPath);
17004                    } else {
17005                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17006                    }
17007                }
17008            }
17009            return status;
17010        }
17011
17012        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17013            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17014            String newMountPath = null;
17015            if (PackageHelper.isContainerMounted(cid)) {
17016                // Unmount the container
17017                if (!PackageHelper.unMountSdDir(cid)) {
17018                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17019                    return false;
17020                }
17021            }
17022            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17023                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17024                        " which might be stale. Will try to clean up.");
17025                // Clean up the stale container and proceed to recreate.
17026                if (!PackageHelper.destroySdDir(newCacheId)) {
17027                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17028                    return false;
17029                }
17030                // Successfully cleaned up stale container. Try to rename again.
17031                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17032                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17033                            + " inspite of cleaning it up.");
17034                    return false;
17035                }
17036            }
17037            if (!PackageHelper.isContainerMounted(newCacheId)) {
17038                Slog.w(TAG, "Mounting container " + newCacheId);
17039                newMountPath = PackageHelper.mountSdDir(newCacheId,
17040                        getEncryptKey(), Process.SYSTEM_UID);
17041            } else {
17042                newMountPath = PackageHelper.getSdDir(newCacheId);
17043            }
17044            if (newMountPath == null) {
17045                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17046                return false;
17047            }
17048            Log.i(TAG, "Succesfully renamed " + cid +
17049                    " to " + newCacheId +
17050                    " at new path: " + newMountPath);
17051            cid = newCacheId;
17052
17053            final File beforeCodeFile = new File(packagePath);
17054            setMountPath(newMountPath);
17055            final File afterCodeFile = new File(packagePath);
17056
17057            // Reflect the rename in scanned details
17058            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17059            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17060                    afterCodeFile, pkg.baseCodePath));
17061            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17062                    afterCodeFile, pkg.splitCodePaths));
17063
17064            // Reflect the rename in app info
17065            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17066            pkg.setApplicationInfoCodePath(pkg.codePath);
17067            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17068            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17069            pkg.setApplicationInfoResourcePath(pkg.codePath);
17070            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17071            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17072
17073            return true;
17074        }
17075
17076        private void setMountPath(String mountPath) {
17077            final File mountFile = new File(mountPath);
17078
17079            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17080            if (monolithicFile.exists()) {
17081                packagePath = monolithicFile.getAbsolutePath();
17082                if (isFwdLocked()) {
17083                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17084                } else {
17085                    resourcePath = packagePath;
17086                }
17087            } else {
17088                packagePath = mountFile.getAbsolutePath();
17089                resourcePath = packagePath;
17090            }
17091        }
17092
17093        int doPostInstall(int status, int uid) {
17094            if (status != PackageManager.INSTALL_SUCCEEDED) {
17095                cleanUp();
17096            } else {
17097                final int groupOwner;
17098                final String protectedFile;
17099                if (isFwdLocked()) {
17100                    groupOwner = UserHandle.getSharedAppGid(uid);
17101                    protectedFile = RES_FILE_NAME;
17102                } else {
17103                    groupOwner = -1;
17104                    protectedFile = null;
17105                }
17106
17107                if (uid < Process.FIRST_APPLICATION_UID
17108                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17109                    Slog.e(TAG, "Failed to finalize " + cid);
17110                    PackageHelper.destroySdDir(cid);
17111                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17112                }
17113
17114                boolean mounted = PackageHelper.isContainerMounted(cid);
17115                if (!mounted) {
17116                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17117                }
17118            }
17119            return status;
17120        }
17121
17122        private void cleanUp() {
17123            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17124
17125            // Destroy secure container
17126            PackageHelper.destroySdDir(cid);
17127        }
17128
17129        private List<String> getAllCodePaths() {
17130            final File codeFile = new File(getCodePath());
17131            if (codeFile != null && codeFile.exists()) {
17132                try {
17133                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17134                    return pkg.getAllCodePaths();
17135                } catch (PackageParserException e) {
17136                    // Ignored; we tried our best
17137                }
17138            }
17139            return Collections.EMPTY_LIST;
17140        }
17141
17142        void cleanUpResourcesLI() {
17143            // Enumerate all code paths before deleting
17144            cleanUpResourcesLI(getAllCodePaths());
17145        }
17146
17147        private void cleanUpResourcesLI(List<String> allCodePaths) {
17148            cleanUp();
17149            removeDexFiles(allCodePaths, instructionSets);
17150        }
17151
17152        String getPackageName() {
17153            return getAsecPackageName(cid);
17154        }
17155
17156        boolean doPostDeleteLI(boolean delete) {
17157            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17158            final List<String> allCodePaths = getAllCodePaths();
17159            boolean mounted = PackageHelper.isContainerMounted(cid);
17160            if (mounted) {
17161                // Unmount first
17162                if (PackageHelper.unMountSdDir(cid)) {
17163                    mounted = false;
17164                }
17165            }
17166            if (!mounted && delete) {
17167                cleanUpResourcesLI(allCodePaths);
17168            }
17169            return !mounted;
17170        }
17171
17172        @Override
17173        int doPreCopy() {
17174            if (isFwdLocked()) {
17175                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17176                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17177                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17178                }
17179            }
17180
17181            return PackageManager.INSTALL_SUCCEEDED;
17182        }
17183
17184        @Override
17185        int doPostCopy(int uid) {
17186            if (isFwdLocked()) {
17187                if (uid < Process.FIRST_APPLICATION_UID
17188                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17189                                RES_FILE_NAME)) {
17190                    Slog.e(TAG, "Failed to finalize " + cid);
17191                    PackageHelper.destroySdDir(cid);
17192                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17193                }
17194            }
17195
17196            return PackageManager.INSTALL_SUCCEEDED;
17197        }
17198    }
17199
17200    /**
17201     * Logic to handle movement of existing installed applications.
17202     */
17203    class MoveInstallArgs extends InstallArgs {
17204        private File codeFile;
17205        private File resourceFile;
17206
17207        /** New install */
17208        MoveInstallArgs(InstallParams params) {
17209            super(params.origin, params.move, params.observer, params.installFlags,
17210                    params.installerPackageName, params.volumeUuid,
17211                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17212                    params.grantedRuntimePermissions,
17213                    params.traceMethod, params.traceCookie, params.certificates,
17214                    params.installReason);
17215        }
17216
17217        int copyApk(IMediaContainerService imcs, boolean temp) {
17218            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17219                    + move.fromUuid + " to " + move.toUuid);
17220            synchronized (mInstaller) {
17221                try {
17222                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17223                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17224                } catch (InstallerException e) {
17225                    Slog.w(TAG, "Failed to move app", e);
17226                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17227                }
17228            }
17229
17230            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17231            resourceFile = codeFile;
17232            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17233
17234            return PackageManager.INSTALL_SUCCEEDED;
17235        }
17236
17237        int doPreInstall(int status) {
17238            if (status != PackageManager.INSTALL_SUCCEEDED) {
17239                cleanUp(move.toUuid);
17240            }
17241            return status;
17242        }
17243
17244        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17245            if (status != PackageManager.INSTALL_SUCCEEDED) {
17246                cleanUp(move.toUuid);
17247                return false;
17248            }
17249
17250            // Reflect the move in app info
17251            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17252            pkg.setApplicationInfoCodePath(pkg.codePath);
17253            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17254            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17255            pkg.setApplicationInfoResourcePath(pkg.codePath);
17256            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17257            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17258
17259            return true;
17260        }
17261
17262        int doPostInstall(int status, int uid) {
17263            if (status == PackageManager.INSTALL_SUCCEEDED) {
17264                cleanUp(move.fromUuid);
17265            } else {
17266                cleanUp(move.toUuid);
17267            }
17268            return status;
17269        }
17270
17271        @Override
17272        String getCodePath() {
17273            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17274        }
17275
17276        @Override
17277        String getResourcePath() {
17278            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17279        }
17280
17281        private boolean cleanUp(String volumeUuid) {
17282            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17283                    move.dataAppName);
17284            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17285            final int[] userIds = sUserManager.getUserIds();
17286            synchronized (mInstallLock) {
17287                // Clean up both app data and code
17288                // All package moves are frozen until finished
17289                for (int userId : userIds) {
17290                    try {
17291                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17292                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17293                    } catch (InstallerException e) {
17294                        Slog.w(TAG, String.valueOf(e));
17295                    }
17296                }
17297                removeCodePathLI(codeFile);
17298            }
17299            return true;
17300        }
17301
17302        void cleanUpResourcesLI() {
17303            throw new UnsupportedOperationException();
17304        }
17305
17306        boolean doPostDeleteLI(boolean delete) {
17307            throw new UnsupportedOperationException();
17308        }
17309    }
17310
17311    static String getAsecPackageName(String packageCid) {
17312        int idx = packageCid.lastIndexOf("-");
17313        if (idx == -1) {
17314            return packageCid;
17315        }
17316        return packageCid.substring(0, idx);
17317    }
17318
17319    // Utility method used to create code paths based on package name and available index.
17320    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17321        String idxStr = "";
17322        int idx = 1;
17323        // Fall back to default value of idx=1 if prefix is not
17324        // part of oldCodePath
17325        if (oldCodePath != null) {
17326            String subStr = oldCodePath;
17327            // Drop the suffix right away
17328            if (suffix != null && subStr.endsWith(suffix)) {
17329                subStr = subStr.substring(0, subStr.length() - suffix.length());
17330            }
17331            // If oldCodePath already contains prefix find out the
17332            // ending index to either increment or decrement.
17333            int sidx = subStr.lastIndexOf(prefix);
17334            if (sidx != -1) {
17335                subStr = subStr.substring(sidx + prefix.length());
17336                if (subStr != null) {
17337                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17338                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17339                    }
17340                    try {
17341                        idx = Integer.parseInt(subStr);
17342                        if (idx <= 1) {
17343                            idx++;
17344                        } else {
17345                            idx--;
17346                        }
17347                    } catch(NumberFormatException e) {
17348                    }
17349                }
17350            }
17351        }
17352        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17353        return prefix + idxStr;
17354    }
17355
17356    private File getNextCodePath(File targetDir, String packageName) {
17357        File result;
17358        SecureRandom random = new SecureRandom();
17359        byte[] bytes = new byte[16];
17360        do {
17361            random.nextBytes(bytes);
17362            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17363            result = new File(targetDir, packageName + "-" + suffix);
17364        } while (result.exists());
17365        return result;
17366    }
17367
17368    // Utility method that returns the relative package path with respect
17369    // to the installation directory. Like say for /data/data/com.test-1.apk
17370    // string com.test-1 is returned.
17371    static String deriveCodePathName(String codePath) {
17372        if (codePath == null) {
17373            return null;
17374        }
17375        final File codeFile = new File(codePath);
17376        final String name = codeFile.getName();
17377        if (codeFile.isDirectory()) {
17378            return name;
17379        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17380            final int lastDot = name.lastIndexOf('.');
17381            return name.substring(0, lastDot);
17382        } else {
17383            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17384            return null;
17385        }
17386    }
17387
17388    static class PackageInstalledInfo {
17389        String name;
17390        int uid;
17391        // The set of users that originally had this package installed.
17392        int[] origUsers;
17393        // The set of users that now have this package installed.
17394        int[] newUsers;
17395        PackageParser.Package pkg;
17396        int returnCode;
17397        String returnMsg;
17398        PackageRemovedInfo removedInfo;
17399        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17400
17401        public void setError(int code, String msg) {
17402            setReturnCode(code);
17403            setReturnMessage(msg);
17404            Slog.w(TAG, msg);
17405        }
17406
17407        public void setError(String msg, PackageParserException e) {
17408            setReturnCode(e.error);
17409            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17410            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17411            for (int i = 0; i < childCount; i++) {
17412                addedChildPackages.valueAt(i).setError(msg, e);
17413            }
17414            Slog.w(TAG, msg, e);
17415        }
17416
17417        public void setError(String msg, PackageManagerException e) {
17418            returnCode = e.error;
17419            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17420            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17421            for (int i = 0; i < childCount; i++) {
17422                addedChildPackages.valueAt(i).setError(msg, e);
17423            }
17424            Slog.w(TAG, msg, e);
17425        }
17426
17427        public void setReturnCode(int returnCode) {
17428            this.returnCode = returnCode;
17429            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17430            for (int i = 0; i < childCount; i++) {
17431                addedChildPackages.valueAt(i).returnCode = returnCode;
17432            }
17433        }
17434
17435        private void setReturnMessage(String returnMsg) {
17436            this.returnMsg = returnMsg;
17437            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17438            for (int i = 0; i < childCount; i++) {
17439                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17440            }
17441        }
17442
17443        // In some error cases we want to convey more info back to the observer
17444        String origPackage;
17445        String origPermission;
17446    }
17447
17448    /*
17449     * Install a non-existing package.
17450     */
17451    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17452            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17453            PackageInstalledInfo res, int installReason) {
17454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17455
17456        // Remember this for later, in case we need to rollback this install
17457        String pkgName = pkg.packageName;
17458
17459        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17460
17461        synchronized(mPackages) {
17462            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17463            if (renamedPackage != null) {
17464                // A package with the same name is already installed, though
17465                // it has been renamed to an older name.  The package we
17466                // are trying to install should be installed as an update to
17467                // the existing one, but that has not been requested, so bail.
17468                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17469                        + " without first uninstalling package running as "
17470                        + renamedPackage);
17471                return;
17472            }
17473            if (mPackages.containsKey(pkgName)) {
17474                // Don't allow installation over an existing package with the same name.
17475                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17476                        + " without first uninstalling.");
17477                return;
17478            }
17479        }
17480
17481        try {
17482            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17483                    System.currentTimeMillis(), user);
17484
17485            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17486
17487            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17488                prepareAppDataAfterInstallLIF(newPackage);
17489
17490            } else {
17491                // Remove package from internal structures, but keep around any
17492                // data that might have already existed
17493                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17494                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17495            }
17496        } catch (PackageManagerException e) {
17497            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17498        }
17499
17500        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17501    }
17502
17503    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17504        // Can't rotate keys during boot or if sharedUser.
17505        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17506                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17507            return false;
17508        }
17509        // app is using upgradeKeySets; make sure all are valid
17510        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17511        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17512        for (int i = 0; i < upgradeKeySets.length; i++) {
17513            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17514                Slog.wtf(TAG, "Package "
17515                         + (oldPs.name != null ? oldPs.name : "<null>")
17516                         + " contains upgrade-key-set reference to unknown key-set: "
17517                         + upgradeKeySets[i]
17518                         + " reverting to signatures check.");
17519                return false;
17520            }
17521        }
17522        return true;
17523    }
17524
17525    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17526        // Upgrade keysets are being used.  Determine if new package has a superset of the
17527        // required keys.
17528        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17529        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17530        for (int i = 0; i < upgradeKeySets.length; i++) {
17531            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17532            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17533                return true;
17534            }
17535        }
17536        return false;
17537    }
17538
17539    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17540        try (DigestInputStream digestStream =
17541                new DigestInputStream(new FileInputStream(file), digest)) {
17542            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17543        }
17544    }
17545
17546    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17547            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17548            int installReason) {
17549        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17550
17551        final PackageParser.Package oldPackage;
17552        final PackageSetting ps;
17553        final String pkgName = pkg.packageName;
17554        final int[] allUsers;
17555        final int[] installedUsers;
17556
17557        synchronized(mPackages) {
17558            oldPackage = mPackages.get(pkgName);
17559            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17560
17561            // don't allow upgrade to target a release SDK from a pre-release SDK
17562            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17563                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17564            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17565                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17566            if (oldTargetsPreRelease
17567                    && !newTargetsPreRelease
17568                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17569                Slog.w(TAG, "Can't install package targeting released sdk");
17570                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17571                return;
17572            }
17573
17574            ps = mSettings.mPackages.get(pkgName);
17575
17576            // verify signatures are valid
17577            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17578                if (!checkUpgradeKeySetLP(ps, pkg)) {
17579                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17580                            "New package not signed by keys specified by upgrade-keysets: "
17581                                    + pkgName);
17582                    return;
17583                }
17584            } else {
17585                // default to original signature matching
17586                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17587                        != PackageManager.SIGNATURE_MATCH) {
17588                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17589                            "New package has a different signature: " + pkgName);
17590                    return;
17591                }
17592            }
17593
17594            // don't allow a system upgrade unless the upgrade hash matches
17595            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17596                byte[] digestBytes = null;
17597                try {
17598                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17599                    updateDigest(digest, new File(pkg.baseCodePath));
17600                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17601                        for (String path : pkg.splitCodePaths) {
17602                            updateDigest(digest, new File(path));
17603                        }
17604                    }
17605                    digestBytes = digest.digest();
17606                } catch (NoSuchAlgorithmException | IOException e) {
17607                    res.setError(INSTALL_FAILED_INVALID_APK,
17608                            "Could not compute hash: " + pkgName);
17609                    return;
17610                }
17611                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17612                    res.setError(INSTALL_FAILED_INVALID_APK,
17613                            "New package fails restrict-update check: " + pkgName);
17614                    return;
17615                }
17616                // retain upgrade restriction
17617                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17618            }
17619
17620            // Check for shared user id changes
17621            String invalidPackageName =
17622                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17623            if (invalidPackageName != null) {
17624                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17625                        "Package " + invalidPackageName + " tried to change user "
17626                                + oldPackage.mSharedUserId);
17627                return;
17628            }
17629
17630            // In case of rollback, remember per-user/profile install state
17631            allUsers = sUserManager.getUserIds();
17632            installedUsers = ps.queryInstalledUsers(allUsers, true);
17633
17634            // don't allow an upgrade from full to ephemeral
17635            if (isInstantApp) {
17636                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17637                    for (int currentUser : allUsers) {
17638                        if (!ps.getInstantApp(currentUser)) {
17639                            // can't downgrade from full to instant
17640                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17641                                    + " for user: " + currentUser);
17642                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17643                            return;
17644                        }
17645                    }
17646                } else if (!ps.getInstantApp(user.getIdentifier())) {
17647                    // can't downgrade from full to instant
17648                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17649                            + " for user: " + user.getIdentifier());
17650                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17651                    return;
17652                }
17653            }
17654        }
17655
17656        // Update what is removed
17657        res.removedInfo = new PackageRemovedInfo(this);
17658        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17659        res.removedInfo.removedPackage = oldPackage.packageName;
17660        res.removedInfo.installerPackageName = ps.installerPackageName;
17661        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17662        res.removedInfo.isUpdate = true;
17663        res.removedInfo.origUsers = installedUsers;
17664        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17665        for (int i = 0; i < installedUsers.length; i++) {
17666            final int userId = installedUsers[i];
17667            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17668        }
17669
17670        final int childCount = (oldPackage.childPackages != null)
17671                ? oldPackage.childPackages.size() : 0;
17672        for (int i = 0; i < childCount; i++) {
17673            boolean childPackageUpdated = false;
17674            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17675            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17676            if (res.addedChildPackages != null) {
17677                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17678                if (childRes != null) {
17679                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17680                    childRes.removedInfo.removedPackage = childPkg.packageName;
17681                    if (childPs != null) {
17682                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17683                    }
17684                    childRes.removedInfo.isUpdate = true;
17685                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17686                    childPackageUpdated = true;
17687                }
17688            }
17689            if (!childPackageUpdated) {
17690                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17691                childRemovedRes.removedPackage = childPkg.packageName;
17692                if (childPs != null) {
17693                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17694                }
17695                childRemovedRes.isUpdate = false;
17696                childRemovedRes.dataRemoved = true;
17697                synchronized (mPackages) {
17698                    if (childPs != null) {
17699                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17700                    }
17701                }
17702                if (res.removedInfo.removedChildPackages == null) {
17703                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17704                }
17705                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17706            }
17707        }
17708
17709        boolean sysPkg = (isSystemApp(oldPackage));
17710        if (sysPkg) {
17711            // Set the system/privileged flags as needed
17712            final boolean privileged =
17713                    (oldPackage.applicationInfo.privateFlags
17714                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17715            final int systemPolicyFlags = policyFlags
17716                    | PackageParser.PARSE_IS_SYSTEM
17717                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17718
17719            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17720                    user, allUsers, installerPackageName, res, installReason);
17721        } else {
17722            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17723                    user, allUsers, installerPackageName, res, installReason);
17724        }
17725    }
17726
17727    @Override
17728    public List<String> getPreviousCodePaths(String packageName) {
17729        final int callingUid = Binder.getCallingUid();
17730        final List<String> result = new ArrayList<>();
17731        if (getInstantAppPackageName(callingUid) != null) {
17732            return result;
17733        }
17734        final PackageSetting ps = mSettings.mPackages.get(packageName);
17735        if (ps != null
17736                && ps.oldCodePaths != null
17737                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17738            result.addAll(ps.oldCodePaths);
17739        }
17740        return result;
17741    }
17742
17743    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17744            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17745            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17746            int installReason) {
17747        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17748                + deletedPackage);
17749
17750        String pkgName = deletedPackage.packageName;
17751        boolean deletedPkg = true;
17752        boolean addedPkg = false;
17753        boolean updatedSettings = false;
17754        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17755        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17756                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17757
17758        final long origUpdateTime = (pkg.mExtras != null)
17759                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17760
17761        // First delete the existing package while retaining the data directory
17762        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17763                res.removedInfo, true, pkg)) {
17764            // If the existing package wasn't successfully deleted
17765            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17766            deletedPkg = false;
17767        } else {
17768            // Successfully deleted the old package; proceed with replace.
17769
17770            // If deleted package lived in a container, give users a chance to
17771            // relinquish resources before killing.
17772            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17773                if (DEBUG_INSTALL) {
17774                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17775                }
17776                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17777                final ArrayList<String> pkgList = new ArrayList<String>(1);
17778                pkgList.add(deletedPackage.applicationInfo.packageName);
17779                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17780            }
17781
17782            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17783                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17784            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17785
17786            try {
17787                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17788                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17789                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17790                        installReason);
17791
17792                // Update the in-memory copy of the previous code paths.
17793                PackageSetting ps = mSettings.mPackages.get(pkgName);
17794                if (!killApp) {
17795                    if (ps.oldCodePaths == null) {
17796                        ps.oldCodePaths = new ArraySet<>();
17797                    }
17798                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17799                    if (deletedPackage.splitCodePaths != null) {
17800                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17801                    }
17802                } else {
17803                    ps.oldCodePaths = null;
17804                }
17805                if (ps.childPackageNames != null) {
17806                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17807                        final String childPkgName = ps.childPackageNames.get(i);
17808                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17809                        childPs.oldCodePaths = ps.oldCodePaths;
17810                    }
17811                }
17812                // set instant app status, but, only if it's explicitly specified
17813                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17814                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17815                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17816                prepareAppDataAfterInstallLIF(newPackage);
17817                addedPkg = true;
17818                mDexManager.notifyPackageUpdated(newPackage.packageName,
17819                        newPackage.baseCodePath, newPackage.splitCodePaths);
17820            } catch (PackageManagerException e) {
17821                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17822            }
17823        }
17824
17825        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17826            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17827
17828            // Revert all internal state mutations and added folders for the failed install
17829            if (addedPkg) {
17830                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17831                        res.removedInfo, true, null);
17832            }
17833
17834            // Restore the old package
17835            if (deletedPkg) {
17836                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17837                File restoreFile = new File(deletedPackage.codePath);
17838                // Parse old package
17839                boolean oldExternal = isExternal(deletedPackage);
17840                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17841                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17842                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17843                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17844                try {
17845                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17846                            null);
17847                } catch (PackageManagerException e) {
17848                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17849                            + e.getMessage());
17850                    return;
17851                }
17852
17853                synchronized (mPackages) {
17854                    // Ensure the installer package name up to date
17855                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17856
17857                    // Update permissions for restored package
17858                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17859
17860                    mSettings.writeLPr();
17861                }
17862
17863                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17864            }
17865        } else {
17866            synchronized (mPackages) {
17867                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17868                if (ps != null) {
17869                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17870                    if (res.removedInfo.removedChildPackages != null) {
17871                        final int childCount = res.removedInfo.removedChildPackages.size();
17872                        // Iterate in reverse as we may modify the collection
17873                        for (int i = childCount - 1; i >= 0; i--) {
17874                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17875                            if (res.addedChildPackages.containsKey(childPackageName)) {
17876                                res.removedInfo.removedChildPackages.removeAt(i);
17877                            } else {
17878                                PackageRemovedInfo childInfo = res.removedInfo
17879                                        .removedChildPackages.valueAt(i);
17880                                childInfo.removedForAllUsers = mPackages.get(
17881                                        childInfo.removedPackage) == null;
17882                            }
17883                        }
17884                    }
17885                }
17886            }
17887        }
17888    }
17889
17890    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17891            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17892            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17893            int installReason) {
17894        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17895                + ", old=" + deletedPackage);
17896
17897        final boolean disabledSystem;
17898
17899        // Remove existing system package
17900        removePackageLI(deletedPackage, true);
17901
17902        synchronized (mPackages) {
17903            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17904        }
17905        if (!disabledSystem) {
17906            // We didn't need to disable the .apk as a current system package,
17907            // which means we are replacing another update that is already
17908            // installed.  We need to make sure to delete the older one's .apk.
17909            res.removedInfo.args = createInstallArgsForExisting(0,
17910                    deletedPackage.applicationInfo.getCodePath(),
17911                    deletedPackage.applicationInfo.getResourcePath(),
17912                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17913        } else {
17914            res.removedInfo.args = null;
17915        }
17916
17917        // Successfully disabled the old package. Now proceed with re-installation
17918        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17919                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17920        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17921
17922        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17923        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17924                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17925
17926        PackageParser.Package newPackage = null;
17927        try {
17928            // Add the package to the internal data structures
17929            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17930
17931            // Set the update and install times
17932            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17933            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17934                    System.currentTimeMillis());
17935
17936            // Update the package dynamic state if succeeded
17937            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17938                // Now that the install succeeded make sure we remove data
17939                // directories for any child package the update removed.
17940                final int deletedChildCount = (deletedPackage.childPackages != null)
17941                        ? deletedPackage.childPackages.size() : 0;
17942                final int newChildCount = (newPackage.childPackages != null)
17943                        ? newPackage.childPackages.size() : 0;
17944                for (int i = 0; i < deletedChildCount; i++) {
17945                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17946                    boolean childPackageDeleted = true;
17947                    for (int j = 0; j < newChildCount; j++) {
17948                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17949                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17950                            childPackageDeleted = false;
17951                            break;
17952                        }
17953                    }
17954                    if (childPackageDeleted) {
17955                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17956                                deletedChildPkg.packageName);
17957                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17958                            PackageRemovedInfo removedChildRes = res.removedInfo
17959                                    .removedChildPackages.get(deletedChildPkg.packageName);
17960                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17961                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17962                        }
17963                    }
17964                }
17965
17966                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17967                        installReason);
17968                prepareAppDataAfterInstallLIF(newPackage);
17969
17970                mDexManager.notifyPackageUpdated(newPackage.packageName,
17971                            newPackage.baseCodePath, newPackage.splitCodePaths);
17972            }
17973        } catch (PackageManagerException e) {
17974            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17975            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17976        }
17977
17978        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17979            // Re installation failed. Restore old information
17980            // Remove new pkg information
17981            if (newPackage != null) {
17982                removeInstalledPackageLI(newPackage, true);
17983            }
17984            // Add back the old system package
17985            try {
17986                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17987            } catch (PackageManagerException e) {
17988                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17989            }
17990
17991            synchronized (mPackages) {
17992                if (disabledSystem) {
17993                    enableSystemPackageLPw(deletedPackage);
17994                }
17995
17996                // Ensure the installer package name up to date
17997                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17998
17999                // Update permissions for restored package
18000                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18001
18002                mSettings.writeLPr();
18003            }
18004
18005            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18006                    + " after failed upgrade");
18007        }
18008    }
18009
18010    /**
18011     * Checks whether the parent or any of the child packages have a change shared
18012     * user. For a package to be a valid update the shred users of the parent and
18013     * the children should match. We may later support changing child shared users.
18014     * @param oldPkg The updated package.
18015     * @param newPkg The update package.
18016     * @return The shared user that change between the versions.
18017     */
18018    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18019            PackageParser.Package newPkg) {
18020        // Check parent shared user
18021        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18022            return newPkg.packageName;
18023        }
18024        // Check child shared users
18025        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18026        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18027        for (int i = 0; i < newChildCount; i++) {
18028            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18029            // If this child was present, did it have the same shared user?
18030            for (int j = 0; j < oldChildCount; j++) {
18031                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18032                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18033                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18034                    return newChildPkg.packageName;
18035                }
18036            }
18037        }
18038        return null;
18039    }
18040
18041    private void removeNativeBinariesLI(PackageSetting ps) {
18042        // Remove the lib path for the parent package
18043        if (ps != null) {
18044            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18045            // Remove the lib path for the child packages
18046            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18047            for (int i = 0; i < childCount; i++) {
18048                PackageSetting childPs = null;
18049                synchronized (mPackages) {
18050                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18051                }
18052                if (childPs != null) {
18053                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18054                            .legacyNativeLibraryPathString);
18055                }
18056            }
18057        }
18058    }
18059
18060    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18061        // Enable the parent package
18062        mSettings.enableSystemPackageLPw(pkg.packageName);
18063        // Enable the child packages
18064        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18065        for (int i = 0; i < childCount; i++) {
18066            PackageParser.Package childPkg = pkg.childPackages.get(i);
18067            mSettings.enableSystemPackageLPw(childPkg.packageName);
18068        }
18069    }
18070
18071    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18072            PackageParser.Package newPkg) {
18073        // Disable the parent package (parent always replaced)
18074        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18075        // Disable the child packages
18076        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18077        for (int i = 0; i < childCount; i++) {
18078            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18079            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18080            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18081        }
18082        return disabled;
18083    }
18084
18085    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18086            String installerPackageName) {
18087        // Enable the parent package
18088        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18089        // Enable the child packages
18090        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18091        for (int i = 0; i < childCount; i++) {
18092            PackageParser.Package childPkg = pkg.childPackages.get(i);
18093            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18094        }
18095    }
18096
18097    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18098        // Collect all used permissions in the UID
18099        ArraySet<String> usedPermissions = new ArraySet<>();
18100        final int packageCount = su.packages.size();
18101        for (int i = 0; i < packageCount; i++) {
18102            PackageSetting ps = su.packages.valueAt(i);
18103            if (ps.pkg == null) {
18104                continue;
18105            }
18106            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18107            for (int j = 0; j < requestedPermCount; j++) {
18108                String permission = ps.pkg.requestedPermissions.get(j);
18109                BasePermission bp = mSettings.mPermissions.get(permission);
18110                if (bp != null) {
18111                    usedPermissions.add(permission);
18112                }
18113            }
18114        }
18115
18116        PermissionsState permissionsState = su.getPermissionsState();
18117        // Prune install permissions
18118        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18119        final int installPermCount = installPermStates.size();
18120        for (int i = installPermCount - 1; i >= 0;  i--) {
18121            PermissionState permissionState = installPermStates.get(i);
18122            if (!usedPermissions.contains(permissionState.getName())) {
18123                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18124                if (bp != null) {
18125                    permissionsState.revokeInstallPermission(bp);
18126                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18127                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18128                }
18129            }
18130        }
18131
18132        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18133
18134        // Prune runtime permissions
18135        for (int userId : allUserIds) {
18136            List<PermissionState> runtimePermStates = permissionsState
18137                    .getRuntimePermissionStates(userId);
18138            final int runtimePermCount = runtimePermStates.size();
18139            for (int i = runtimePermCount - 1; i >= 0; i--) {
18140                PermissionState permissionState = runtimePermStates.get(i);
18141                if (!usedPermissions.contains(permissionState.getName())) {
18142                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18143                    if (bp != null) {
18144                        permissionsState.revokeRuntimePermission(bp, userId);
18145                        permissionsState.updatePermissionFlags(bp, userId,
18146                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18147                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18148                                runtimePermissionChangedUserIds, userId);
18149                    }
18150                }
18151            }
18152        }
18153
18154        return runtimePermissionChangedUserIds;
18155    }
18156
18157    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18158            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18159        // Update the parent package setting
18160        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18161                res, user, installReason);
18162        // Update the child packages setting
18163        final int childCount = (newPackage.childPackages != null)
18164                ? newPackage.childPackages.size() : 0;
18165        for (int i = 0; i < childCount; i++) {
18166            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18167            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18168            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18169                    childRes.origUsers, childRes, user, installReason);
18170        }
18171    }
18172
18173    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18174            String installerPackageName, int[] allUsers, int[] installedForUsers,
18175            PackageInstalledInfo res, UserHandle user, int installReason) {
18176        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18177
18178        String pkgName = newPackage.packageName;
18179        synchronized (mPackages) {
18180            //write settings. the installStatus will be incomplete at this stage.
18181            //note that the new package setting would have already been
18182            //added to mPackages. It hasn't been persisted yet.
18183            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18184            // TODO: Remove this write? It's also written at the end of this method
18185            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18186            mSettings.writeLPr();
18187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18188        }
18189
18190        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18191        synchronized (mPackages) {
18192            updatePermissionsLPw(newPackage.packageName, newPackage,
18193                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18194                            ? UPDATE_PERMISSIONS_ALL : 0));
18195            // For system-bundled packages, we assume that installing an upgraded version
18196            // of the package implies that the user actually wants to run that new code,
18197            // so we enable the package.
18198            PackageSetting ps = mSettings.mPackages.get(pkgName);
18199            final int userId = user.getIdentifier();
18200            if (ps != null) {
18201                if (isSystemApp(newPackage)) {
18202                    if (DEBUG_INSTALL) {
18203                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18204                    }
18205                    // Enable system package for requested users
18206                    if (res.origUsers != null) {
18207                        for (int origUserId : res.origUsers) {
18208                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18209                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18210                                        origUserId, installerPackageName);
18211                            }
18212                        }
18213                    }
18214                    // Also convey the prior install/uninstall state
18215                    if (allUsers != null && installedForUsers != null) {
18216                        for (int currentUserId : allUsers) {
18217                            final boolean installed = ArrayUtils.contains(
18218                                    installedForUsers, currentUserId);
18219                            if (DEBUG_INSTALL) {
18220                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18221                            }
18222                            ps.setInstalled(installed, currentUserId);
18223                        }
18224                        // these install state changes will be persisted in the
18225                        // upcoming call to mSettings.writeLPr().
18226                    }
18227                }
18228                // It's implied that when a user requests installation, they want the app to be
18229                // installed and enabled.
18230                if (userId != UserHandle.USER_ALL) {
18231                    ps.setInstalled(true, userId);
18232                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18233                }
18234
18235                // When replacing an existing package, preserve the original install reason for all
18236                // users that had the package installed before.
18237                final Set<Integer> previousUserIds = new ArraySet<>();
18238                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18239                    final int installReasonCount = res.removedInfo.installReasons.size();
18240                    for (int i = 0; i < installReasonCount; i++) {
18241                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18242                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18243                        ps.setInstallReason(previousInstallReason, previousUserId);
18244                        previousUserIds.add(previousUserId);
18245                    }
18246                }
18247
18248                // Set install reason for users that are having the package newly installed.
18249                if (userId == UserHandle.USER_ALL) {
18250                    for (int currentUserId : sUserManager.getUserIds()) {
18251                        if (!previousUserIds.contains(currentUserId)) {
18252                            ps.setInstallReason(installReason, currentUserId);
18253                        }
18254                    }
18255                } else if (!previousUserIds.contains(userId)) {
18256                    ps.setInstallReason(installReason, userId);
18257                }
18258                mSettings.writeKernelMappingLPr(ps);
18259            }
18260            res.name = pkgName;
18261            res.uid = newPackage.applicationInfo.uid;
18262            res.pkg = newPackage;
18263            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18264            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18265            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18266            //to update install status
18267            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18268            mSettings.writeLPr();
18269            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18270        }
18271
18272        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18273    }
18274
18275    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18276        try {
18277            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18278            installPackageLI(args, res);
18279        } finally {
18280            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18281        }
18282    }
18283
18284    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18285        final int installFlags = args.installFlags;
18286        final String installerPackageName = args.installerPackageName;
18287        final String volumeUuid = args.volumeUuid;
18288        final File tmpPackageFile = new File(args.getCodePath());
18289        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18290        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18291                || (args.volumeUuid != null));
18292        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18293        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18294        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18295        final boolean virtualPreload =
18296                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18297        boolean replace = false;
18298        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18299        if (args.move != null) {
18300            // moving a complete application; perform an initial scan on the new install location
18301            scanFlags |= SCAN_INITIAL;
18302        }
18303        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18304            scanFlags |= SCAN_DONT_KILL_APP;
18305        }
18306        if (instantApp) {
18307            scanFlags |= SCAN_AS_INSTANT_APP;
18308        }
18309        if (fullApp) {
18310            scanFlags |= SCAN_AS_FULL_APP;
18311        }
18312        if (virtualPreload) {
18313            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18314        }
18315
18316        // Result object to be returned
18317        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18318
18319        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18320
18321        // Sanity check
18322        if (instantApp && (forwardLocked || onExternal)) {
18323            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18324                    + " external=" + onExternal);
18325            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18326            return;
18327        }
18328
18329        // Retrieve PackageSettings and parse package
18330        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18331                | PackageParser.PARSE_ENFORCE_CODE
18332                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18333                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18334                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18335                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18336        PackageParser pp = new PackageParser();
18337        pp.setSeparateProcesses(mSeparateProcesses);
18338        pp.setDisplayMetrics(mMetrics);
18339        pp.setCallback(mPackageParserCallback);
18340
18341        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18342        final PackageParser.Package pkg;
18343        try {
18344            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18345        } catch (PackageParserException e) {
18346            res.setError("Failed parse during installPackageLI", e);
18347            return;
18348        } finally {
18349            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18350        }
18351
18352        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18353        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18354            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18355            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18356                    "Instant app package must target O");
18357            return;
18358        }
18359        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18360            Slog.w(TAG, "Instant app package " + pkg.packageName
18361                    + " does not target targetSandboxVersion 2");
18362            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18363                    "Instant app package must use targetSanboxVersion 2");
18364            return;
18365        }
18366
18367        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18368            // Static shared libraries have synthetic package names
18369            renameStaticSharedLibraryPackage(pkg);
18370
18371            // No static shared libs on external storage
18372            if (onExternal) {
18373                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18374                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18375                        "Packages declaring static-shared libs cannot be updated");
18376                return;
18377            }
18378        }
18379
18380        // If we are installing a clustered package add results for the children
18381        if (pkg.childPackages != null) {
18382            synchronized (mPackages) {
18383                final int childCount = pkg.childPackages.size();
18384                for (int i = 0; i < childCount; i++) {
18385                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18386                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18387                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18388                    childRes.pkg = childPkg;
18389                    childRes.name = childPkg.packageName;
18390                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18391                    if (childPs != null) {
18392                        childRes.origUsers = childPs.queryInstalledUsers(
18393                                sUserManager.getUserIds(), true);
18394                    }
18395                    if ((mPackages.containsKey(childPkg.packageName))) {
18396                        childRes.removedInfo = new PackageRemovedInfo(this);
18397                        childRes.removedInfo.removedPackage = childPkg.packageName;
18398                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18399                    }
18400                    if (res.addedChildPackages == null) {
18401                        res.addedChildPackages = new ArrayMap<>();
18402                    }
18403                    res.addedChildPackages.put(childPkg.packageName, childRes);
18404                }
18405            }
18406        }
18407
18408        // If package doesn't declare API override, mark that we have an install
18409        // time CPU ABI override.
18410        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18411            pkg.cpuAbiOverride = args.abiOverride;
18412        }
18413
18414        String pkgName = res.name = pkg.packageName;
18415        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18416            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18417                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18418                return;
18419            }
18420        }
18421
18422        try {
18423            // either use what we've been given or parse directly from the APK
18424            if (args.certificates != null) {
18425                try {
18426                    PackageParser.populateCertificates(pkg, args.certificates);
18427                } catch (PackageParserException e) {
18428                    // there was something wrong with the certificates we were given;
18429                    // try to pull them from the APK
18430                    PackageParser.collectCertificates(pkg, parseFlags);
18431                }
18432            } else {
18433                PackageParser.collectCertificates(pkg, parseFlags);
18434            }
18435        } catch (PackageParserException e) {
18436            res.setError("Failed collect during installPackageLI", e);
18437            return;
18438        }
18439
18440        // Get rid of all references to package scan path via parser.
18441        pp = null;
18442        String oldCodePath = null;
18443        boolean systemApp = false;
18444        synchronized (mPackages) {
18445            // Check if installing already existing package
18446            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18447                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18448                if (pkg.mOriginalPackages != null
18449                        && pkg.mOriginalPackages.contains(oldName)
18450                        && mPackages.containsKey(oldName)) {
18451                    // This package is derived from an original package,
18452                    // and this device has been updating from that original
18453                    // name.  We must continue using the original name, so
18454                    // rename the new package here.
18455                    pkg.setPackageName(oldName);
18456                    pkgName = pkg.packageName;
18457                    replace = true;
18458                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18459                            + oldName + " pkgName=" + pkgName);
18460                } else if (mPackages.containsKey(pkgName)) {
18461                    // This package, under its official name, already exists
18462                    // on the device; we should replace it.
18463                    replace = true;
18464                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18465                }
18466
18467                // Child packages are installed through the parent package
18468                if (pkg.parentPackage != null) {
18469                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18470                            "Package " + pkg.packageName + " is child of package "
18471                                    + pkg.parentPackage.parentPackage + ". Child packages "
18472                                    + "can be updated only through the parent package.");
18473                    return;
18474                }
18475
18476                if (replace) {
18477                    // Prevent apps opting out from runtime permissions
18478                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18479                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18480                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18481                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18482                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18483                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18484                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18485                                        + " doesn't support runtime permissions but the old"
18486                                        + " target SDK " + oldTargetSdk + " does.");
18487                        return;
18488                    }
18489                    // Prevent apps from downgrading their targetSandbox.
18490                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18491                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18492                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18493                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18494                                "Package " + pkg.packageName + " new target sandbox "
18495                                + newTargetSandbox + " is incompatible with the previous value of"
18496                                + oldTargetSandbox + ".");
18497                        return;
18498                    }
18499
18500                    // Prevent installing of child packages
18501                    if (oldPackage.parentPackage != null) {
18502                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18503                                "Package " + pkg.packageName + " is child of package "
18504                                        + oldPackage.parentPackage + ". Child packages "
18505                                        + "can be updated only through the parent package.");
18506                        return;
18507                    }
18508                }
18509            }
18510
18511            PackageSetting ps = mSettings.mPackages.get(pkgName);
18512            if (ps != null) {
18513                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18514
18515                // Static shared libs have same package with different versions where
18516                // we internally use a synthetic package name to allow multiple versions
18517                // of the same package, therefore we need to compare signatures against
18518                // the package setting for the latest library version.
18519                PackageSetting signatureCheckPs = ps;
18520                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18521                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18522                    if (libraryEntry != null) {
18523                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18524                    }
18525                }
18526
18527                // Quick sanity check that we're signed correctly if updating;
18528                // we'll check this again later when scanning, but we want to
18529                // bail early here before tripping over redefined permissions.
18530                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18531                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18532                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18533                                + pkg.packageName + " upgrade keys do not match the "
18534                                + "previously installed version");
18535                        return;
18536                    }
18537                } else {
18538                    try {
18539                        verifySignaturesLP(signatureCheckPs, pkg);
18540                    } catch (PackageManagerException e) {
18541                        res.setError(e.error, e.getMessage());
18542                        return;
18543                    }
18544                }
18545
18546                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18547                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18548                    systemApp = (ps.pkg.applicationInfo.flags &
18549                            ApplicationInfo.FLAG_SYSTEM) != 0;
18550                }
18551                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18552            }
18553
18554            int N = pkg.permissions.size();
18555            for (int i = N-1; i >= 0; i--) {
18556                PackageParser.Permission perm = pkg.permissions.get(i);
18557                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18558
18559                // Don't allow anyone but the system to define ephemeral permissions.
18560                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18561                        && !systemApp) {
18562                    Slog.w(TAG, "Non-System package " + pkg.packageName
18563                            + " attempting to delcare ephemeral permission "
18564                            + perm.info.name + "; Removing ephemeral.");
18565                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18566                }
18567                // Check whether the newly-scanned package wants to define an already-defined perm
18568                if (bp != null) {
18569                    // If the defining package is signed with our cert, it's okay.  This
18570                    // also includes the "updating the same package" case, of course.
18571                    // "updating same package" could also involve key-rotation.
18572                    final boolean sigsOk;
18573                    if (bp.sourcePackage.equals(pkg.packageName)
18574                            && (bp.packageSetting instanceof PackageSetting)
18575                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18576                                    scanFlags))) {
18577                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18578                    } else {
18579                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18580                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18581                    }
18582                    if (!sigsOk) {
18583                        // If the owning package is the system itself, we log but allow
18584                        // install to proceed; we fail the install on all other permission
18585                        // redefinitions.
18586                        if (!bp.sourcePackage.equals("android")) {
18587                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18588                                    + pkg.packageName + " attempting to redeclare permission "
18589                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18590                            res.origPermission = perm.info.name;
18591                            res.origPackage = bp.sourcePackage;
18592                            return;
18593                        } else {
18594                            Slog.w(TAG, "Package " + pkg.packageName
18595                                    + " attempting to redeclare system permission "
18596                                    + perm.info.name + "; ignoring new declaration");
18597                            pkg.permissions.remove(i);
18598                        }
18599                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18600                        // Prevent apps to change protection level to dangerous from any other
18601                        // type as this would allow a privilege escalation where an app adds a
18602                        // normal/signature permission in other app's group and later redefines
18603                        // it as dangerous leading to the group auto-grant.
18604                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18605                                == PermissionInfo.PROTECTION_DANGEROUS) {
18606                            if (bp != null && !bp.isRuntime()) {
18607                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18608                                        + "non-runtime permission " + perm.info.name
18609                                        + " to runtime; keeping old protection level");
18610                                perm.info.protectionLevel = bp.protectionLevel;
18611                            }
18612                        }
18613                    }
18614                }
18615            }
18616        }
18617
18618        if (systemApp) {
18619            if (onExternal) {
18620                // Abort update; system app can't be replaced with app on sdcard
18621                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18622                        "Cannot install updates to system apps on sdcard");
18623                return;
18624            } else if (instantApp) {
18625                // Abort update; system app can't be replaced with an instant app
18626                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18627                        "Cannot update a system app with an instant app");
18628                return;
18629            }
18630        }
18631
18632        if (args.move != null) {
18633            // We did an in-place move, so dex is ready to roll
18634            scanFlags |= SCAN_NO_DEX;
18635            scanFlags |= SCAN_MOVE;
18636
18637            synchronized (mPackages) {
18638                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18639                if (ps == null) {
18640                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18641                            "Missing settings for moved package " + pkgName);
18642                }
18643
18644                // We moved the entire application as-is, so bring over the
18645                // previously derived ABI information.
18646                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18647                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18648            }
18649
18650        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18651            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18652            scanFlags |= SCAN_NO_DEX;
18653
18654            try {
18655                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18656                    args.abiOverride : pkg.cpuAbiOverride);
18657                final boolean extractNativeLibs = !pkg.isLibrary();
18658                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18659                        extractNativeLibs, mAppLib32InstallDir);
18660            } catch (PackageManagerException pme) {
18661                Slog.e(TAG, "Error deriving application ABI", pme);
18662                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18663                return;
18664            }
18665
18666            // Shared libraries for the package need to be updated.
18667            synchronized (mPackages) {
18668                try {
18669                    updateSharedLibrariesLPr(pkg, null);
18670                } catch (PackageManagerException e) {
18671                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18672                }
18673            }
18674        }
18675
18676        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18677            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18678            return;
18679        }
18680
18681        // Verify if we need to dexopt the app.
18682        //
18683        // NOTE: it is *important* to call dexopt after doRename which will sync the
18684        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18685        //
18686        // We only need to dexopt if the package meets ALL of the following conditions:
18687        //   1) it is not forward locked.
18688        //   2) it is not on on an external ASEC container.
18689        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18690        //
18691        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18692        // complete, so we skip this step during installation. Instead, we'll take extra time
18693        // the first time the instant app starts. It's preferred to do it this way to provide
18694        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18695        // middle of running an instant app. The default behaviour can be overridden
18696        // via gservices.
18697        final boolean performDexopt = !forwardLocked
18698            && !pkg.applicationInfo.isExternalAsec()
18699            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18700                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18701
18702        if (performDexopt) {
18703            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18704            // Do not run PackageDexOptimizer through the local performDexOpt
18705            // method because `pkg` may not be in `mPackages` yet.
18706            //
18707            // Also, don't fail application installs if the dexopt step fails.
18708            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18709                REASON_INSTALL,
18710                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18711            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18712                null /* instructionSets */,
18713                getOrCreateCompilerPackageStats(pkg),
18714                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18715                dexoptOptions);
18716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18717        }
18718
18719        // Notify BackgroundDexOptService that the package has been changed.
18720        // If this is an update of a package which used to fail to compile,
18721        // BackgroundDexOptService will remove it from its blacklist.
18722        // TODO: Layering violation
18723        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18724
18725        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18726
18727        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18728                "installPackageLI")) {
18729            if (replace) {
18730                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18731                    // Static libs have a synthetic package name containing the version
18732                    // and cannot be updated as an update would get a new package name,
18733                    // unless this is the exact same version code which is useful for
18734                    // development.
18735                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18736                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18737                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18738                                + "static-shared libs cannot be updated");
18739                        return;
18740                    }
18741                }
18742                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18743                        installerPackageName, res, args.installReason);
18744            } else {
18745                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18746                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18747            }
18748        }
18749
18750        synchronized (mPackages) {
18751            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18752            if (ps != null) {
18753                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18754                ps.setUpdateAvailable(false /*updateAvailable*/);
18755            }
18756
18757            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18758            for (int i = 0; i < childCount; i++) {
18759                PackageParser.Package childPkg = pkg.childPackages.get(i);
18760                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18761                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18762                if (childPs != null) {
18763                    childRes.newUsers = childPs.queryInstalledUsers(
18764                            sUserManager.getUserIds(), true);
18765                }
18766            }
18767
18768            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18769                updateSequenceNumberLP(ps, res.newUsers);
18770                updateInstantAppInstallerLocked(pkgName);
18771            }
18772        }
18773    }
18774
18775    private void startIntentFilterVerifications(int userId, boolean replacing,
18776            PackageParser.Package pkg) {
18777        if (mIntentFilterVerifierComponent == null) {
18778            Slog.w(TAG, "No IntentFilter verification will not be done as "
18779                    + "there is no IntentFilterVerifier available!");
18780            return;
18781        }
18782
18783        final int verifierUid = getPackageUid(
18784                mIntentFilterVerifierComponent.getPackageName(),
18785                MATCH_DEBUG_TRIAGED_MISSING,
18786                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18787
18788        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18789        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18790        mHandler.sendMessage(msg);
18791
18792        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18793        for (int i = 0; i < childCount; i++) {
18794            PackageParser.Package childPkg = pkg.childPackages.get(i);
18795            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18796            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18797            mHandler.sendMessage(msg);
18798        }
18799    }
18800
18801    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18802            PackageParser.Package pkg) {
18803        int size = pkg.activities.size();
18804        if (size == 0) {
18805            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18806                    "No activity, so no need to verify any IntentFilter!");
18807            return;
18808        }
18809
18810        final boolean hasDomainURLs = hasDomainURLs(pkg);
18811        if (!hasDomainURLs) {
18812            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18813                    "No domain URLs, so no need to verify any IntentFilter!");
18814            return;
18815        }
18816
18817        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18818                + " if any IntentFilter from the " + size
18819                + " Activities needs verification ...");
18820
18821        int count = 0;
18822        final String packageName = pkg.packageName;
18823
18824        synchronized (mPackages) {
18825            // If this is a new install and we see that we've already run verification for this
18826            // package, we have nothing to do: it means the state was restored from backup.
18827            if (!replacing) {
18828                IntentFilterVerificationInfo ivi =
18829                        mSettings.getIntentFilterVerificationLPr(packageName);
18830                if (ivi != null) {
18831                    if (DEBUG_DOMAIN_VERIFICATION) {
18832                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18833                                + ivi.getStatusString());
18834                    }
18835                    return;
18836                }
18837            }
18838
18839            // If any filters need to be verified, then all need to be.
18840            boolean needToVerify = false;
18841            for (PackageParser.Activity a : pkg.activities) {
18842                for (ActivityIntentInfo filter : a.intents) {
18843                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18844                        if (DEBUG_DOMAIN_VERIFICATION) {
18845                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18846                        }
18847                        needToVerify = true;
18848                        break;
18849                    }
18850                }
18851            }
18852
18853            if (needToVerify) {
18854                final int verificationId = mIntentFilterVerificationToken++;
18855                for (PackageParser.Activity a : pkg.activities) {
18856                    for (ActivityIntentInfo filter : a.intents) {
18857                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18858                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18859                                    "Verification needed for IntentFilter:" + filter.toString());
18860                            mIntentFilterVerifier.addOneIntentFilterVerification(
18861                                    verifierUid, userId, verificationId, filter, packageName);
18862                            count++;
18863                        }
18864                    }
18865                }
18866            }
18867        }
18868
18869        if (count > 0) {
18870            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18871                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18872                    +  " for userId:" + userId);
18873            mIntentFilterVerifier.startVerifications(userId);
18874        } else {
18875            if (DEBUG_DOMAIN_VERIFICATION) {
18876                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18877            }
18878        }
18879    }
18880
18881    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18882        final ComponentName cn  = filter.activity.getComponentName();
18883        final String packageName = cn.getPackageName();
18884
18885        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18886                packageName);
18887        if (ivi == null) {
18888            return true;
18889        }
18890        int status = ivi.getStatus();
18891        switch (status) {
18892            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18893            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18894                return true;
18895
18896            default:
18897                // Nothing to do
18898                return false;
18899        }
18900    }
18901
18902    private static boolean isMultiArch(ApplicationInfo info) {
18903        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18904    }
18905
18906    private static boolean isExternal(PackageParser.Package pkg) {
18907        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18908    }
18909
18910    private static boolean isExternal(PackageSetting ps) {
18911        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18912    }
18913
18914    private static boolean isSystemApp(PackageParser.Package pkg) {
18915        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18916    }
18917
18918    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18919        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18920    }
18921
18922    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18923        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18924    }
18925
18926    private static boolean isSystemApp(PackageSetting ps) {
18927        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18928    }
18929
18930    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18931        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18932    }
18933
18934    private int packageFlagsToInstallFlags(PackageSetting ps) {
18935        int installFlags = 0;
18936        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18937            // This existing package was an external ASEC install when we have
18938            // the external flag without a UUID
18939            installFlags |= PackageManager.INSTALL_EXTERNAL;
18940        }
18941        if (ps.isForwardLocked()) {
18942            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18943        }
18944        return installFlags;
18945    }
18946
18947    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18948        if (isExternal(pkg)) {
18949            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18950                return StorageManager.UUID_PRIMARY_PHYSICAL;
18951            } else {
18952                return pkg.volumeUuid;
18953            }
18954        } else {
18955            return StorageManager.UUID_PRIVATE_INTERNAL;
18956        }
18957    }
18958
18959    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18960        if (isExternal(pkg)) {
18961            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18962                return mSettings.getExternalVersion();
18963            } else {
18964                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18965            }
18966        } else {
18967            return mSettings.getInternalVersion();
18968        }
18969    }
18970
18971    private void deleteTempPackageFiles() {
18972        final FilenameFilter filter = new FilenameFilter() {
18973            public boolean accept(File dir, String name) {
18974                return name.startsWith("vmdl") && name.endsWith(".tmp");
18975            }
18976        };
18977        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18978            file.delete();
18979        }
18980    }
18981
18982    @Override
18983    public void deletePackageAsUser(String packageName, int versionCode,
18984            IPackageDeleteObserver observer, int userId, int flags) {
18985        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18986                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18987    }
18988
18989    @Override
18990    public void deletePackageVersioned(VersionedPackage versionedPackage,
18991            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18992        final int callingUid = Binder.getCallingUid();
18993        mContext.enforceCallingOrSelfPermission(
18994                android.Manifest.permission.DELETE_PACKAGES, null);
18995        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18996        Preconditions.checkNotNull(versionedPackage);
18997        Preconditions.checkNotNull(observer);
18998        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18999                PackageManager.VERSION_CODE_HIGHEST,
19000                Integer.MAX_VALUE, "versionCode must be >= -1");
19001
19002        final String packageName = versionedPackage.getPackageName();
19003        final int versionCode = versionedPackage.getVersionCode();
19004        final String internalPackageName;
19005        synchronized (mPackages) {
19006            // Normalize package name to handle renamed packages and static libs
19007            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19008                    versionedPackage.getVersionCode());
19009        }
19010
19011        final int uid = Binder.getCallingUid();
19012        if (!isOrphaned(internalPackageName)
19013                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19014            try {
19015                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19016                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19017                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19018                observer.onUserActionRequired(intent);
19019            } catch (RemoteException re) {
19020            }
19021            return;
19022        }
19023        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19024        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19025        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19026            mContext.enforceCallingOrSelfPermission(
19027                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19028                    "deletePackage for user " + userId);
19029        }
19030
19031        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19032            try {
19033                observer.onPackageDeleted(packageName,
19034                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19035            } catch (RemoteException re) {
19036            }
19037            return;
19038        }
19039
19040        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19041            try {
19042                observer.onPackageDeleted(packageName,
19043                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19044            } catch (RemoteException re) {
19045            }
19046            return;
19047        }
19048
19049        if (DEBUG_REMOVE) {
19050            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19051                    + " deleteAllUsers: " + deleteAllUsers + " version="
19052                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19053                    ? "VERSION_CODE_HIGHEST" : versionCode));
19054        }
19055        // Queue up an async operation since the package deletion may take a little while.
19056        mHandler.post(new Runnable() {
19057            public void run() {
19058                mHandler.removeCallbacks(this);
19059                int returnCode;
19060                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19061                boolean doDeletePackage = true;
19062                if (ps != null) {
19063                    final boolean targetIsInstantApp =
19064                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19065                    doDeletePackage = !targetIsInstantApp
19066                            || canViewInstantApps;
19067                }
19068                if (doDeletePackage) {
19069                    if (!deleteAllUsers) {
19070                        returnCode = deletePackageX(internalPackageName, versionCode,
19071                                userId, deleteFlags);
19072                    } else {
19073                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19074                                internalPackageName, users);
19075                        // If nobody is blocking uninstall, proceed with delete for all users
19076                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19077                            returnCode = deletePackageX(internalPackageName, versionCode,
19078                                    userId, deleteFlags);
19079                        } else {
19080                            // Otherwise uninstall individually for users with blockUninstalls=false
19081                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19082                            for (int userId : users) {
19083                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19084                                    returnCode = deletePackageX(internalPackageName, versionCode,
19085                                            userId, userFlags);
19086                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19087                                        Slog.w(TAG, "Package delete failed for user " + userId
19088                                                + ", returnCode " + returnCode);
19089                                    }
19090                                }
19091                            }
19092                            // The app has only been marked uninstalled for certain users.
19093                            // We still need to report that delete was blocked
19094                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19095                        }
19096                    }
19097                } else {
19098                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19099                }
19100                try {
19101                    observer.onPackageDeleted(packageName, returnCode, null);
19102                } catch (RemoteException e) {
19103                    Log.i(TAG, "Observer no longer exists.");
19104                } //end catch
19105            } //end run
19106        });
19107    }
19108
19109    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19110        if (pkg.staticSharedLibName != null) {
19111            return pkg.manifestPackageName;
19112        }
19113        return pkg.packageName;
19114    }
19115
19116    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19117        // Handle renamed packages
19118        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19119        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19120
19121        // Is this a static library?
19122        SparseArray<SharedLibraryEntry> versionedLib =
19123                mStaticLibsByDeclaringPackage.get(packageName);
19124        if (versionedLib == null || versionedLib.size() <= 0) {
19125            return packageName;
19126        }
19127
19128        // Figure out which lib versions the caller can see
19129        SparseIntArray versionsCallerCanSee = null;
19130        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19131        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19132                && callingAppId != Process.ROOT_UID) {
19133            versionsCallerCanSee = new SparseIntArray();
19134            String libName = versionedLib.valueAt(0).info.getName();
19135            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19136            if (uidPackages != null) {
19137                for (String uidPackage : uidPackages) {
19138                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19139                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19140                    if (libIdx >= 0) {
19141                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19142                        versionsCallerCanSee.append(libVersion, libVersion);
19143                    }
19144                }
19145            }
19146        }
19147
19148        // Caller can see nothing - done
19149        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19150            return packageName;
19151        }
19152
19153        // Find the version the caller can see and the app version code
19154        SharedLibraryEntry highestVersion = null;
19155        final int versionCount = versionedLib.size();
19156        for (int i = 0; i < versionCount; i++) {
19157            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19158            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19159                    libEntry.info.getVersion()) < 0) {
19160                continue;
19161            }
19162            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19163            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19164                if (libVersionCode == versionCode) {
19165                    return libEntry.apk;
19166                }
19167            } else if (highestVersion == null) {
19168                highestVersion = libEntry;
19169            } else if (libVersionCode  > highestVersion.info
19170                    .getDeclaringPackage().getVersionCode()) {
19171                highestVersion = libEntry;
19172            }
19173        }
19174
19175        if (highestVersion != null) {
19176            return highestVersion.apk;
19177        }
19178
19179        return packageName;
19180    }
19181
19182    boolean isCallerVerifier(int callingUid) {
19183        final int callingUserId = UserHandle.getUserId(callingUid);
19184        return mRequiredVerifierPackage != null &&
19185                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19186    }
19187
19188    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19189        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19190              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19191            return true;
19192        }
19193        final int callingUserId = UserHandle.getUserId(callingUid);
19194        // If the caller installed the pkgName, then allow it to silently uninstall.
19195        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19196            return true;
19197        }
19198
19199        // Allow package verifier to silently uninstall.
19200        if (mRequiredVerifierPackage != null &&
19201                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19202            return true;
19203        }
19204
19205        // Allow package uninstaller to silently uninstall.
19206        if (mRequiredUninstallerPackage != null &&
19207                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19208            return true;
19209        }
19210
19211        // Allow storage manager to silently uninstall.
19212        if (mStorageManagerPackage != null &&
19213                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19214            return true;
19215        }
19216
19217        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19218        // uninstall for device owner provisioning.
19219        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19220                == PERMISSION_GRANTED) {
19221            return true;
19222        }
19223
19224        return false;
19225    }
19226
19227    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19228        int[] result = EMPTY_INT_ARRAY;
19229        for (int userId : userIds) {
19230            if (getBlockUninstallForUser(packageName, userId)) {
19231                result = ArrayUtils.appendInt(result, userId);
19232            }
19233        }
19234        return result;
19235    }
19236
19237    @Override
19238    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19239        final int callingUid = Binder.getCallingUid();
19240        if (getInstantAppPackageName(callingUid) != null
19241                && !isCallerSameApp(packageName, callingUid)) {
19242            return false;
19243        }
19244        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19245    }
19246
19247    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19248        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19249                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19250        try {
19251            if (dpm != null) {
19252                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19253                        /* callingUserOnly =*/ false);
19254                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19255                        : deviceOwnerComponentName.getPackageName();
19256                // Does the package contains the device owner?
19257                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19258                // this check is probably not needed, since DO should be registered as a device
19259                // admin on some user too. (Original bug for this: b/17657954)
19260                if (packageName.equals(deviceOwnerPackageName)) {
19261                    return true;
19262                }
19263                // Does it contain a device admin for any user?
19264                int[] users;
19265                if (userId == UserHandle.USER_ALL) {
19266                    users = sUserManager.getUserIds();
19267                } else {
19268                    users = new int[]{userId};
19269                }
19270                for (int i = 0; i < users.length; ++i) {
19271                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19272                        return true;
19273                    }
19274                }
19275            }
19276        } catch (RemoteException e) {
19277        }
19278        return false;
19279    }
19280
19281    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19282        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19283    }
19284
19285    /**
19286     *  This method is an internal method that could be get invoked either
19287     *  to delete an installed package or to clean up a failed installation.
19288     *  After deleting an installed package, a broadcast is sent to notify any
19289     *  listeners that the package has been removed. For cleaning up a failed
19290     *  installation, the broadcast is not necessary since the package's
19291     *  installation wouldn't have sent the initial broadcast either
19292     *  The key steps in deleting a package are
19293     *  deleting the package information in internal structures like mPackages,
19294     *  deleting the packages base directories through installd
19295     *  updating mSettings to reflect current status
19296     *  persisting settings for later use
19297     *  sending a broadcast if necessary
19298     */
19299    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19300        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19301        final boolean res;
19302
19303        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19304                ? UserHandle.USER_ALL : userId;
19305
19306        if (isPackageDeviceAdmin(packageName, removeUser)) {
19307            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19308            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19309        }
19310
19311        PackageSetting uninstalledPs = null;
19312        PackageParser.Package pkg = null;
19313
19314        // for the uninstall-updates case and restricted profiles, remember the per-
19315        // user handle installed state
19316        int[] allUsers;
19317        synchronized (mPackages) {
19318            uninstalledPs = mSettings.mPackages.get(packageName);
19319            if (uninstalledPs == null) {
19320                Slog.w(TAG, "Not removing non-existent package " + packageName);
19321                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19322            }
19323
19324            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19325                    && uninstalledPs.versionCode != versionCode) {
19326                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19327                        + uninstalledPs.versionCode + " != " + versionCode);
19328                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19329            }
19330
19331            // Static shared libs can be declared by any package, so let us not
19332            // allow removing a package if it provides a lib others depend on.
19333            pkg = mPackages.get(packageName);
19334
19335            allUsers = sUserManager.getUserIds();
19336
19337            if (pkg != null && pkg.staticSharedLibName != null) {
19338                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19339                        pkg.staticSharedLibVersion);
19340                if (libEntry != null) {
19341                    for (int currUserId : allUsers) {
19342                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19343                            continue;
19344                        }
19345                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19346                                libEntry.info, 0, currUserId);
19347                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19348                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19349                                    + " hosting lib " + libEntry.info.getName() + " version "
19350                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19351                                    + " for user " + currUserId);
19352                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19353                        }
19354                    }
19355                }
19356            }
19357
19358            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19359        }
19360
19361        final int freezeUser;
19362        if (isUpdatedSystemApp(uninstalledPs)
19363                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19364            // We're downgrading a system app, which will apply to all users, so
19365            // freeze them all during the downgrade
19366            freezeUser = UserHandle.USER_ALL;
19367        } else {
19368            freezeUser = removeUser;
19369        }
19370
19371        synchronized (mInstallLock) {
19372            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19373            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19374                    deleteFlags, "deletePackageX")) {
19375                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19376                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19377            }
19378            synchronized (mPackages) {
19379                if (res) {
19380                    if (pkg != null) {
19381                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19382                    }
19383                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19384                    updateInstantAppInstallerLocked(packageName);
19385                }
19386            }
19387        }
19388
19389        if (res) {
19390            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19391            info.sendPackageRemovedBroadcasts(killApp);
19392            info.sendSystemPackageUpdatedBroadcasts();
19393            info.sendSystemPackageAppearedBroadcasts();
19394        }
19395        // Force a gc here.
19396        Runtime.getRuntime().gc();
19397        // Delete the resources here after sending the broadcast to let
19398        // other processes clean up before deleting resources.
19399        if (info.args != null) {
19400            synchronized (mInstallLock) {
19401                info.args.doPostDeleteLI(true);
19402            }
19403        }
19404
19405        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19406    }
19407
19408    static class PackageRemovedInfo {
19409        final PackageSender packageSender;
19410        String removedPackage;
19411        String installerPackageName;
19412        int uid = -1;
19413        int removedAppId = -1;
19414        int[] origUsers;
19415        int[] removedUsers = null;
19416        int[] broadcastUsers = null;
19417        SparseArray<Integer> installReasons;
19418        boolean isRemovedPackageSystemUpdate = false;
19419        boolean isUpdate;
19420        boolean dataRemoved;
19421        boolean removedForAllUsers;
19422        boolean isStaticSharedLib;
19423        // Clean up resources deleted packages.
19424        InstallArgs args = null;
19425        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19426        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19427
19428        PackageRemovedInfo(PackageSender packageSender) {
19429            this.packageSender = packageSender;
19430        }
19431
19432        void sendPackageRemovedBroadcasts(boolean killApp) {
19433            sendPackageRemovedBroadcastInternal(killApp);
19434            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19435            for (int i = 0; i < childCount; i++) {
19436                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19437                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19438            }
19439        }
19440
19441        void sendSystemPackageUpdatedBroadcasts() {
19442            if (isRemovedPackageSystemUpdate) {
19443                sendSystemPackageUpdatedBroadcastsInternal();
19444                final int childCount = (removedChildPackages != null)
19445                        ? removedChildPackages.size() : 0;
19446                for (int i = 0; i < childCount; i++) {
19447                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19448                    if (childInfo.isRemovedPackageSystemUpdate) {
19449                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19450                    }
19451                }
19452            }
19453        }
19454
19455        void sendSystemPackageAppearedBroadcasts() {
19456            final int packageCount = (appearedChildPackages != null)
19457                    ? appearedChildPackages.size() : 0;
19458            for (int i = 0; i < packageCount; i++) {
19459                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19460                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19461                    true /*sendBootCompleted*/, false /*startReceiver*/,
19462                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19463            }
19464        }
19465
19466        private void sendSystemPackageUpdatedBroadcastsInternal() {
19467            Bundle extras = new Bundle(2);
19468            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19469            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19470            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19471                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19472            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19473                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19474            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19475                null, null, 0, removedPackage, null, null);
19476            if (installerPackageName != null) {
19477                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19478                        removedPackage, extras, 0 /*flags*/,
19479                        installerPackageName, null, null);
19480                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19481                        removedPackage, extras, 0 /*flags*/,
19482                        installerPackageName, null, null);
19483            }
19484        }
19485
19486        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19487            // Don't send static shared library removal broadcasts as these
19488            // libs are visible only the the apps that depend on them an one
19489            // cannot remove the library if it has a dependency.
19490            if (isStaticSharedLib) {
19491                return;
19492            }
19493            Bundle extras = new Bundle(2);
19494            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19495            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19496            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19497            if (isUpdate || isRemovedPackageSystemUpdate) {
19498                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19499            }
19500            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19501            if (removedPackage != null) {
19502                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19503                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19504                if (installerPackageName != null) {
19505                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19506                            removedPackage, extras, 0 /*flags*/,
19507                            installerPackageName, null, broadcastUsers);
19508                }
19509                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19510                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19511                        removedPackage, extras,
19512                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19513                        null, null, broadcastUsers);
19514                }
19515            }
19516            if (removedAppId >= 0) {
19517                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19518                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19519                    null, null, broadcastUsers);
19520            }
19521        }
19522
19523        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19524            removedUsers = userIds;
19525            if (removedUsers == null) {
19526                broadcastUsers = null;
19527                return;
19528            }
19529
19530            broadcastUsers = EMPTY_INT_ARRAY;
19531            for (int i = userIds.length - 1; i >= 0; --i) {
19532                final int userId = userIds[i];
19533                if (deletedPackageSetting.getInstantApp(userId)) {
19534                    continue;
19535                }
19536                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19537            }
19538        }
19539    }
19540
19541    /*
19542     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19543     * flag is not set, the data directory is removed as well.
19544     * make sure this flag is set for partially installed apps. If not its meaningless to
19545     * delete a partially installed application.
19546     */
19547    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19548            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19549        String packageName = ps.name;
19550        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19551        // Retrieve object to delete permissions for shared user later on
19552        final PackageParser.Package deletedPkg;
19553        final PackageSetting deletedPs;
19554        // reader
19555        synchronized (mPackages) {
19556            deletedPkg = mPackages.get(packageName);
19557            deletedPs = mSettings.mPackages.get(packageName);
19558            if (outInfo != null) {
19559                outInfo.removedPackage = packageName;
19560                outInfo.installerPackageName = ps.installerPackageName;
19561                outInfo.isStaticSharedLib = deletedPkg != null
19562                        && deletedPkg.staticSharedLibName != null;
19563                outInfo.populateUsers(deletedPs == null ? null
19564                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19565            }
19566        }
19567
19568        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19569
19570        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19571            final PackageParser.Package resolvedPkg;
19572            if (deletedPkg != null) {
19573                resolvedPkg = deletedPkg;
19574            } else {
19575                // We don't have a parsed package when it lives on an ejected
19576                // adopted storage device, so fake something together
19577                resolvedPkg = new PackageParser.Package(ps.name);
19578                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19579            }
19580            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19581                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19582            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19583            if (outInfo != null) {
19584                outInfo.dataRemoved = true;
19585            }
19586            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19587        }
19588
19589        int removedAppId = -1;
19590
19591        // writer
19592        synchronized (mPackages) {
19593            boolean installedStateChanged = false;
19594            if (deletedPs != null) {
19595                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19596                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19597                    clearDefaultBrowserIfNeeded(packageName);
19598                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19599                    removedAppId = mSettings.removePackageLPw(packageName);
19600                    if (outInfo != null) {
19601                        outInfo.removedAppId = removedAppId;
19602                    }
19603                    updatePermissionsLPw(deletedPs.name, null, 0);
19604                    if (deletedPs.sharedUser != null) {
19605                        // Remove permissions associated with package. Since runtime
19606                        // permissions are per user we have to kill the removed package
19607                        // or packages running under the shared user of the removed
19608                        // package if revoking the permissions requested only by the removed
19609                        // package is successful and this causes a change in gids.
19610                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19611                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19612                                    userId);
19613                            if (userIdToKill == UserHandle.USER_ALL
19614                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19615                                // If gids changed for this user, kill all affected packages.
19616                                mHandler.post(new Runnable() {
19617                                    @Override
19618                                    public void run() {
19619                                        // This has to happen with no lock held.
19620                                        killApplication(deletedPs.name, deletedPs.appId,
19621                                                KILL_APP_REASON_GIDS_CHANGED);
19622                                    }
19623                                });
19624                                break;
19625                            }
19626                        }
19627                    }
19628                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19629                }
19630                // make sure to preserve per-user disabled state if this removal was just
19631                // a downgrade of a system app to the factory package
19632                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19633                    if (DEBUG_REMOVE) {
19634                        Slog.d(TAG, "Propagating install state across downgrade");
19635                    }
19636                    for (int userId : allUserHandles) {
19637                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19638                        if (DEBUG_REMOVE) {
19639                            Slog.d(TAG, "    user " + userId + " => " + installed);
19640                        }
19641                        if (installed != ps.getInstalled(userId)) {
19642                            installedStateChanged = true;
19643                        }
19644                        ps.setInstalled(installed, userId);
19645                    }
19646                }
19647            }
19648            // can downgrade to reader
19649            if (writeSettings) {
19650                // Save settings now
19651                mSettings.writeLPr();
19652            }
19653            if (installedStateChanged) {
19654                mSettings.writeKernelMappingLPr(ps);
19655            }
19656        }
19657        if (removedAppId != -1) {
19658            // A user ID was deleted here. Go through all users and remove it
19659            // from KeyStore.
19660            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19661        }
19662    }
19663
19664    static boolean locationIsPrivileged(File path) {
19665        try {
19666            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19667                    .getCanonicalPath();
19668            return path.getCanonicalPath().startsWith(privilegedAppDir);
19669        } catch (IOException e) {
19670            Slog.e(TAG, "Unable to access code path " + path);
19671        }
19672        return false;
19673    }
19674
19675    /*
19676     * Tries to delete system package.
19677     */
19678    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19679            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19680            boolean writeSettings) {
19681        if (deletedPs.parentPackageName != null) {
19682            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19683            return false;
19684        }
19685
19686        final boolean applyUserRestrictions
19687                = (allUserHandles != null) && (outInfo.origUsers != null);
19688        final PackageSetting disabledPs;
19689        // Confirm if the system package has been updated
19690        // An updated system app can be deleted. This will also have to restore
19691        // the system pkg from system partition
19692        // reader
19693        synchronized (mPackages) {
19694            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19695        }
19696
19697        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19698                + " disabledPs=" + disabledPs);
19699
19700        if (disabledPs == null) {
19701            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19702            return false;
19703        } else if (DEBUG_REMOVE) {
19704            Slog.d(TAG, "Deleting system pkg from data partition");
19705        }
19706
19707        if (DEBUG_REMOVE) {
19708            if (applyUserRestrictions) {
19709                Slog.d(TAG, "Remembering install states:");
19710                for (int userId : allUserHandles) {
19711                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19712                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19713                }
19714            }
19715        }
19716
19717        // Delete the updated package
19718        outInfo.isRemovedPackageSystemUpdate = true;
19719        if (outInfo.removedChildPackages != null) {
19720            final int childCount = (deletedPs.childPackageNames != null)
19721                    ? deletedPs.childPackageNames.size() : 0;
19722            for (int i = 0; i < childCount; i++) {
19723                String childPackageName = deletedPs.childPackageNames.get(i);
19724                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19725                        .contains(childPackageName)) {
19726                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19727                            childPackageName);
19728                    if (childInfo != null) {
19729                        childInfo.isRemovedPackageSystemUpdate = true;
19730                    }
19731                }
19732            }
19733        }
19734
19735        if (disabledPs.versionCode < deletedPs.versionCode) {
19736            // Delete data for downgrades
19737            flags &= ~PackageManager.DELETE_KEEP_DATA;
19738        } else {
19739            // Preserve data by setting flag
19740            flags |= PackageManager.DELETE_KEEP_DATA;
19741        }
19742
19743        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19744                outInfo, writeSettings, disabledPs.pkg);
19745        if (!ret) {
19746            return false;
19747        }
19748
19749        // writer
19750        synchronized (mPackages) {
19751            // Reinstate the old system package
19752            enableSystemPackageLPw(disabledPs.pkg);
19753            // Remove any native libraries from the upgraded package.
19754            removeNativeBinariesLI(deletedPs);
19755        }
19756
19757        // Install the system package
19758        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19759        int parseFlags = mDefParseFlags
19760                | PackageParser.PARSE_MUST_BE_APK
19761                | PackageParser.PARSE_IS_SYSTEM
19762                | PackageParser.PARSE_IS_SYSTEM_DIR;
19763        if (locationIsPrivileged(disabledPs.codePath)) {
19764            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19765        }
19766
19767        final PackageParser.Package newPkg;
19768        try {
19769            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19770                0 /* currentTime */, null);
19771        } catch (PackageManagerException e) {
19772            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19773                    + e.getMessage());
19774            return false;
19775        }
19776
19777        try {
19778            // update shared libraries for the newly re-installed system package
19779            updateSharedLibrariesLPr(newPkg, null);
19780        } catch (PackageManagerException e) {
19781            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19782        }
19783
19784        prepareAppDataAfterInstallLIF(newPkg);
19785
19786        // writer
19787        synchronized (mPackages) {
19788            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19789
19790            // Propagate the permissions state as we do not want to drop on the floor
19791            // runtime permissions. The update permissions method below will take
19792            // care of removing obsolete permissions and grant install permissions.
19793            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19794            updatePermissionsLPw(newPkg.packageName, newPkg,
19795                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19796
19797            if (applyUserRestrictions) {
19798                boolean installedStateChanged = false;
19799                if (DEBUG_REMOVE) {
19800                    Slog.d(TAG, "Propagating install state across reinstall");
19801                }
19802                for (int userId : allUserHandles) {
19803                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19804                    if (DEBUG_REMOVE) {
19805                        Slog.d(TAG, "    user " + userId + " => " + installed);
19806                    }
19807                    if (installed != ps.getInstalled(userId)) {
19808                        installedStateChanged = true;
19809                    }
19810                    ps.setInstalled(installed, userId);
19811
19812                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19813                }
19814                // Regardless of writeSettings we need to ensure that this restriction
19815                // state propagation is persisted
19816                mSettings.writeAllUsersPackageRestrictionsLPr();
19817                if (installedStateChanged) {
19818                    mSettings.writeKernelMappingLPr(ps);
19819                }
19820            }
19821            // can downgrade to reader here
19822            if (writeSettings) {
19823                mSettings.writeLPr();
19824            }
19825        }
19826        return true;
19827    }
19828
19829    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19830            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19831            PackageRemovedInfo outInfo, boolean writeSettings,
19832            PackageParser.Package replacingPackage) {
19833        synchronized (mPackages) {
19834            if (outInfo != null) {
19835                outInfo.uid = ps.appId;
19836            }
19837
19838            if (outInfo != null && outInfo.removedChildPackages != null) {
19839                final int childCount = (ps.childPackageNames != null)
19840                        ? ps.childPackageNames.size() : 0;
19841                for (int i = 0; i < childCount; i++) {
19842                    String childPackageName = ps.childPackageNames.get(i);
19843                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19844                    if (childPs == null) {
19845                        return false;
19846                    }
19847                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19848                            childPackageName);
19849                    if (childInfo != null) {
19850                        childInfo.uid = childPs.appId;
19851                    }
19852                }
19853            }
19854        }
19855
19856        // Delete package data from internal structures and also remove data if flag is set
19857        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19858
19859        // Delete the child packages data
19860        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19861        for (int i = 0; i < childCount; i++) {
19862            PackageSetting childPs;
19863            synchronized (mPackages) {
19864                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19865            }
19866            if (childPs != null) {
19867                PackageRemovedInfo childOutInfo = (outInfo != null
19868                        && outInfo.removedChildPackages != null)
19869                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19870                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19871                        && (replacingPackage != null
19872                        && !replacingPackage.hasChildPackage(childPs.name))
19873                        ? flags & ~DELETE_KEEP_DATA : flags;
19874                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19875                        deleteFlags, writeSettings);
19876            }
19877        }
19878
19879        // Delete application code and resources only for parent packages
19880        if (ps.parentPackageName == null) {
19881            if (deleteCodeAndResources && (outInfo != null)) {
19882                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19883                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19884                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19885            }
19886        }
19887
19888        return true;
19889    }
19890
19891    @Override
19892    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19893            int userId) {
19894        mContext.enforceCallingOrSelfPermission(
19895                android.Manifest.permission.DELETE_PACKAGES, null);
19896        synchronized (mPackages) {
19897            // Cannot block uninstall of static shared libs as they are
19898            // considered a part of the using app (emulating static linking).
19899            // Also static libs are installed always on internal storage.
19900            PackageParser.Package pkg = mPackages.get(packageName);
19901            if (pkg != null && pkg.staticSharedLibName != null) {
19902                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19903                        + " providing static shared library: " + pkg.staticSharedLibName);
19904                return false;
19905            }
19906            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19907            mSettings.writePackageRestrictionsLPr(userId);
19908        }
19909        return true;
19910    }
19911
19912    @Override
19913    public boolean getBlockUninstallForUser(String packageName, int userId) {
19914        synchronized (mPackages) {
19915            final PackageSetting ps = mSettings.mPackages.get(packageName);
19916            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19917                return false;
19918            }
19919            return mSettings.getBlockUninstallLPr(userId, packageName);
19920        }
19921    }
19922
19923    @Override
19924    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19925        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19926        synchronized (mPackages) {
19927            PackageSetting ps = mSettings.mPackages.get(packageName);
19928            if (ps == null) {
19929                Log.w(TAG, "Package doesn't exist: " + packageName);
19930                return false;
19931            }
19932            if (systemUserApp) {
19933                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19934            } else {
19935                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19936            }
19937            mSettings.writeLPr();
19938        }
19939        return true;
19940    }
19941
19942    /*
19943     * This method handles package deletion in general
19944     */
19945    private boolean deletePackageLIF(String packageName, UserHandle user,
19946            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19947            PackageRemovedInfo outInfo, boolean writeSettings,
19948            PackageParser.Package replacingPackage) {
19949        if (packageName == null) {
19950            Slog.w(TAG, "Attempt to delete null packageName.");
19951            return false;
19952        }
19953
19954        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19955
19956        PackageSetting ps;
19957        synchronized (mPackages) {
19958            ps = mSettings.mPackages.get(packageName);
19959            if (ps == null) {
19960                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19961                return false;
19962            }
19963
19964            if (ps.parentPackageName != null && (!isSystemApp(ps)
19965                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19966                if (DEBUG_REMOVE) {
19967                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19968                            + ((user == null) ? UserHandle.USER_ALL : user));
19969                }
19970                final int removedUserId = (user != null) ? user.getIdentifier()
19971                        : UserHandle.USER_ALL;
19972                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19973                    return false;
19974                }
19975                markPackageUninstalledForUserLPw(ps, user);
19976                scheduleWritePackageRestrictionsLocked(user);
19977                return true;
19978            }
19979        }
19980
19981        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19982                && user.getIdentifier() != UserHandle.USER_ALL)) {
19983            // The caller is asking that the package only be deleted for a single
19984            // user.  To do this, we just mark its uninstalled state and delete
19985            // its data. If this is a system app, we only allow this to happen if
19986            // they have set the special DELETE_SYSTEM_APP which requests different
19987            // semantics than normal for uninstalling system apps.
19988            markPackageUninstalledForUserLPw(ps, user);
19989
19990            if (!isSystemApp(ps)) {
19991                // Do not uninstall the APK if an app should be cached
19992                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19993                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19994                    // Other user still have this package installed, so all
19995                    // we need to do is clear this user's data and save that
19996                    // it is uninstalled.
19997                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19998                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19999                        return false;
20000                    }
20001                    scheduleWritePackageRestrictionsLocked(user);
20002                    return true;
20003                } else {
20004                    // We need to set it back to 'installed' so the uninstall
20005                    // broadcasts will be sent correctly.
20006                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20007                    ps.setInstalled(true, user.getIdentifier());
20008                    mSettings.writeKernelMappingLPr(ps);
20009                }
20010            } else {
20011                // This is a system app, so we assume that the
20012                // other users still have this package installed, so all
20013                // we need to do is clear this user's data and save that
20014                // it is uninstalled.
20015                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20016                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20017                    return false;
20018                }
20019                scheduleWritePackageRestrictionsLocked(user);
20020                return true;
20021            }
20022        }
20023
20024        // If we are deleting a composite package for all users, keep track
20025        // of result for each child.
20026        if (ps.childPackageNames != null && outInfo != null) {
20027            synchronized (mPackages) {
20028                final int childCount = ps.childPackageNames.size();
20029                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20030                for (int i = 0; i < childCount; i++) {
20031                    String childPackageName = ps.childPackageNames.get(i);
20032                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20033                    childInfo.removedPackage = childPackageName;
20034                    childInfo.installerPackageName = ps.installerPackageName;
20035                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20036                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20037                    if (childPs != null) {
20038                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20039                    }
20040                }
20041            }
20042        }
20043
20044        boolean ret = false;
20045        if (isSystemApp(ps)) {
20046            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20047            // When an updated system application is deleted we delete the existing resources
20048            // as well and fall back to existing code in system partition
20049            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20050        } else {
20051            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20052            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20053                    outInfo, writeSettings, replacingPackage);
20054        }
20055
20056        // Take a note whether we deleted the package for all users
20057        if (outInfo != null) {
20058            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20059            if (outInfo.removedChildPackages != null) {
20060                synchronized (mPackages) {
20061                    final int childCount = outInfo.removedChildPackages.size();
20062                    for (int i = 0; i < childCount; i++) {
20063                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20064                        if (childInfo != null) {
20065                            childInfo.removedForAllUsers = mPackages.get(
20066                                    childInfo.removedPackage) == null;
20067                        }
20068                    }
20069                }
20070            }
20071            // If we uninstalled an update to a system app there may be some
20072            // child packages that appeared as they are declared in the system
20073            // app but were not declared in the update.
20074            if (isSystemApp(ps)) {
20075                synchronized (mPackages) {
20076                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20077                    final int childCount = (updatedPs.childPackageNames != null)
20078                            ? updatedPs.childPackageNames.size() : 0;
20079                    for (int i = 0; i < childCount; i++) {
20080                        String childPackageName = updatedPs.childPackageNames.get(i);
20081                        if (outInfo.removedChildPackages == null
20082                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20083                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20084                            if (childPs == null) {
20085                                continue;
20086                            }
20087                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20088                            installRes.name = childPackageName;
20089                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20090                            installRes.pkg = mPackages.get(childPackageName);
20091                            installRes.uid = childPs.pkg.applicationInfo.uid;
20092                            if (outInfo.appearedChildPackages == null) {
20093                                outInfo.appearedChildPackages = new ArrayMap<>();
20094                            }
20095                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20096                        }
20097                    }
20098                }
20099            }
20100        }
20101
20102        return ret;
20103    }
20104
20105    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20106        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20107                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20108        for (int nextUserId : userIds) {
20109            if (DEBUG_REMOVE) {
20110                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20111            }
20112            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20113                    false /*installed*/,
20114                    true /*stopped*/,
20115                    true /*notLaunched*/,
20116                    false /*hidden*/,
20117                    false /*suspended*/,
20118                    false /*instantApp*/,
20119                    false /*virtualPreload*/,
20120                    null /*lastDisableAppCaller*/,
20121                    null /*enabledComponents*/,
20122                    null /*disabledComponents*/,
20123                    ps.readUserState(nextUserId).domainVerificationStatus,
20124                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20125        }
20126        mSettings.writeKernelMappingLPr(ps);
20127    }
20128
20129    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20130            PackageRemovedInfo outInfo) {
20131        final PackageParser.Package pkg;
20132        synchronized (mPackages) {
20133            pkg = mPackages.get(ps.name);
20134        }
20135
20136        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20137                : new int[] {userId};
20138        for (int nextUserId : userIds) {
20139            if (DEBUG_REMOVE) {
20140                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20141                        + nextUserId);
20142            }
20143
20144            destroyAppDataLIF(pkg, userId,
20145                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20146            destroyAppProfilesLIF(pkg, userId);
20147            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20148            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20149            schedulePackageCleaning(ps.name, nextUserId, false);
20150            synchronized (mPackages) {
20151                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20152                    scheduleWritePackageRestrictionsLocked(nextUserId);
20153                }
20154                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20155            }
20156        }
20157
20158        if (outInfo != null) {
20159            outInfo.removedPackage = ps.name;
20160            outInfo.installerPackageName = ps.installerPackageName;
20161            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20162            outInfo.removedAppId = ps.appId;
20163            outInfo.removedUsers = userIds;
20164            outInfo.broadcastUsers = userIds;
20165        }
20166
20167        return true;
20168    }
20169
20170    private final class ClearStorageConnection implements ServiceConnection {
20171        IMediaContainerService mContainerService;
20172
20173        @Override
20174        public void onServiceConnected(ComponentName name, IBinder service) {
20175            synchronized (this) {
20176                mContainerService = IMediaContainerService.Stub
20177                        .asInterface(Binder.allowBlocking(service));
20178                notifyAll();
20179            }
20180        }
20181
20182        @Override
20183        public void onServiceDisconnected(ComponentName name) {
20184        }
20185    }
20186
20187    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20188        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20189
20190        final boolean mounted;
20191        if (Environment.isExternalStorageEmulated()) {
20192            mounted = true;
20193        } else {
20194            final String status = Environment.getExternalStorageState();
20195
20196            mounted = status.equals(Environment.MEDIA_MOUNTED)
20197                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20198        }
20199
20200        if (!mounted) {
20201            return;
20202        }
20203
20204        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20205        int[] users;
20206        if (userId == UserHandle.USER_ALL) {
20207            users = sUserManager.getUserIds();
20208        } else {
20209            users = new int[] { userId };
20210        }
20211        final ClearStorageConnection conn = new ClearStorageConnection();
20212        if (mContext.bindServiceAsUser(
20213                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20214            try {
20215                for (int curUser : users) {
20216                    long timeout = SystemClock.uptimeMillis() + 5000;
20217                    synchronized (conn) {
20218                        long now;
20219                        while (conn.mContainerService == null &&
20220                                (now = SystemClock.uptimeMillis()) < timeout) {
20221                            try {
20222                                conn.wait(timeout - now);
20223                            } catch (InterruptedException e) {
20224                            }
20225                        }
20226                    }
20227                    if (conn.mContainerService == null) {
20228                        return;
20229                    }
20230
20231                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20232                    clearDirectory(conn.mContainerService,
20233                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20234                    if (allData) {
20235                        clearDirectory(conn.mContainerService,
20236                                userEnv.buildExternalStorageAppDataDirs(packageName));
20237                        clearDirectory(conn.mContainerService,
20238                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20239                    }
20240                }
20241            } finally {
20242                mContext.unbindService(conn);
20243            }
20244        }
20245    }
20246
20247    @Override
20248    public void clearApplicationProfileData(String packageName) {
20249        enforceSystemOrRoot("Only the system can clear all profile data");
20250
20251        final PackageParser.Package pkg;
20252        synchronized (mPackages) {
20253            pkg = mPackages.get(packageName);
20254        }
20255
20256        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20257            synchronized (mInstallLock) {
20258                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20259            }
20260        }
20261    }
20262
20263    @Override
20264    public void clearApplicationUserData(final String packageName,
20265            final IPackageDataObserver observer, final int userId) {
20266        mContext.enforceCallingOrSelfPermission(
20267                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20268
20269        final int callingUid = Binder.getCallingUid();
20270        enforceCrossUserPermission(callingUid, userId,
20271                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20272
20273        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20274        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20275        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20276            throw new SecurityException("Cannot clear data for a protected package: "
20277                    + packageName);
20278        }
20279        // Queue up an async operation since the package deletion may take a little while.
20280        mHandler.post(new Runnable() {
20281            public void run() {
20282                mHandler.removeCallbacks(this);
20283                final boolean succeeded;
20284                if (!filterApp) {
20285                    try (PackageFreezer freezer = freezePackage(packageName,
20286                            "clearApplicationUserData")) {
20287                        synchronized (mInstallLock) {
20288                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20289                        }
20290                        clearExternalStorageDataSync(packageName, userId, true);
20291                        synchronized (mPackages) {
20292                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20293                                    packageName, userId);
20294                        }
20295                    }
20296                    if (succeeded) {
20297                        // invoke DeviceStorageMonitor's update method to clear any notifications
20298                        DeviceStorageMonitorInternal dsm = LocalServices
20299                                .getService(DeviceStorageMonitorInternal.class);
20300                        if (dsm != null) {
20301                            dsm.checkMemory();
20302                        }
20303                    }
20304                } else {
20305                    succeeded = false;
20306                }
20307                if (observer != null) {
20308                    try {
20309                        observer.onRemoveCompleted(packageName, succeeded);
20310                    } catch (RemoteException e) {
20311                        Log.i(TAG, "Observer no longer exists.");
20312                    }
20313                } //end if observer
20314            } //end run
20315        });
20316    }
20317
20318    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20319        if (packageName == null) {
20320            Slog.w(TAG, "Attempt to delete null packageName.");
20321            return false;
20322        }
20323
20324        // Try finding details about the requested package
20325        PackageParser.Package pkg;
20326        synchronized (mPackages) {
20327            pkg = mPackages.get(packageName);
20328            if (pkg == null) {
20329                final PackageSetting ps = mSettings.mPackages.get(packageName);
20330                if (ps != null) {
20331                    pkg = ps.pkg;
20332                }
20333            }
20334
20335            if (pkg == null) {
20336                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20337                return false;
20338            }
20339
20340            PackageSetting ps = (PackageSetting) pkg.mExtras;
20341            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20342        }
20343
20344        clearAppDataLIF(pkg, userId,
20345                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20346
20347        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20348        removeKeystoreDataIfNeeded(userId, appId);
20349
20350        UserManagerInternal umInternal = getUserManagerInternal();
20351        final int flags;
20352        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20353            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20354        } else if (umInternal.isUserRunning(userId)) {
20355            flags = StorageManager.FLAG_STORAGE_DE;
20356        } else {
20357            flags = 0;
20358        }
20359        prepareAppDataContentsLIF(pkg, userId, flags);
20360
20361        return true;
20362    }
20363
20364    /**
20365     * Reverts user permission state changes (permissions and flags) in
20366     * all packages for a given user.
20367     *
20368     * @param userId The device user for which to do a reset.
20369     */
20370    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20371        final int packageCount = mPackages.size();
20372        for (int i = 0; i < packageCount; i++) {
20373            PackageParser.Package pkg = mPackages.valueAt(i);
20374            PackageSetting ps = (PackageSetting) pkg.mExtras;
20375            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20376        }
20377    }
20378
20379    private void resetNetworkPolicies(int userId) {
20380        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20381    }
20382
20383    /**
20384     * Reverts user permission state changes (permissions and flags).
20385     *
20386     * @param ps The package for which to reset.
20387     * @param userId The device user for which to do a reset.
20388     */
20389    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20390            final PackageSetting ps, final int userId) {
20391        if (ps.pkg == null) {
20392            return;
20393        }
20394
20395        // These are flags that can change base on user actions.
20396        final int userSettableMask = FLAG_PERMISSION_USER_SET
20397                | FLAG_PERMISSION_USER_FIXED
20398                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20399                | FLAG_PERMISSION_REVIEW_REQUIRED;
20400
20401        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20402                | FLAG_PERMISSION_POLICY_FIXED;
20403
20404        boolean writeInstallPermissions = false;
20405        boolean writeRuntimePermissions = false;
20406
20407        final int permissionCount = ps.pkg.requestedPermissions.size();
20408        for (int i = 0; i < permissionCount; i++) {
20409            String permission = ps.pkg.requestedPermissions.get(i);
20410
20411            BasePermission bp = mSettings.mPermissions.get(permission);
20412            if (bp == null) {
20413                continue;
20414            }
20415
20416            // If shared user we just reset the state to which only this app contributed.
20417            if (ps.sharedUser != null) {
20418                boolean used = false;
20419                final int packageCount = ps.sharedUser.packages.size();
20420                for (int j = 0; j < packageCount; j++) {
20421                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20422                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20423                            && pkg.pkg.requestedPermissions.contains(permission)) {
20424                        used = true;
20425                        break;
20426                    }
20427                }
20428                if (used) {
20429                    continue;
20430                }
20431            }
20432
20433            PermissionsState permissionsState = ps.getPermissionsState();
20434
20435            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20436
20437            // Always clear the user settable flags.
20438            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20439                    bp.name) != null;
20440            // If permission review is enabled and this is a legacy app, mark the
20441            // permission as requiring a review as this is the initial state.
20442            int flags = 0;
20443            if (mPermissionReviewRequired
20444                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20445                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20446            }
20447            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20448                if (hasInstallState) {
20449                    writeInstallPermissions = true;
20450                } else {
20451                    writeRuntimePermissions = true;
20452                }
20453            }
20454
20455            // Below is only runtime permission handling.
20456            if (!bp.isRuntime()) {
20457                continue;
20458            }
20459
20460            // Never clobber system or policy.
20461            if ((oldFlags & policyOrSystemFlags) != 0) {
20462                continue;
20463            }
20464
20465            // If this permission was granted by default, make sure it is.
20466            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20467                if (permissionsState.grantRuntimePermission(bp, userId)
20468                        != PERMISSION_OPERATION_FAILURE) {
20469                    writeRuntimePermissions = true;
20470                }
20471            // If permission review is enabled the permissions for a legacy apps
20472            // are represented as constantly granted runtime ones, so don't revoke.
20473            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20474                // Otherwise, reset the permission.
20475                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20476                switch (revokeResult) {
20477                    case PERMISSION_OPERATION_SUCCESS:
20478                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20479                        writeRuntimePermissions = true;
20480                        final int appId = ps.appId;
20481                        mHandler.post(new Runnable() {
20482                            @Override
20483                            public void run() {
20484                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20485                            }
20486                        });
20487                    } break;
20488                }
20489            }
20490        }
20491
20492        // Synchronously write as we are taking permissions away.
20493        if (writeRuntimePermissions) {
20494            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20495        }
20496
20497        // Synchronously write as we are taking permissions away.
20498        if (writeInstallPermissions) {
20499            mSettings.writeLPr();
20500        }
20501    }
20502
20503    /**
20504     * Remove entries from the keystore daemon. Will only remove it if the
20505     * {@code appId} is valid.
20506     */
20507    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20508        if (appId < 0) {
20509            return;
20510        }
20511
20512        final KeyStore keyStore = KeyStore.getInstance();
20513        if (keyStore != null) {
20514            if (userId == UserHandle.USER_ALL) {
20515                for (final int individual : sUserManager.getUserIds()) {
20516                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20517                }
20518            } else {
20519                keyStore.clearUid(UserHandle.getUid(userId, appId));
20520            }
20521        } else {
20522            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20523        }
20524    }
20525
20526    @Override
20527    public void deleteApplicationCacheFiles(final String packageName,
20528            final IPackageDataObserver observer) {
20529        final int userId = UserHandle.getCallingUserId();
20530        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20531    }
20532
20533    @Override
20534    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20535            final IPackageDataObserver observer) {
20536        final int callingUid = Binder.getCallingUid();
20537        mContext.enforceCallingOrSelfPermission(
20538                android.Manifest.permission.DELETE_CACHE_FILES, null);
20539        enforceCrossUserPermission(callingUid, userId,
20540                /* requireFullPermission= */ true, /* checkShell= */ false,
20541                "delete application cache files");
20542        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20543                android.Manifest.permission.ACCESS_INSTANT_APPS);
20544
20545        final PackageParser.Package pkg;
20546        synchronized (mPackages) {
20547            pkg = mPackages.get(packageName);
20548        }
20549
20550        // Queue up an async operation since the package deletion may take a little while.
20551        mHandler.post(new Runnable() {
20552            public void run() {
20553                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20554                boolean doClearData = true;
20555                if (ps != null) {
20556                    final boolean targetIsInstantApp =
20557                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20558                    doClearData = !targetIsInstantApp
20559                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20560                }
20561                if (doClearData) {
20562                    synchronized (mInstallLock) {
20563                        final int flags = StorageManager.FLAG_STORAGE_DE
20564                                | StorageManager.FLAG_STORAGE_CE;
20565                        // We're only clearing cache files, so we don't care if the
20566                        // app is unfrozen and still able to run
20567                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20568                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20569                    }
20570                    clearExternalStorageDataSync(packageName, userId, false);
20571                }
20572                if (observer != null) {
20573                    try {
20574                        observer.onRemoveCompleted(packageName, true);
20575                    } catch (RemoteException e) {
20576                        Log.i(TAG, "Observer no longer exists.");
20577                    }
20578                }
20579            }
20580        });
20581    }
20582
20583    @Override
20584    public void getPackageSizeInfo(final String packageName, int userHandle,
20585            final IPackageStatsObserver observer) {
20586        throw new UnsupportedOperationException(
20587                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20588    }
20589
20590    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20591        final PackageSetting ps;
20592        synchronized (mPackages) {
20593            ps = mSettings.mPackages.get(packageName);
20594            if (ps == null) {
20595                Slog.w(TAG, "Failed to find settings for " + packageName);
20596                return false;
20597            }
20598        }
20599
20600        final String[] packageNames = { packageName };
20601        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20602        final String[] codePaths = { ps.codePathString };
20603
20604        try {
20605            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20606                    ps.appId, ceDataInodes, codePaths, stats);
20607
20608            // For now, ignore code size of packages on system partition
20609            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20610                stats.codeSize = 0;
20611            }
20612
20613            // External clients expect these to be tracked separately
20614            stats.dataSize -= stats.cacheSize;
20615
20616        } catch (InstallerException e) {
20617            Slog.w(TAG, String.valueOf(e));
20618            return false;
20619        }
20620
20621        return true;
20622    }
20623
20624    private int getUidTargetSdkVersionLockedLPr(int uid) {
20625        Object obj = mSettings.getUserIdLPr(uid);
20626        if (obj instanceof SharedUserSetting) {
20627            final SharedUserSetting sus = (SharedUserSetting) obj;
20628            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20629            final Iterator<PackageSetting> it = sus.packages.iterator();
20630            while (it.hasNext()) {
20631                final PackageSetting ps = it.next();
20632                if (ps.pkg != null) {
20633                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20634                    if (v < vers) vers = v;
20635                }
20636            }
20637            return vers;
20638        } else if (obj instanceof PackageSetting) {
20639            final PackageSetting ps = (PackageSetting) obj;
20640            if (ps.pkg != null) {
20641                return ps.pkg.applicationInfo.targetSdkVersion;
20642            }
20643        }
20644        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20645    }
20646
20647    @Override
20648    public void addPreferredActivity(IntentFilter filter, int match,
20649            ComponentName[] set, ComponentName activity, int userId) {
20650        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20651                "Adding preferred");
20652    }
20653
20654    private void addPreferredActivityInternal(IntentFilter filter, int match,
20655            ComponentName[] set, ComponentName activity, boolean always, int userId,
20656            String opname) {
20657        // writer
20658        int callingUid = Binder.getCallingUid();
20659        enforceCrossUserPermission(callingUid, userId,
20660                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20661        if (filter.countActions() == 0) {
20662            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20663            return;
20664        }
20665        synchronized (mPackages) {
20666            if (mContext.checkCallingOrSelfPermission(
20667                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20668                    != PackageManager.PERMISSION_GRANTED) {
20669                if (getUidTargetSdkVersionLockedLPr(callingUid)
20670                        < Build.VERSION_CODES.FROYO) {
20671                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20672                            + callingUid);
20673                    return;
20674                }
20675                mContext.enforceCallingOrSelfPermission(
20676                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20677            }
20678
20679            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20680            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20681                    + userId + ":");
20682            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20683            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20684            scheduleWritePackageRestrictionsLocked(userId);
20685            postPreferredActivityChangedBroadcast(userId);
20686        }
20687    }
20688
20689    private void postPreferredActivityChangedBroadcast(int userId) {
20690        mHandler.post(() -> {
20691            final IActivityManager am = ActivityManager.getService();
20692            if (am == null) {
20693                return;
20694            }
20695
20696            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20697            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20698            try {
20699                am.broadcastIntent(null, intent, null, null,
20700                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20701                        null, false, false, userId);
20702            } catch (RemoteException e) {
20703            }
20704        });
20705    }
20706
20707    @Override
20708    public void replacePreferredActivity(IntentFilter filter, int match,
20709            ComponentName[] set, ComponentName activity, int userId) {
20710        if (filter.countActions() != 1) {
20711            throw new IllegalArgumentException(
20712                    "replacePreferredActivity expects filter to have only 1 action.");
20713        }
20714        if (filter.countDataAuthorities() != 0
20715                || filter.countDataPaths() != 0
20716                || filter.countDataSchemes() > 1
20717                || filter.countDataTypes() != 0) {
20718            throw new IllegalArgumentException(
20719                    "replacePreferredActivity expects filter to have no data authorities, " +
20720                    "paths, or types; and at most one scheme.");
20721        }
20722
20723        final int callingUid = Binder.getCallingUid();
20724        enforceCrossUserPermission(callingUid, userId,
20725                true /* requireFullPermission */, false /* checkShell */,
20726                "replace preferred activity");
20727        synchronized (mPackages) {
20728            if (mContext.checkCallingOrSelfPermission(
20729                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20730                    != PackageManager.PERMISSION_GRANTED) {
20731                if (getUidTargetSdkVersionLockedLPr(callingUid)
20732                        < Build.VERSION_CODES.FROYO) {
20733                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20734                            + Binder.getCallingUid());
20735                    return;
20736                }
20737                mContext.enforceCallingOrSelfPermission(
20738                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20739            }
20740
20741            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20742            if (pir != null) {
20743                // Get all of the existing entries that exactly match this filter.
20744                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20745                if (existing != null && existing.size() == 1) {
20746                    PreferredActivity cur = existing.get(0);
20747                    if (DEBUG_PREFERRED) {
20748                        Slog.i(TAG, "Checking replace of preferred:");
20749                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20750                        if (!cur.mPref.mAlways) {
20751                            Slog.i(TAG, "  -- CUR; not mAlways!");
20752                        } else {
20753                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20754                            Slog.i(TAG, "  -- CUR: mSet="
20755                                    + Arrays.toString(cur.mPref.mSetComponents));
20756                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20757                            Slog.i(TAG, "  -- NEW: mMatch="
20758                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20759                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20760                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20761                        }
20762                    }
20763                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20764                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20765                            && cur.mPref.sameSet(set)) {
20766                        // Setting the preferred activity to what it happens to be already
20767                        if (DEBUG_PREFERRED) {
20768                            Slog.i(TAG, "Replacing with same preferred activity "
20769                                    + cur.mPref.mShortComponent + " for user "
20770                                    + userId + ":");
20771                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20772                        }
20773                        return;
20774                    }
20775                }
20776
20777                if (existing != null) {
20778                    if (DEBUG_PREFERRED) {
20779                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20780                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20781                    }
20782                    for (int i = 0; i < existing.size(); i++) {
20783                        PreferredActivity pa = existing.get(i);
20784                        if (DEBUG_PREFERRED) {
20785                            Slog.i(TAG, "Removing existing preferred activity "
20786                                    + pa.mPref.mComponent + ":");
20787                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20788                        }
20789                        pir.removeFilter(pa);
20790                    }
20791                }
20792            }
20793            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20794                    "Replacing preferred");
20795        }
20796    }
20797
20798    @Override
20799    public void clearPackagePreferredActivities(String packageName) {
20800        final int callingUid = Binder.getCallingUid();
20801        if (getInstantAppPackageName(callingUid) != null) {
20802            return;
20803        }
20804        // writer
20805        synchronized (mPackages) {
20806            PackageParser.Package pkg = mPackages.get(packageName);
20807            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20808                if (mContext.checkCallingOrSelfPermission(
20809                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20810                        != PackageManager.PERMISSION_GRANTED) {
20811                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20812                            < Build.VERSION_CODES.FROYO) {
20813                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20814                                + callingUid);
20815                        return;
20816                    }
20817                    mContext.enforceCallingOrSelfPermission(
20818                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20819                }
20820            }
20821            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20822            if (ps != null
20823                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20824                return;
20825            }
20826            int user = UserHandle.getCallingUserId();
20827            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20828                scheduleWritePackageRestrictionsLocked(user);
20829            }
20830        }
20831    }
20832
20833    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20834    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20835        ArrayList<PreferredActivity> removed = null;
20836        boolean changed = false;
20837        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20838            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20839            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20840            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20841                continue;
20842            }
20843            Iterator<PreferredActivity> it = pir.filterIterator();
20844            while (it.hasNext()) {
20845                PreferredActivity pa = it.next();
20846                // Mark entry for removal only if it matches the package name
20847                // and the entry is of type "always".
20848                if (packageName == null ||
20849                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20850                                && pa.mPref.mAlways)) {
20851                    if (removed == null) {
20852                        removed = new ArrayList<PreferredActivity>();
20853                    }
20854                    removed.add(pa);
20855                }
20856            }
20857            if (removed != null) {
20858                for (int j=0; j<removed.size(); j++) {
20859                    PreferredActivity pa = removed.get(j);
20860                    pir.removeFilter(pa);
20861                }
20862                changed = true;
20863            }
20864        }
20865        if (changed) {
20866            postPreferredActivityChangedBroadcast(userId);
20867        }
20868        return changed;
20869    }
20870
20871    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20872    private void clearIntentFilterVerificationsLPw(int userId) {
20873        final int packageCount = mPackages.size();
20874        for (int i = 0; i < packageCount; i++) {
20875            PackageParser.Package pkg = mPackages.valueAt(i);
20876            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20877        }
20878    }
20879
20880    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20881    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20882        if (userId == UserHandle.USER_ALL) {
20883            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20884                    sUserManager.getUserIds())) {
20885                for (int oneUserId : sUserManager.getUserIds()) {
20886                    scheduleWritePackageRestrictionsLocked(oneUserId);
20887                }
20888            }
20889        } else {
20890            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20891                scheduleWritePackageRestrictionsLocked(userId);
20892            }
20893        }
20894    }
20895
20896    /** Clears state for all users, and touches intent filter verification policy */
20897    void clearDefaultBrowserIfNeeded(String packageName) {
20898        for (int oneUserId : sUserManager.getUserIds()) {
20899            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20900        }
20901    }
20902
20903    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20904        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20905        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20906            if (packageName.equals(defaultBrowserPackageName)) {
20907                setDefaultBrowserPackageName(null, userId);
20908            }
20909        }
20910    }
20911
20912    @Override
20913    public void resetApplicationPreferences(int userId) {
20914        mContext.enforceCallingOrSelfPermission(
20915                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20916        final long identity = Binder.clearCallingIdentity();
20917        // writer
20918        try {
20919            synchronized (mPackages) {
20920                clearPackagePreferredActivitiesLPw(null, userId);
20921                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20922                // TODO: We have to reset the default SMS and Phone. This requires
20923                // significant refactoring to keep all default apps in the package
20924                // manager (cleaner but more work) or have the services provide
20925                // callbacks to the package manager to request a default app reset.
20926                applyFactoryDefaultBrowserLPw(userId);
20927                clearIntentFilterVerificationsLPw(userId);
20928                primeDomainVerificationsLPw(userId);
20929                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20930                scheduleWritePackageRestrictionsLocked(userId);
20931            }
20932            resetNetworkPolicies(userId);
20933        } finally {
20934            Binder.restoreCallingIdentity(identity);
20935        }
20936    }
20937
20938    @Override
20939    public int getPreferredActivities(List<IntentFilter> outFilters,
20940            List<ComponentName> outActivities, String packageName) {
20941        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20942            return 0;
20943        }
20944        int num = 0;
20945        final int userId = UserHandle.getCallingUserId();
20946        // reader
20947        synchronized (mPackages) {
20948            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20949            if (pir != null) {
20950                final Iterator<PreferredActivity> it = pir.filterIterator();
20951                while (it.hasNext()) {
20952                    final PreferredActivity pa = it.next();
20953                    if (packageName == null
20954                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20955                                    && pa.mPref.mAlways)) {
20956                        if (outFilters != null) {
20957                            outFilters.add(new IntentFilter(pa));
20958                        }
20959                        if (outActivities != null) {
20960                            outActivities.add(pa.mPref.mComponent);
20961                        }
20962                    }
20963                }
20964            }
20965        }
20966
20967        return num;
20968    }
20969
20970    @Override
20971    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20972            int userId) {
20973        int callingUid = Binder.getCallingUid();
20974        if (callingUid != Process.SYSTEM_UID) {
20975            throw new SecurityException(
20976                    "addPersistentPreferredActivity can only be run by the system");
20977        }
20978        if (filter.countActions() == 0) {
20979            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20980            return;
20981        }
20982        synchronized (mPackages) {
20983            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20984                    ":");
20985            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20986            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20987                    new PersistentPreferredActivity(filter, activity));
20988            scheduleWritePackageRestrictionsLocked(userId);
20989            postPreferredActivityChangedBroadcast(userId);
20990        }
20991    }
20992
20993    @Override
20994    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20995        int callingUid = Binder.getCallingUid();
20996        if (callingUid != Process.SYSTEM_UID) {
20997            throw new SecurityException(
20998                    "clearPackagePersistentPreferredActivities can only be run by the system");
20999        }
21000        ArrayList<PersistentPreferredActivity> removed = null;
21001        boolean changed = false;
21002        synchronized (mPackages) {
21003            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21004                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21005                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21006                        .valueAt(i);
21007                if (userId != thisUserId) {
21008                    continue;
21009                }
21010                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21011                while (it.hasNext()) {
21012                    PersistentPreferredActivity ppa = it.next();
21013                    // Mark entry for removal only if it matches the package name.
21014                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21015                        if (removed == null) {
21016                            removed = new ArrayList<PersistentPreferredActivity>();
21017                        }
21018                        removed.add(ppa);
21019                    }
21020                }
21021                if (removed != null) {
21022                    for (int j=0; j<removed.size(); j++) {
21023                        PersistentPreferredActivity ppa = removed.get(j);
21024                        ppir.removeFilter(ppa);
21025                    }
21026                    changed = true;
21027                }
21028            }
21029
21030            if (changed) {
21031                scheduleWritePackageRestrictionsLocked(userId);
21032                postPreferredActivityChangedBroadcast(userId);
21033            }
21034        }
21035    }
21036
21037    /**
21038     * Common machinery for picking apart a restored XML blob and passing
21039     * it to a caller-supplied functor to be applied to the running system.
21040     */
21041    private void restoreFromXml(XmlPullParser parser, int userId,
21042            String expectedStartTag, BlobXmlRestorer functor)
21043            throws IOException, XmlPullParserException {
21044        int type;
21045        while ((type = parser.next()) != XmlPullParser.START_TAG
21046                && type != XmlPullParser.END_DOCUMENT) {
21047        }
21048        if (type != XmlPullParser.START_TAG) {
21049            // oops didn't find a start tag?!
21050            if (DEBUG_BACKUP) {
21051                Slog.e(TAG, "Didn't find start tag during restore");
21052            }
21053            return;
21054        }
21055Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21056        // this is supposed to be TAG_PREFERRED_BACKUP
21057        if (!expectedStartTag.equals(parser.getName())) {
21058            if (DEBUG_BACKUP) {
21059                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21060            }
21061            return;
21062        }
21063
21064        // skip interfering stuff, then we're aligned with the backing implementation
21065        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21066Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21067        functor.apply(parser, userId);
21068    }
21069
21070    private interface BlobXmlRestorer {
21071        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21072    }
21073
21074    /**
21075     * Non-Binder method, support for the backup/restore mechanism: write the
21076     * full set of preferred activities in its canonical XML format.  Returns the
21077     * XML output as a byte array, or null if there is none.
21078     */
21079    @Override
21080    public byte[] getPreferredActivityBackup(int userId) {
21081        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21082            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21083        }
21084
21085        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21086        try {
21087            final XmlSerializer serializer = new FastXmlSerializer();
21088            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21089            serializer.startDocument(null, true);
21090            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21091
21092            synchronized (mPackages) {
21093                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21094            }
21095
21096            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21097            serializer.endDocument();
21098            serializer.flush();
21099        } catch (Exception e) {
21100            if (DEBUG_BACKUP) {
21101                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21102            }
21103            return null;
21104        }
21105
21106        return dataStream.toByteArray();
21107    }
21108
21109    @Override
21110    public void restorePreferredActivities(byte[] backup, int userId) {
21111        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21112            throw new SecurityException("Only the system may call restorePreferredActivities()");
21113        }
21114
21115        try {
21116            final XmlPullParser parser = Xml.newPullParser();
21117            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21118            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21119                    new BlobXmlRestorer() {
21120                        @Override
21121                        public void apply(XmlPullParser parser, int userId)
21122                                throws XmlPullParserException, IOException {
21123                            synchronized (mPackages) {
21124                                mSettings.readPreferredActivitiesLPw(parser, userId);
21125                            }
21126                        }
21127                    } );
21128        } catch (Exception e) {
21129            if (DEBUG_BACKUP) {
21130                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21131            }
21132        }
21133    }
21134
21135    /**
21136     * Non-Binder method, support for the backup/restore mechanism: write the
21137     * default browser (etc) settings in its canonical XML format.  Returns the default
21138     * browser XML representation as a byte array, or null if there is none.
21139     */
21140    @Override
21141    public byte[] getDefaultAppsBackup(int userId) {
21142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21143            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21144        }
21145
21146        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21147        try {
21148            final XmlSerializer serializer = new FastXmlSerializer();
21149            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21150            serializer.startDocument(null, true);
21151            serializer.startTag(null, TAG_DEFAULT_APPS);
21152
21153            synchronized (mPackages) {
21154                mSettings.writeDefaultAppsLPr(serializer, userId);
21155            }
21156
21157            serializer.endTag(null, TAG_DEFAULT_APPS);
21158            serializer.endDocument();
21159            serializer.flush();
21160        } catch (Exception e) {
21161            if (DEBUG_BACKUP) {
21162                Slog.e(TAG, "Unable to write default apps for backup", e);
21163            }
21164            return null;
21165        }
21166
21167        return dataStream.toByteArray();
21168    }
21169
21170    @Override
21171    public void restoreDefaultApps(byte[] backup, int userId) {
21172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21173            throw new SecurityException("Only the system may call restoreDefaultApps()");
21174        }
21175
21176        try {
21177            final XmlPullParser parser = Xml.newPullParser();
21178            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21179            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21180                    new BlobXmlRestorer() {
21181                        @Override
21182                        public void apply(XmlPullParser parser, int userId)
21183                                throws XmlPullParserException, IOException {
21184                            synchronized (mPackages) {
21185                                mSettings.readDefaultAppsLPw(parser, userId);
21186                            }
21187                        }
21188                    } );
21189        } catch (Exception e) {
21190            if (DEBUG_BACKUP) {
21191                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21192            }
21193        }
21194    }
21195
21196    @Override
21197    public byte[] getIntentFilterVerificationBackup(int userId) {
21198        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21199            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21200        }
21201
21202        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21203        try {
21204            final XmlSerializer serializer = new FastXmlSerializer();
21205            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21206            serializer.startDocument(null, true);
21207            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21208
21209            synchronized (mPackages) {
21210                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21211            }
21212
21213            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21214            serializer.endDocument();
21215            serializer.flush();
21216        } catch (Exception e) {
21217            if (DEBUG_BACKUP) {
21218                Slog.e(TAG, "Unable to write default apps for backup", e);
21219            }
21220            return null;
21221        }
21222
21223        return dataStream.toByteArray();
21224    }
21225
21226    @Override
21227    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21228        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21229            throw new SecurityException("Only the system may call restorePreferredActivities()");
21230        }
21231
21232        try {
21233            final XmlPullParser parser = Xml.newPullParser();
21234            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21235            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21236                    new BlobXmlRestorer() {
21237                        @Override
21238                        public void apply(XmlPullParser parser, int userId)
21239                                throws XmlPullParserException, IOException {
21240                            synchronized (mPackages) {
21241                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21242                                mSettings.writeLPr();
21243                            }
21244                        }
21245                    } );
21246        } catch (Exception e) {
21247            if (DEBUG_BACKUP) {
21248                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21249            }
21250        }
21251    }
21252
21253    @Override
21254    public byte[] getPermissionGrantBackup(int userId) {
21255        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21256            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21257        }
21258
21259        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21260        try {
21261            final XmlSerializer serializer = new FastXmlSerializer();
21262            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21263            serializer.startDocument(null, true);
21264            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21265
21266            synchronized (mPackages) {
21267                serializeRuntimePermissionGrantsLPr(serializer, userId);
21268            }
21269
21270            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21271            serializer.endDocument();
21272            serializer.flush();
21273        } catch (Exception e) {
21274            if (DEBUG_BACKUP) {
21275                Slog.e(TAG, "Unable to write default apps for backup", e);
21276            }
21277            return null;
21278        }
21279
21280        return dataStream.toByteArray();
21281    }
21282
21283    @Override
21284    public void restorePermissionGrants(byte[] backup, int userId) {
21285        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21286            throw new SecurityException("Only the system may call restorePermissionGrants()");
21287        }
21288
21289        try {
21290            final XmlPullParser parser = Xml.newPullParser();
21291            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21292            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21293                    new BlobXmlRestorer() {
21294                        @Override
21295                        public void apply(XmlPullParser parser, int userId)
21296                                throws XmlPullParserException, IOException {
21297                            synchronized (mPackages) {
21298                                processRestoredPermissionGrantsLPr(parser, userId);
21299                            }
21300                        }
21301                    } );
21302        } catch (Exception e) {
21303            if (DEBUG_BACKUP) {
21304                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21305            }
21306        }
21307    }
21308
21309    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21310            throws IOException {
21311        serializer.startTag(null, TAG_ALL_GRANTS);
21312
21313        final int N = mSettings.mPackages.size();
21314        for (int i = 0; i < N; i++) {
21315            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21316            boolean pkgGrantsKnown = false;
21317
21318            PermissionsState packagePerms = ps.getPermissionsState();
21319
21320            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21321                final int grantFlags = state.getFlags();
21322                // only look at grants that are not system/policy fixed
21323                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21324                    final boolean isGranted = state.isGranted();
21325                    // And only back up the user-twiddled state bits
21326                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21327                        final String packageName = mSettings.mPackages.keyAt(i);
21328                        if (!pkgGrantsKnown) {
21329                            serializer.startTag(null, TAG_GRANT);
21330                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21331                            pkgGrantsKnown = true;
21332                        }
21333
21334                        final boolean userSet =
21335                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21336                        final boolean userFixed =
21337                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21338                        final boolean revoke =
21339                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21340
21341                        serializer.startTag(null, TAG_PERMISSION);
21342                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21343                        if (isGranted) {
21344                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21345                        }
21346                        if (userSet) {
21347                            serializer.attribute(null, ATTR_USER_SET, "true");
21348                        }
21349                        if (userFixed) {
21350                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21351                        }
21352                        if (revoke) {
21353                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21354                        }
21355                        serializer.endTag(null, TAG_PERMISSION);
21356                    }
21357                }
21358            }
21359
21360            if (pkgGrantsKnown) {
21361                serializer.endTag(null, TAG_GRANT);
21362            }
21363        }
21364
21365        serializer.endTag(null, TAG_ALL_GRANTS);
21366    }
21367
21368    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21369            throws XmlPullParserException, IOException {
21370        String pkgName = null;
21371        int outerDepth = parser.getDepth();
21372        int type;
21373        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21374                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21375            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21376                continue;
21377            }
21378
21379            final String tagName = parser.getName();
21380            if (tagName.equals(TAG_GRANT)) {
21381                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21382                if (DEBUG_BACKUP) {
21383                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21384                }
21385            } else if (tagName.equals(TAG_PERMISSION)) {
21386
21387                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21388                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21389
21390                int newFlagSet = 0;
21391                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21392                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21393                }
21394                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21395                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21396                }
21397                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21398                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21399                }
21400                if (DEBUG_BACKUP) {
21401                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21402                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21403                }
21404                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21405                if (ps != null) {
21406                    // Already installed so we apply the grant immediately
21407                    if (DEBUG_BACKUP) {
21408                        Slog.v(TAG, "        + already installed; applying");
21409                    }
21410                    PermissionsState perms = ps.getPermissionsState();
21411                    BasePermission bp = mSettings.mPermissions.get(permName);
21412                    if (bp != null) {
21413                        if (isGranted) {
21414                            perms.grantRuntimePermission(bp, userId);
21415                        }
21416                        if (newFlagSet != 0) {
21417                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21418                        }
21419                    }
21420                } else {
21421                    // Need to wait for post-restore install to apply the grant
21422                    if (DEBUG_BACKUP) {
21423                        Slog.v(TAG, "        - not yet installed; saving for later");
21424                    }
21425                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21426                            isGranted, newFlagSet, userId);
21427                }
21428            } else {
21429                PackageManagerService.reportSettingsProblem(Log.WARN,
21430                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21431                XmlUtils.skipCurrentTag(parser);
21432            }
21433        }
21434
21435        scheduleWriteSettingsLocked();
21436        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21437    }
21438
21439    @Override
21440    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21441            int sourceUserId, int targetUserId, int flags) {
21442        mContext.enforceCallingOrSelfPermission(
21443                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21444        int callingUid = Binder.getCallingUid();
21445        enforceOwnerRights(ownerPackage, callingUid);
21446        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21447        if (intentFilter.countActions() == 0) {
21448            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21449            return;
21450        }
21451        synchronized (mPackages) {
21452            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21453                    ownerPackage, targetUserId, flags);
21454            CrossProfileIntentResolver resolver =
21455                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21456            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21457            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21458            if (existing != null) {
21459                int size = existing.size();
21460                for (int i = 0; i < size; i++) {
21461                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21462                        return;
21463                    }
21464                }
21465            }
21466            resolver.addFilter(newFilter);
21467            scheduleWritePackageRestrictionsLocked(sourceUserId);
21468        }
21469    }
21470
21471    @Override
21472    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21473        mContext.enforceCallingOrSelfPermission(
21474                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21475        final int callingUid = Binder.getCallingUid();
21476        enforceOwnerRights(ownerPackage, callingUid);
21477        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21478        synchronized (mPackages) {
21479            CrossProfileIntentResolver resolver =
21480                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21481            ArraySet<CrossProfileIntentFilter> set =
21482                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21483            for (CrossProfileIntentFilter filter : set) {
21484                if (filter.getOwnerPackage().equals(ownerPackage)) {
21485                    resolver.removeFilter(filter);
21486                }
21487            }
21488            scheduleWritePackageRestrictionsLocked(sourceUserId);
21489        }
21490    }
21491
21492    // Enforcing that callingUid is owning pkg on userId
21493    private void enforceOwnerRights(String pkg, int callingUid) {
21494        // The system owns everything.
21495        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21496            return;
21497        }
21498        final int callingUserId = UserHandle.getUserId(callingUid);
21499        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21500        if (pi == null) {
21501            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21502                    + callingUserId);
21503        }
21504        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21505            throw new SecurityException("Calling uid " + callingUid
21506                    + " does not own package " + pkg);
21507        }
21508    }
21509
21510    @Override
21511    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21512        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21513            return null;
21514        }
21515        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21516    }
21517
21518    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21519        UserManagerService ums = UserManagerService.getInstance();
21520        if (ums != null) {
21521            final UserInfo parent = ums.getProfileParent(userId);
21522            final int launcherUid = (parent != null) ? parent.id : userId;
21523            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21524            if (launcherComponent != null) {
21525                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21526                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21527                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21528                        .setPackage(launcherComponent.getPackageName());
21529                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21530            }
21531        }
21532    }
21533
21534    /**
21535     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21536     * then reports the most likely home activity or null if there are more than one.
21537     */
21538    private ComponentName getDefaultHomeActivity(int userId) {
21539        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21540        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21541        if (cn != null) {
21542            return cn;
21543        }
21544
21545        // Find the launcher with the highest priority and return that component if there are no
21546        // other home activity with the same priority.
21547        int lastPriority = Integer.MIN_VALUE;
21548        ComponentName lastComponent = null;
21549        final int size = allHomeCandidates.size();
21550        for (int i = 0; i < size; i++) {
21551            final ResolveInfo ri = allHomeCandidates.get(i);
21552            if (ri.priority > lastPriority) {
21553                lastComponent = ri.activityInfo.getComponentName();
21554                lastPriority = ri.priority;
21555            } else if (ri.priority == lastPriority) {
21556                // Two components found with same priority.
21557                lastComponent = null;
21558            }
21559        }
21560        return lastComponent;
21561    }
21562
21563    private Intent getHomeIntent() {
21564        Intent intent = new Intent(Intent.ACTION_MAIN);
21565        intent.addCategory(Intent.CATEGORY_HOME);
21566        intent.addCategory(Intent.CATEGORY_DEFAULT);
21567        return intent;
21568    }
21569
21570    private IntentFilter getHomeFilter() {
21571        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21572        filter.addCategory(Intent.CATEGORY_HOME);
21573        filter.addCategory(Intent.CATEGORY_DEFAULT);
21574        return filter;
21575    }
21576
21577    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21578            int userId) {
21579        Intent intent  = getHomeIntent();
21580        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21581                PackageManager.GET_META_DATA, userId);
21582        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21583                true, false, false, userId);
21584
21585        allHomeCandidates.clear();
21586        if (list != null) {
21587            for (ResolveInfo ri : list) {
21588                allHomeCandidates.add(ri);
21589            }
21590        }
21591        return (preferred == null || preferred.activityInfo == null)
21592                ? null
21593                : new ComponentName(preferred.activityInfo.packageName,
21594                        preferred.activityInfo.name);
21595    }
21596
21597    @Override
21598    public void setHomeActivity(ComponentName comp, int userId) {
21599        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21600            return;
21601        }
21602        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21603        getHomeActivitiesAsUser(homeActivities, userId);
21604
21605        boolean found = false;
21606
21607        final int size = homeActivities.size();
21608        final ComponentName[] set = new ComponentName[size];
21609        for (int i = 0; i < size; i++) {
21610            final ResolveInfo candidate = homeActivities.get(i);
21611            final ActivityInfo info = candidate.activityInfo;
21612            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21613            set[i] = activityName;
21614            if (!found && activityName.equals(comp)) {
21615                found = true;
21616            }
21617        }
21618        if (!found) {
21619            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21620                    + userId);
21621        }
21622        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21623                set, comp, userId);
21624    }
21625
21626    private @Nullable String getSetupWizardPackageName() {
21627        final Intent intent = new Intent(Intent.ACTION_MAIN);
21628        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21629
21630        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21631                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21632                        | MATCH_DISABLED_COMPONENTS,
21633                UserHandle.myUserId());
21634        if (matches.size() == 1) {
21635            return matches.get(0).getComponentInfo().packageName;
21636        } else {
21637            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21638                    + ": matches=" + matches);
21639            return null;
21640        }
21641    }
21642
21643    private @Nullable String getStorageManagerPackageName() {
21644        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21645
21646        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21647                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21648                        | MATCH_DISABLED_COMPONENTS,
21649                UserHandle.myUserId());
21650        if (matches.size() == 1) {
21651            return matches.get(0).getComponentInfo().packageName;
21652        } else {
21653            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21654                    + matches.size() + ": matches=" + matches);
21655            return null;
21656        }
21657    }
21658
21659    @Override
21660    public void setApplicationEnabledSetting(String appPackageName,
21661            int newState, int flags, int userId, String callingPackage) {
21662        if (!sUserManager.exists(userId)) return;
21663        if (callingPackage == null) {
21664            callingPackage = Integer.toString(Binder.getCallingUid());
21665        }
21666        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21667    }
21668
21669    @Override
21670    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21672        synchronized (mPackages) {
21673            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21674            if (pkgSetting != null) {
21675                pkgSetting.setUpdateAvailable(updateAvailable);
21676            }
21677        }
21678    }
21679
21680    @Override
21681    public void setComponentEnabledSetting(ComponentName componentName,
21682            int newState, int flags, int userId) {
21683        if (!sUserManager.exists(userId)) return;
21684        setEnabledSetting(componentName.getPackageName(),
21685                componentName.getClassName(), newState, flags, userId, null);
21686    }
21687
21688    private void setEnabledSetting(final String packageName, String className, int newState,
21689            final int flags, int userId, String callingPackage) {
21690        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21691              || newState == COMPONENT_ENABLED_STATE_ENABLED
21692              || newState == COMPONENT_ENABLED_STATE_DISABLED
21693              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21694              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21695            throw new IllegalArgumentException("Invalid new component state: "
21696                    + newState);
21697        }
21698        PackageSetting pkgSetting;
21699        final int callingUid = Binder.getCallingUid();
21700        final int permission;
21701        if (callingUid == Process.SYSTEM_UID) {
21702            permission = PackageManager.PERMISSION_GRANTED;
21703        } else {
21704            permission = mContext.checkCallingOrSelfPermission(
21705                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21706        }
21707        enforceCrossUserPermission(callingUid, userId,
21708                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21709        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21710        boolean sendNow = false;
21711        boolean isApp = (className == null);
21712        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21713        String componentName = isApp ? packageName : className;
21714        int packageUid = -1;
21715        ArrayList<String> components;
21716
21717        // reader
21718        synchronized (mPackages) {
21719            pkgSetting = mSettings.mPackages.get(packageName);
21720            if (pkgSetting == null) {
21721                if (!isCallerInstantApp) {
21722                    if (className == null) {
21723                        throw new IllegalArgumentException("Unknown package: " + packageName);
21724                    }
21725                    throw new IllegalArgumentException(
21726                            "Unknown component: " + packageName + "/" + className);
21727                } else {
21728                    // throw SecurityException to prevent leaking package information
21729                    throw new SecurityException(
21730                            "Attempt to change component state; "
21731                            + "pid=" + Binder.getCallingPid()
21732                            + ", uid=" + callingUid
21733                            + (className == null
21734                                    ? ", package=" + packageName
21735                                    : ", component=" + packageName + "/" + className));
21736                }
21737            }
21738        }
21739
21740        // Limit who can change which apps
21741        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21742            // Don't allow apps that don't have permission to modify other apps
21743            if (!allowedByPermission
21744                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21745                throw new SecurityException(
21746                        "Attempt to change component state; "
21747                        + "pid=" + Binder.getCallingPid()
21748                        + ", uid=" + callingUid
21749                        + (className == null
21750                                ? ", package=" + packageName
21751                                : ", component=" + packageName + "/" + className));
21752            }
21753            // Don't allow changing protected packages.
21754            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21755                throw new SecurityException("Cannot disable a protected package: " + packageName);
21756            }
21757        }
21758
21759        synchronized (mPackages) {
21760            if (callingUid == Process.SHELL_UID
21761                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21762                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21763                // unless it is a test package.
21764                int oldState = pkgSetting.getEnabled(userId);
21765                if (className == null
21766                    &&
21767                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21768                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21769                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21770                    &&
21771                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21772                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21773                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21774                    // ok
21775                } else {
21776                    throw new SecurityException(
21777                            "Shell cannot change component state for " + packageName + "/"
21778                            + className + " to " + newState);
21779                }
21780            }
21781            if (className == null) {
21782                // We're dealing with an application/package level state change
21783                if (pkgSetting.getEnabled(userId) == newState) {
21784                    // Nothing to do
21785                    return;
21786                }
21787                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21788                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21789                    // Don't care about who enables an app.
21790                    callingPackage = null;
21791                }
21792                pkgSetting.setEnabled(newState, userId, callingPackage);
21793                // pkgSetting.pkg.mSetEnabled = newState;
21794            } else {
21795                // We're dealing with a component level state change
21796                // First, verify that this is a valid class name.
21797                PackageParser.Package pkg = pkgSetting.pkg;
21798                if (pkg == null || !pkg.hasComponentClassName(className)) {
21799                    if (pkg != null &&
21800                            pkg.applicationInfo.targetSdkVersion >=
21801                                    Build.VERSION_CODES.JELLY_BEAN) {
21802                        throw new IllegalArgumentException("Component class " + className
21803                                + " does not exist in " + packageName);
21804                    } else {
21805                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21806                                + className + " does not exist in " + packageName);
21807                    }
21808                }
21809                switch (newState) {
21810                case COMPONENT_ENABLED_STATE_ENABLED:
21811                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21812                        return;
21813                    }
21814                    break;
21815                case COMPONENT_ENABLED_STATE_DISABLED:
21816                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21817                        return;
21818                    }
21819                    break;
21820                case COMPONENT_ENABLED_STATE_DEFAULT:
21821                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21822                        return;
21823                    }
21824                    break;
21825                default:
21826                    Slog.e(TAG, "Invalid new component state: " + newState);
21827                    return;
21828                }
21829            }
21830            scheduleWritePackageRestrictionsLocked(userId);
21831            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21832            final long callingId = Binder.clearCallingIdentity();
21833            try {
21834                updateInstantAppInstallerLocked(packageName);
21835            } finally {
21836                Binder.restoreCallingIdentity(callingId);
21837            }
21838            components = mPendingBroadcasts.get(userId, packageName);
21839            final boolean newPackage = components == null;
21840            if (newPackage) {
21841                components = new ArrayList<String>();
21842            }
21843            if (!components.contains(componentName)) {
21844                components.add(componentName);
21845            }
21846            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21847                sendNow = true;
21848                // Purge entry from pending broadcast list if another one exists already
21849                // since we are sending one right away.
21850                mPendingBroadcasts.remove(userId, packageName);
21851            } else {
21852                if (newPackage) {
21853                    mPendingBroadcasts.put(userId, packageName, components);
21854                }
21855                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21856                    // Schedule a message
21857                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21858                }
21859            }
21860        }
21861
21862        long callingId = Binder.clearCallingIdentity();
21863        try {
21864            if (sendNow) {
21865                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21866                sendPackageChangedBroadcast(packageName,
21867                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21868            }
21869        } finally {
21870            Binder.restoreCallingIdentity(callingId);
21871        }
21872    }
21873
21874    @Override
21875    public void flushPackageRestrictionsAsUser(int userId) {
21876        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21877            return;
21878        }
21879        if (!sUserManager.exists(userId)) {
21880            return;
21881        }
21882        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21883                false /* checkShell */, "flushPackageRestrictions");
21884        synchronized (mPackages) {
21885            mSettings.writePackageRestrictionsLPr(userId);
21886            mDirtyUsers.remove(userId);
21887            if (mDirtyUsers.isEmpty()) {
21888                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21889            }
21890        }
21891    }
21892
21893    private void sendPackageChangedBroadcast(String packageName,
21894            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21895        if (DEBUG_INSTALL)
21896            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21897                    + componentNames);
21898        Bundle extras = new Bundle(4);
21899        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21900        String nameList[] = new String[componentNames.size()];
21901        componentNames.toArray(nameList);
21902        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21903        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21904        extras.putInt(Intent.EXTRA_UID, packageUid);
21905        // If this is not reporting a change of the overall package, then only send it
21906        // to registered receivers.  We don't want to launch a swath of apps for every
21907        // little component state change.
21908        final int flags = !componentNames.contains(packageName)
21909                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21910        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21911                new int[] {UserHandle.getUserId(packageUid)});
21912    }
21913
21914    @Override
21915    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21916        if (!sUserManager.exists(userId)) return;
21917        final int callingUid = Binder.getCallingUid();
21918        if (getInstantAppPackageName(callingUid) != null) {
21919            return;
21920        }
21921        final int permission = mContext.checkCallingOrSelfPermission(
21922                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21923        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21924        enforceCrossUserPermission(callingUid, userId,
21925                true /* requireFullPermission */, true /* checkShell */, "stop package");
21926        // writer
21927        synchronized (mPackages) {
21928            final PackageSetting ps = mSettings.mPackages.get(packageName);
21929            if (!filterAppAccessLPr(ps, callingUid, userId)
21930                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21931                            allowedByPermission, callingUid, userId)) {
21932                scheduleWritePackageRestrictionsLocked(userId);
21933            }
21934        }
21935    }
21936
21937    @Override
21938    public String getInstallerPackageName(String packageName) {
21939        final int callingUid = Binder.getCallingUid();
21940        if (getInstantAppPackageName(callingUid) != null) {
21941            return null;
21942        }
21943        // reader
21944        synchronized (mPackages) {
21945            final PackageSetting ps = mSettings.mPackages.get(packageName);
21946            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21947                return null;
21948            }
21949            return mSettings.getInstallerPackageNameLPr(packageName);
21950        }
21951    }
21952
21953    public boolean isOrphaned(String packageName) {
21954        // reader
21955        synchronized (mPackages) {
21956            return mSettings.isOrphaned(packageName);
21957        }
21958    }
21959
21960    @Override
21961    public int getApplicationEnabledSetting(String packageName, int userId) {
21962        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21963        int callingUid = Binder.getCallingUid();
21964        enforceCrossUserPermission(callingUid, userId,
21965                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21966        // reader
21967        synchronized (mPackages) {
21968            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21969                return COMPONENT_ENABLED_STATE_DISABLED;
21970            }
21971            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21972        }
21973    }
21974
21975    @Override
21976    public int getComponentEnabledSetting(ComponentName component, int userId) {
21977        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21978        int callingUid = Binder.getCallingUid();
21979        enforceCrossUserPermission(callingUid, userId,
21980                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21981        synchronized (mPackages) {
21982            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21983                    component, TYPE_UNKNOWN, userId)) {
21984                return COMPONENT_ENABLED_STATE_DISABLED;
21985            }
21986            return mSettings.getComponentEnabledSettingLPr(component, userId);
21987        }
21988    }
21989
21990    @Override
21991    public void enterSafeMode() {
21992        enforceSystemOrRoot("Only the system can request entering safe mode");
21993
21994        if (!mSystemReady) {
21995            mSafeMode = true;
21996        }
21997    }
21998
21999    @Override
22000    public void systemReady() {
22001        enforceSystemOrRoot("Only the system can claim the system is ready");
22002
22003        mSystemReady = true;
22004        final ContentResolver resolver = mContext.getContentResolver();
22005        ContentObserver co = new ContentObserver(mHandler) {
22006            @Override
22007            public void onChange(boolean selfChange) {
22008                mEphemeralAppsDisabled =
22009                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22010                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22011            }
22012        };
22013        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22014                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22015                false, co, UserHandle.USER_SYSTEM);
22016        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22017                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22018        co.onChange(true);
22019
22020        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22021        // disabled after already being started.
22022        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22023                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22024
22025        // Read the compatibilty setting when the system is ready.
22026        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22027                mContext.getContentResolver(),
22028                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22029        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22030        if (DEBUG_SETTINGS) {
22031            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22032        }
22033
22034        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22035
22036        synchronized (mPackages) {
22037            // Verify that all of the preferred activity components actually
22038            // exist.  It is possible for applications to be updated and at
22039            // that point remove a previously declared activity component that
22040            // had been set as a preferred activity.  We try to clean this up
22041            // the next time we encounter that preferred activity, but it is
22042            // possible for the user flow to never be able to return to that
22043            // situation so here we do a sanity check to make sure we haven't
22044            // left any junk around.
22045            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22046            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22047                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22048                removed.clear();
22049                for (PreferredActivity pa : pir.filterSet()) {
22050                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22051                        removed.add(pa);
22052                    }
22053                }
22054                if (removed.size() > 0) {
22055                    for (int r=0; r<removed.size(); r++) {
22056                        PreferredActivity pa = removed.get(r);
22057                        Slog.w(TAG, "Removing dangling preferred activity: "
22058                                + pa.mPref.mComponent);
22059                        pir.removeFilter(pa);
22060                    }
22061                    mSettings.writePackageRestrictionsLPr(
22062                            mSettings.mPreferredActivities.keyAt(i));
22063                }
22064            }
22065
22066            for (int userId : UserManagerService.getInstance().getUserIds()) {
22067                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22068                    grantPermissionsUserIds = ArrayUtils.appendInt(
22069                            grantPermissionsUserIds, userId);
22070                }
22071            }
22072        }
22073        sUserManager.systemReady();
22074
22075        // If we upgraded grant all default permissions before kicking off.
22076        for (int userId : grantPermissionsUserIds) {
22077            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22078        }
22079
22080        // If we did not grant default permissions, we preload from this the
22081        // default permission exceptions lazily to ensure we don't hit the
22082        // disk on a new user creation.
22083        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22084            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22085        }
22086
22087        // Kick off any messages waiting for system ready
22088        if (mPostSystemReadyMessages != null) {
22089            for (Message msg : mPostSystemReadyMessages) {
22090                msg.sendToTarget();
22091            }
22092            mPostSystemReadyMessages = null;
22093        }
22094
22095        // Watch for external volumes that come and go over time
22096        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22097        storage.registerListener(mStorageListener);
22098
22099        mInstallerService.systemReady();
22100        mPackageDexOptimizer.systemReady();
22101
22102        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22103                StorageManagerInternal.class);
22104        StorageManagerInternal.addExternalStoragePolicy(
22105                new StorageManagerInternal.ExternalStorageMountPolicy() {
22106            @Override
22107            public int getMountMode(int uid, String packageName) {
22108                if (Process.isIsolated(uid)) {
22109                    return Zygote.MOUNT_EXTERNAL_NONE;
22110                }
22111                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22112                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22113                }
22114                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22115                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22116                }
22117                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22118                    return Zygote.MOUNT_EXTERNAL_READ;
22119                }
22120                return Zygote.MOUNT_EXTERNAL_WRITE;
22121            }
22122
22123            @Override
22124            public boolean hasExternalStorage(int uid, String packageName) {
22125                return true;
22126            }
22127        });
22128
22129        // Now that we're mostly running, clean up stale users and apps
22130        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22131        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22132
22133        if (mPrivappPermissionsViolations != null) {
22134            Slog.wtf(TAG,"Signature|privileged permissions not in "
22135                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22136            mPrivappPermissionsViolations = null;
22137        }
22138    }
22139
22140    public void waitForAppDataPrepared() {
22141        if (mPrepareAppDataFuture == null) {
22142            return;
22143        }
22144        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22145        mPrepareAppDataFuture = null;
22146    }
22147
22148    @Override
22149    public boolean isSafeMode() {
22150        // allow instant applications
22151        return mSafeMode;
22152    }
22153
22154    @Override
22155    public boolean hasSystemUidErrors() {
22156        // allow instant applications
22157        return mHasSystemUidErrors;
22158    }
22159
22160    static String arrayToString(int[] array) {
22161        StringBuffer buf = new StringBuffer(128);
22162        buf.append('[');
22163        if (array != null) {
22164            for (int i=0; i<array.length; i++) {
22165                if (i > 0) buf.append(", ");
22166                buf.append(array[i]);
22167            }
22168        }
22169        buf.append(']');
22170        return buf.toString();
22171    }
22172
22173    static class DumpState {
22174        public static final int DUMP_LIBS = 1 << 0;
22175        public static final int DUMP_FEATURES = 1 << 1;
22176        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22177        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22178        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22179        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22180        public static final int DUMP_PERMISSIONS = 1 << 6;
22181        public static final int DUMP_PACKAGES = 1 << 7;
22182        public static final int DUMP_SHARED_USERS = 1 << 8;
22183        public static final int DUMP_MESSAGES = 1 << 9;
22184        public static final int DUMP_PROVIDERS = 1 << 10;
22185        public static final int DUMP_VERIFIERS = 1 << 11;
22186        public static final int DUMP_PREFERRED = 1 << 12;
22187        public static final int DUMP_PREFERRED_XML = 1 << 13;
22188        public static final int DUMP_KEYSETS = 1 << 14;
22189        public static final int DUMP_VERSION = 1 << 15;
22190        public static final int DUMP_INSTALLS = 1 << 16;
22191        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22192        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22193        public static final int DUMP_FROZEN = 1 << 19;
22194        public static final int DUMP_DEXOPT = 1 << 20;
22195        public static final int DUMP_COMPILER_STATS = 1 << 21;
22196        public static final int DUMP_CHANGES = 1 << 22;
22197        public static final int DUMP_VOLUMES = 1 << 23;
22198
22199        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22200
22201        private int mTypes;
22202
22203        private int mOptions;
22204
22205        private boolean mTitlePrinted;
22206
22207        private SharedUserSetting mSharedUser;
22208
22209        public boolean isDumping(int type) {
22210            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22211                return true;
22212            }
22213
22214            return (mTypes & type) != 0;
22215        }
22216
22217        public void setDump(int type) {
22218            mTypes |= type;
22219        }
22220
22221        public boolean isOptionEnabled(int option) {
22222            return (mOptions & option) != 0;
22223        }
22224
22225        public void setOptionEnabled(int option) {
22226            mOptions |= option;
22227        }
22228
22229        public boolean onTitlePrinted() {
22230            final boolean printed = mTitlePrinted;
22231            mTitlePrinted = true;
22232            return printed;
22233        }
22234
22235        public boolean getTitlePrinted() {
22236            return mTitlePrinted;
22237        }
22238
22239        public void setTitlePrinted(boolean enabled) {
22240            mTitlePrinted = enabled;
22241        }
22242
22243        public SharedUserSetting getSharedUser() {
22244            return mSharedUser;
22245        }
22246
22247        public void setSharedUser(SharedUserSetting user) {
22248            mSharedUser = user;
22249        }
22250    }
22251
22252    @Override
22253    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22254            FileDescriptor err, String[] args, ShellCallback callback,
22255            ResultReceiver resultReceiver) {
22256        (new PackageManagerShellCommand(this)).exec(
22257                this, in, out, err, args, callback, resultReceiver);
22258    }
22259
22260    @Override
22261    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22262        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22263
22264        DumpState dumpState = new DumpState();
22265        boolean fullPreferred = false;
22266        boolean checkin = false;
22267
22268        String packageName = null;
22269        ArraySet<String> permissionNames = null;
22270
22271        int opti = 0;
22272        while (opti < args.length) {
22273            String opt = args[opti];
22274            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22275                break;
22276            }
22277            opti++;
22278
22279            if ("-a".equals(opt)) {
22280                // Right now we only know how to print all.
22281            } else if ("-h".equals(opt)) {
22282                pw.println("Package manager dump options:");
22283                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22284                pw.println("    --checkin: dump for a checkin");
22285                pw.println("    -f: print details of intent filters");
22286                pw.println("    -h: print this help");
22287                pw.println("  cmd may be one of:");
22288                pw.println("    l[ibraries]: list known shared libraries");
22289                pw.println("    f[eatures]: list device features");
22290                pw.println("    k[eysets]: print known keysets");
22291                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22292                pw.println("    perm[issions]: dump permissions");
22293                pw.println("    permission [name ...]: dump declaration and use of given permission");
22294                pw.println("    pref[erred]: print preferred package settings");
22295                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22296                pw.println("    prov[iders]: dump content providers");
22297                pw.println("    p[ackages]: dump installed packages");
22298                pw.println("    s[hared-users]: dump shared user IDs");
22299                pw.println("    m[essages]: print collected runtime messages");
22300                pw.println("    v[erifiers]: print package verifier info");
22301                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22302                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22303                pw.println("    version: print database version info");
22304                pw.println("    write: write current settings now");
22305                pw.println("    installs: details about install sessions");
22306                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22307                pw.println("    dexopt: dump dexopt state");
22308                pw.println("    compiler-stats: dump compiler statistics");
22309                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22310                pw.println("    <package.name>: info about given package");
22311                return;
22312            } else if ("--checkin".equals(opt)) {
22313                checkin = true;
22314            } else if ("-f".equals(opt)) {
22315                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22316            } else if ("--proto".equals(opt)) {
22317                dumpProto(fd);
22318                return;
22319            } else {
22320                pw.println("Unknown argument: " + opt + "; use -h for help");
22321            }
22322        }
22323
22324        // Is the caller requesting to dump a particular piece of data?
22325        if (opti < args.length) {
22326            String cmd = args[opti];
22327            opti++;
22328            // Is this a package name?
22329            if ("android".equals(cmd) || cmd.contains(".")) {
22330                packageName = cmd;
22331                // When dumping a single package, we always dump all of its
22332                // filter information since the amount of data will be reasonable.
22333                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22334            } else if ("check-permission".equals(cmd)) {
22335                if (opti >= args.length) {
22336                    pw.println("Error: check-permission missing permission argument");
22337                    return;
22338                }
22339                String perm = args[opti];
22340                opti++;
22341                if (opti >= args.length) {
22342                    pw.println("Error: check-permission missing package argument");
22343                    return;
22344                }
22345
22346                String pkg = args[opti];
22347                opti++;
22348                int user = UserHandle.getUserId(Binder.getCallingUid());
22349                if (opti < args.length) {
22350                    try {
22351                        user = Integer.parseInt(args[opti]);
22352                    } catch (NumberFormatException e) {
22353                        pw.println("Error: check-permission user argument is not a number: "
22354                                + args[opti]);
22355                        return;
22356                    }
22357                }
22358
22359                // Normalize package name to handle renamed packages and static libs
22360                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22361
22362                pw.println(checkPermission(perm, pkg, user));
22363                return;
22364            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22365                dumpState.setDump(DumpState.DUMP_LIBS);
22366            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22367                dumpState.setDump(DumpState.DUMP_FEATURES);
22368            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22369                if (opti >= args.length) {
22370                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22371                            | DumpState.DUMP_SERVICE_RESOLVERS
22372                            | DumpState.DUMP_RECEIVER_RESOLVERS
22373                            | DumpState.DUMP_CONTENT_RESOLVERS);
22374                } else {
22375                    while (opti < args.length) {
22376                        String name = args[opti];
22377                        if ("a".equals(name) || "activity".equals(name)) {
22378                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22379                        } else if ("s".equals(name) || "service".equals(name)) {
22380                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22381                        } else if ("r".equals(name) || "receiver".equals(name)) {
22382                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22383                        } else if ("c".equals(name) || "content".equals(name)) {
22384                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22385                        } else {
22386                            pw.println("Error: unknown resolver table type: " + name);
22387                            return;
22388                        }
22389                        opti++;
22390                    }
22391                }
22392            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22393                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22394            } else if ("permission".equals(cmd)) {
22395                if (opti >= args.length) {
22396                    pw.println("Error: permission requires permission name");
22397                    return;
22398                }
22399                permissionNames = new ArraySet<>();
22400                while (opti < args.length) {
22401                    permissionNames.add(args[opti]);
22402                    opti++;
22403                }
22404                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22405                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22406            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22407                dumpState.setDump(DumpState.DUMP_PREFERRED);
22408            } else if ("preferred-xml".equals(cmd)) {
22409                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22410                if (opti < args.length && "--full".equals(args[opti])) {
22411                    fullPreferred = true;
22412                    opti++;
22413                }
22414            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22415                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22416            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22417                dumpState.setDump(DumpState.DUMP_PACKAGES);
22418            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22419                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22420            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22421                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22422            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22423                dumpState.setDump(DumpState.DUMP_MESSAGES);
22424            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22425                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22426            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22427                    || "intent-filter-verifiers".equals(cmd)) {
22428                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22429            } else if ("version".equals(cmd)) {
22430                dumpState.setDump(DumpState.DUMP_VERSION);
22431            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22432                dumpState.setDump(DumpState.DUMP_KEYSETS);
22433            } else if ("installs".equals(cmd)) {
22434                dumpState.setDump(DumpState.DUMP_INSTALLS);
22435            } else if ("frozen".equals(cmd)) {
22436                dumpState.setDump(DumpState.DUMP_FROZEN);
22437            } else if ("volumes".equals(cmd)) {
22438                dumpState.setDump(DumpState.DUMP_VOLUMES);
22439            } else if ("dexopt".equals(cmd)) {
22440                dumpState.setDump(DumpState.DUMP_DEXOPT);
22441            } else if ("compiler-stats".equals(cmd)) {
22442                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22443            } else if ("changes".equals(cmd)) {
22444                dumpState.setDump(DumpState.DUMP_CHANGES);
22445            } else if ("write".equals(cmd)) {
22446                synchronized (mPackages) {
22447                    mSettings.writeLPr();
22448                    pw.println("Settings written.");
22449                    return;
22450                }
22451            }
22452        }
22453
22454        if (checkin) {
22455            pw.println("vers,1");
22456        }
22457
22458        // reader
22459        synchronized (mPackages) {
22460            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22461                if (!checkin) {
22462                    if (dumpState.onTitlePrinted())
22463                        pw.println();
22464                    pw.println("Database versions:");
22465                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22466                }
22467            }
22468
22469            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22470                if (!checkin) {
22471                    if (dumpState.onTitlePrinted())
22472                        pw.println();
22473                    pw.println("Verifiers:");
22474                    pw.print("  Required: ");
22475                    pw.print(mRequiredVerifierPackage);
22476                    pw.print(" (uid=");
22477                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22478                            UserHandle.USER_SYSTEM));
22479                    pw.println(")");
22480                } else if (mRequiredVerifierPackage != null) {
22481                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22482                    pw.print(",");
22483                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22484                            UserHandle.USER_SYSTEM));
22485                }
22486            }
22487
22488            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22489                    packageName == null) {
22490                if (mIntentFilterVerifierComponent != null) {
22491                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22492                    if (!checkin) {
22493                        if (dumpState.onTitlePrinted())
22494                            pw.println();
22495                        pw.println("Intent Filter Verifier:");
22496                        pw.print("  Using: ");
22497                        pw.print(verifierPackageName);
22498                        pw.print(" (uid=");
22499                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22500                                UserHandle.USER_SYSTEM));
22501                        pw.println(")");
22502                    } else if (verifierPackageName != null) {
22503                        pw.print("ifv,"); pw.print(verifierPackageName);
22504                        pw.print(",");
22505                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22506                                UserHandle.USER_SYSTEM));
22507                    }
22508                } else {
22509                    pw.println();
22510                    pw.println("No Intent Filter Verifier available!");
22511                }
22512            }
22513
22514            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22515                boolean printedHeader = false;
22516                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22517                while (it.hasNext()) {
22518                    String libName = it.next();
22519                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22520                    if (versionedLib == null) {
22521                        continue;
22522                    }
22523                    final int versionCount = versionedLib.size();
22524                    for (int i = 0; i < versionCount; i++) {
22525                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22526                        if (!checkin) {
22527                            if (!printedHeader) {
22528                                if (dumpState.onTitlePrinted())
22529                                    pw.println();
22530                                pw.println("Libraries:");
22531                                printedHeader = true;
22532                            }
22533                            pw.print("  ");
22534                        } else {
22535                            pw.print("lib,");
22536                        }
22537                        pw.print(libEntry.info.getName());
22538                        if (libEntry.info.isStatic()) {
22539                            pw.print(" version=" + libEntry.info.getVersion());
22540                        }
22541                        if (!checkin) {
22542                            pw.print(" -> ");
22543                        }
22544                        if (libEntry.path != null) {
22545                            pw.print(" (jar) ");
22546                            pw.print(libEntry.path);
22547                        } else {
22548                            pw.print(" (apk) ");
22549                            pw.print(libEntry.apk);
22550                        }
22551                        pw.println();
22552                    }
22553                }
22554            }
22555
22556            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22557                if (dumpState.onTitlePrinted())
22558                    pw.println();
22559                if (!checkin) {
22560                    pw.println("Features:");
22561                }
22562
22563                synchronized (mAvailableFeatures) {
22564                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22565                        if (checkin) {
22566                            pw.print("feat,");
22567                            pw.print(feat.name);
22568                            pw.print(",");
22569                            pw.println(feat.version);
22570                        } else {
22571                            pw.print("  ");
22572                            pw.print(feat.name);
22573                            if (feat.version > 0) {
22574                                pw.print(" version=");
22575                                pw.print(feat.version);
22576                            }
22577                            pw.println();
22578                        }
22579                    }
22580                }
22581            }
22582
22583            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22584                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22585                        : "Activity Resolver Table:", "  ", packageName,
22586                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22587                    dumpState.setTitlePrinted(true);
22588                }
22589            }
22590            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22591                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22592                        : "Receiver Resolver Table:", "  ", packageName,
22593                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22594                    dumpState.setTitlePrinted(true);
22595                }
22596            }
22597            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22598                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22599                        : "Service Resolver Table:", "  ", packageName,
22600                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22601                    dumpState.setTitlePrinted(true);
22602                }
22603            }
22604            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22605                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22606                        : "Provider Resolver Table:", "  ", packageName,
22607                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22608                    dumpState.setTitlePrinted(true);
22609                }
22610            }
22611
22612            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22613                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22614                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22615                    int user = mSettings.mPreferredActivities.keyAt(i);
22616                    if (pir.dump(pw,
22617                            dumpState.getTitlePrinted()
22618                                ? "\nPreferred Activities User " + user + ":"
22619                                : "Preferred Activities User " + user + ":", "  ",
22620                            packageName, true, false)) {
22621                        dumpState.setTitlePrinted(true);
22622                    }
22623                }
22624            }
22625
22626            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22627                pw.flush();
22628                FileOutputStream fout = new FileOutputStream(fd);
22629                BufferedOutputStream str = new BufferedOutputStream(fout);
22630                XmlSerializer serializer = new FastXmlSerializer();
22631                try {
22632                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22633                    serializer.startDocument(null, true);
22634                    serializer.setFeature(
22635                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22636                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22637                    serializer.endDocument();
22638                    serializer.flush();
22639                } catch (IllegalArgumentException e) {
22640                    pw.println("Failed writing: " + e);
22641                } catch (IllegalStateException e) {
22642                    pw.println("Failed writing: " + e);
22643                } catch (IOException e) {
22644                    pw.println("Failed writing: " + e);
22645                }
22646            }
22647
22648            if (!checkin
22649                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22650                    && packageName == null) {
22651                pw.println();
22652                int count = mSettings.mPackages.size();
22653                if (count == 0) {
22654                    pw.println("No applications!");
22655                    pw.println();
22656                } else {
22657                    final String prefix = "  ";
22658                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22659                    if (allPackageSettings.size() == 0) {
22660                        pw.println("No domain preferred apps!");
22661                        pw.println();
22662                    } else {
22663                        pw.println("App verification status:");
22664                        pw.println();
22665                        count = 0;
22666                        for (PackageSetting ps : allPackageSettings) {
22667                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22668                            if (ivi == null || ivi.getPackageName() == null) continue;
22669                            pw.println(prefix + "Package: " + ivi.getPackageName());
22670                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22671                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22672                            pw.println();
22673                            count++;
22674                        }
22675                        if (count == 0) {
22676                            pw.println(prefix + "No app verification established.");
22677                            pw.println();
22678                        }
22679                        for (int userId : sUserManager.getUserIds()) {
22680                            pw.println("App linkages for user " + userId + ":");
22681                            pw.println();
22682                            count = 0;
22683                            for (PackageSetting ps : allPackageSettings) {
22684                                final long status = ps.getDomainVerificationStatusForUser(userId);
22685                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22686                                        && !DEBUG_DOMAIN_VERIFICATION) {
22687                                    continue;
22688                                }
22689                                pw.println(prefix + "Package: " + ps.name);
22690                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22691                                String statusStr = IntentFilterVerificationInfo.
22692                                        getStatusStringFromValue(status);
22693                                pw.println(prefix + "Status:  " + statusStr);
22694                                pw.println();
22695                                count++;
22696                            }
22697                            if (count == 0) {
22698                                pw.println(prefix + "No configured app linkages.");
22699                                pw.println();
22700                            }
22701                        }
22702                    }
22703                }
22704            }
22705
22706            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22707                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22708                if (packageName == null && permissionNames == null) {
22709                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22710                        if (iperm == 0) {
22711                            if (dumpState.onTitlePrinted())
22712                                pw.println();
22713                            pw.println("AppOp Permissions:");
22714                        }
22715                        pw.print("  AppOp Permission ");
22716                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22717                        pw.println(":");
22718                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22719                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22720                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22721                        }
22722                    }
22723                }
22724            }
22725
22726            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22727                boolean printedSomething = false;
22728                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22729                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22730                        continue;
22731                    }
22732                    if (!printedSomething) {
22733                        if (dumpState.onTitlePrinted())
22734                            pw.println();
22735                        pw.println("Registered ContentProviders:");
22736                        printedSomething = true;
22737                    }
22738                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22739                    pw.print("    "); pw.println(p.toString());
22740                }
22741                printedSomething = false;
22742                for (Map.Entry<String, PackageParser.Provider> entry :
22743                        mProvidersByAuthority.entrySet()) {
22744                    PackageParser.Provider p = entry.getValue();
22745                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22746                        continue;
22747                    }
22748                    if (!printedSomething) {
22749                        if (dumpState.onTitlePrinted())
22750                            pw.println();
22751                        pw.println("ContentProvider Authorities:");
22752                        printedSomething = true;
22753                    }
22754                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22755                    pw.print("    "); pw.println(p.toString());
22756                    if (p.info != null && p.info.applicationInfo != null) {
22757                        final String appInfo = p.info.applicationInfo.toString();
22758                        pw.print("      applicationInfo="); pw.println(appInfo);
22759                    }
22760                }
22761            }
22762
22763            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22764                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22765            }
22766
22767            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22768                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22769            }
22770
22771            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22772                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22773            }
22774
22775            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22776                if (dumpState.onTitlePrinted()) pw.println();
22777                pw.println("Package Changes:");
22778                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22779                final int K = mChangedPackages.size();
22780                for (int i = 0; i < K; i++) {
22781                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22782                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22783                    final int N = changes.size();
22784                    if (N == 0) {
22785                        pw.print("    "); pw.println("No packages changed");
22786                    } else {
22787                        for (int j = 0; j < N; j++) {
22788                            final String pkgName = changes.valueAt(j);
22789                            final int sequenceNumber = changes.keyAt(j);
22790                            pw.print("    ");
22791                            pw.print("seq=");
22792                            pw.print(sequenceNumber);
22793                            pw.print(", package=");
22794                            pw.println(pkgName);
22795                        }
22796                    }
22797                }
22798            }
22799
22800            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22801                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22802            }
22803
22804            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22805                // XXX should handle packageName != null by dumping only install data that
22806                // the given package is involved with.
22807                if (dumpState.onTitlePrinted()) pw.println();
22808
22809                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22810                ipw.println();
22811                ipw.println("Frozen packages:");
22812                ipw.increaseIndent();
22813                if (mFrozenPackages.size() == 0) {
22814                    ipw.println("(none)");
22815                } else {
22816                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22817                        ipw.println(mFrozenPackages.valueAt(i));
22818                    }
22819                }
22820                ipw.decreaseIndent();
22821            }
22822
22823            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22824                if (dumpState.onTitlePrinted()) pw.println();
22825
22826                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22827                ipw.println();
22828                ipw.println("Loaded volumes:");
22829                ipw.increaseIndent();
22830                if (mLoadedVolumes.size() == 0) {
22831                    ipw.println("(none)");
22832                } else {
22833                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22834                        ipw.println(mLoadedVolumes.valueAt(i));
22835                    }
22836                }
22837                ipw.decreaseIndent();
22838            }
22839
22840            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22841                if (dumpState.onTitlePrinted()) pw.println();
22842                dumpDexoptStateLPr(pw, packageName);
22843            }
22844
22845            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22846                if (dumpState.onTitlePrinted()) pw.println();
22847                dumpCompilerStatsLPr(pw, packageName);
22848            }
22849
22850            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22851                if (dumpState.onTitlePrinted()) pw.println();
22852                mSettings.dumpReadMessagesLPr(pw, dumpState);
22853
22854                pw.println();
22855                pw.println("Package warning messages:");
22856                BufferedReader in = null;
22857                String line = null;
22858                try {
22859                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22860                    while ((line = in.readLine()) != null) {
22861                        if (line.contains("ignored: updated version")) continue;
22862                        pw.println(line);
22863                    }
22864                } catch (IOException ignored) {
22865                } finally {
22866                    IoUtils.closeQuietly(in);
22867                }
22868            }
22869
22870            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22871                BufferedReader in = null;
22872                String line = null;
22873                try {
22874                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22875                    while ((line = in.readLine()) != null) {
22876                        if (line.contains("ignored: updated version")) continue;
22877                        pw.print("msg,");
22878                        pw.println(line);
22879                    }
22880                } catch (IOException ignored) {
22881                } finally {
22882                    IoUtils.closeQuietly(in);
22883                }
22884            }
22885        }
22886
22887        // PackageInstaller should be called outside of mPackages lock
22888        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22889            // XXX should handle packageName != null by dumping only install data that
22890            // the given package is involved with.
22891            if (dumpState.onTitlePrinted()) pw.println();
22892            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22893        }
22894    }
22895
22896    private void dumpProto(FileDescriptor fd) {
22897        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22898
22899        synchronized (mPackages) {
22900            final long requiredVerifierPackageToken =
22901                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22902            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22903            proto.write(
22904                    PackageServiceDumpProto.PackageShortProto.UID,
22905                    getPackageUid(
22906                            mRequiredVerifierPackage,
22907                            MATCH_DEBUG_TRIAGED_MISSING,
22908                            UserHandle.USER_SYSTEM));
22909            proto.end(requiredVerifierPackageToken);
22910
22911            if (mIntentFilterVerifierComponent != null) {
22912                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22913                final long verifierPackageToken =
22914                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22915                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22916                proto.write(
22917                        PackageServiceDumpProto.PackageShortProto.UID,
22918                        getPackageUid(
22919                                verifierPackageName,
22920                                MATCH_DEBUG_TRIAGED_MISSING,
22921                                UserHandle.USER_SYSTEM));
22922                proto.end(verifierPackageToken);
22923            }
22924
22925            dumpSharedLibrariesProto(proto);
22926            dumpFeaturesProto(proto);
22927            mSettings.dumpPackagesProto(proto);
22928            mSettings.dumpSharedUsersProto(proto);
22929            dumpMessagesProto(proto);
22930        }
22931        proto.flush();
22932    }
22933
22934    private void dumpMessagesProto(ProtoOutputStream proto) {
22935        BufferedReader in = null;
22936        String line = null;
22937        try {
22938            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22939            while ((line = in.readLine()) != null) {
22940                if (line.contains("ignored: updated version")) continue;
22941                proto.write(PackageServiceDumpProto.MESSAGES, line);
22942            }
22943        } catch (IOException ignored) {
22944        } finally {
22945            IoUtils.closeQuietly(in);
22946        }
22947    }
22948
22949    private void dumpFeaturesProto(ProtoOutputStream proto) {
22950        synchronized (mAvailableFeatures) {
22951            final int count = mAvailableFeatures.size();
22952            for (int i = 0; i < count; i++) {
22953                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22954                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22955                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22956                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22957                proto.end(featureToken);
22958            }
22959        }
22960    }
22961
22962    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22963        final int count = mSharedLibraries.size();
22964        for (int i = 0; i < count; i++) {
22965            final String libName = mSharedLibraries.keyAt(i);
22966            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22967            if (versionedLib == null) {
22968                continue;
22969            }
22970            final int versionCount = versionedLib.size();
22971            for (int j = 0; j < versionCount; j++) {
22972                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22973                final long sharedLibraryToken =
22974                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22975                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22976                final boolean isJar = (libEntry.path != null);
22977                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22978                if (isJar) {
22979                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22980                } else {
22981                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22982                }
22983                proto.end(sharedLibraryToken);
22984            }
22985        }
22986    }
22987
22988    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22989        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22990        ipw.println();
22991        ipw.println("Dexopt state:");
22992        ipw.increaseIndent();
22993        Collection<PackageParser.Package> packages = null;
22994        if (packageName != null) {
22995            PackageParser.Package targetPackage = mPackages.get(packageName);
22996            if (targetPackage != null) {
22997                packages = Collections.singletonList(targetPackage);
22998            } else {
22999                ipw.println("Unable to find package: " + packageName);
23000                return;
23001            }
23002        } else {
23003            packages = mPackages.values();
23004        }
23005
23006        for (PackageParser.Package pkg : packages) {
23007            ipw.println("[" + pkg.packageName + "]");
23008            ipw.increaseIndent();
23009            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23010                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23011            ipw.decreaseIndent();
23012        }
23013    }
23014
23015    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23016        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23017        ipw.println();
23018        ipw.println("Compiler stats:");
23019        ipw.increaseIndent();
23020        Collection<PackageParser.Package> packages = null;
23021        if (packageName != null) {
23022            PackageParser.Package targetPackage = mPackages.get(packageName);
23023            if (targetPackage != null) {
23024                packages = Collections.singletonList(targetPackage);
23025            } else {
23026                ipw.println("Unable to find package: " + packageName);
23027                return;
23028            }
23029        } else {
23030            packages = mPackages.values();
23031        }
23032
23033        for (PackageParser.Package pkg : packages) {
23034            ipw.println("[" + pkg.packageName + "]");
23035            ipw.increaseIndent();
23036
23037            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23038            if (stats == null) {
23039                ipw.println("(No recorded stats)");
23040            } else {
23041                stats.dump(ipw);
23042            }
23043            ipw.decreaseIndent();
23044        }
23045    }
23046
23047    private String dumpDomainString(String packageName) {
23048        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23049                .getList();
23050        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23051
23052        ArraySet<String> result = new ArraySet<>();
23053        if (iviList.size() > 0) {
23054            for (IntentFilterVerificationInfo ivi : iviList) {
23055                for (String host : ivi.getDomains()) {
23056                    result.add(host);
23057                }
23058            }
23059        }
23060        if (filters != null && filters.size() > 0) {
23061            for (IntentFilter filter : filters) {
23062                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23063                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23064                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23065                    result.addAll(filter.getHostsList());
23066                }
23067            }
23068        }
23069
23070        StringBuilder sb = new StringBuilder(result.size() * 16);
23071        for (String domain : result) {
23072            if (sb.length() > 0) sb.append(" ");
23073            sb.append(domain);
23074        }
23075        return sb.toString();
23076    }
23077
23078    // ------- apps on sdcard specific code -------
23079    static final boolean DEBUG_SD_INSTALL = false;
23080
23081    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23082
23083    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23084
23085    private boolean mMediaMounted = false;
23086
23087    static String getEncryptKey() {
23088        try {
23089            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23090                    SD_ENCRYPTION_KEYSTORE_NAME);
23091            if (sdEncKey == null) {
23092                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23093                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23094                if (sdEncKey == null) {
23095                    Slog.e(TAG, "Failed to create encryption keys");
23096                    return null;
23097                }
23098            }
23099            return sdEncKey;
23100        } catch (NoSuchAlgorithmException nsae) {
23101            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23102            return null;
23103        } catch (IOException ioe) {
23104            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23105            return null;
23106        }
23107    }
23108
23109    /*
23110     * Update media status on PackageManager.
23111     */
23112    @Override
23113    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23114        enforceSystemOrRoot("Media status can only be updated by the system");
23115        // reader; this apparently protects mMediaMounted, but should probably
23116        // be a different lock in that case.
23117        synchronized (mPackages) {
23118            Log.i(TAG, "Updating external media status from "
23119                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23120                    + (mediaStatus ? "mounted" : "unmounted"));
23121            if (DEBUG_SD_INSTALL)
23122                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23123                        + ", mMediaMounted=" + mMediaMounted);
23124            if (mediaStatus == mMediaMounted) {
23125                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23126                        : 0, -1);
23127                mHandler.sendMessage(msg);
23128                return;
23129            }
23130            mMediaMounted = mediaStatus;
23131        }
23132        // Queue up an async operation since the package installation may take a
23133        // little while.
23134        mHandler.post(new Runnable() {
23135            public void run() {
23136                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23137            }
23138        });
23139    }
23140
23141    /**
23142     * Called by StorageManagerService when the initial ASECs to scan are available.
23143     * Should block until all the ASEC containers are finished being scanned.
23144     */
23145    public void scanAvailableAsecs() {
23146        updateExternalMediaStatusInner(true, false, false);
23147    }
23148
23149    /*
23150     * Collect information of applications on external media, map them against
23151     * existing containers and update information based on current mount status.
23152     * Please note that we always have to report status if reportStatus has been
23153     * set to true especially when unloading packages.
23154     */
23155    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23156            boolean externalStorage) {
23157        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23158        int[] uidArr = EmptyArray.INT;
23159
23160        final String[] list = PackageHelper.getSecureContainerList();
23161        if (ArrayUtils.isEmpty(list)) {
23162            Log.i(TAG, "No secure containers found");
23163        } else {
23164            // Process list of secure containers and categorize them
23165            // as active or stale based on their package internal state.
23166
23167            // reader
23168            synchronized (mPackages) {
23169                for (String cid : list) {
23170                    // Leave stages untouched for now; installer service owns them
23171                    if (PackageInstallerService.isStageName(cid)) continue;
23172
23173                    if (DEBUG_SD_INSTALL)
23174                        Log.i(TAG, "Processing container " + cid);
23175                    String pkgName = getAsecPackageName(cid);
23176                    if (pkgName == null) {
23177                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23178                        continue;
23179                    }
23180                    if (DEBUG_SD_INSTALL)
23181                        Log.i(TAG, "Looking for pkg : " + pkgName);
23182
23183                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23184                    if (ps == null) {
23185                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23186                        continue;
23187                    }
23188
23189                    /*
23190                     * Skip packages that are not external if we're unmounting
23191                     * external storage.
23192                     */
23193                    if (externalStorage && !isMounted && !isExternal(ps)) {
23194                        continue;
23195                    }
23196
23197                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23198                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23199                    // The package status is changed only if the code path
23200                    // matches between settings and the container id.
23201                    if (ps.codePathString != null
23202                            && ps.codePathString.startsWith(args.getCodePath())) {
23203                        if (DEBUG_SD_INSTALL) {
23204                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23205                                    + " at code path: " + ps.codePathString);
23206                        }
23207
23208                        // We do have a valid package installed on sdcard
23209                        processCids.put(args, ps.codePathString);
23210                        final int uid = ps.appId;
23211                        if (uid != -1) {
23212                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23213                        }
23214                    } else {
23215                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23216                                + ps.codePathString);
23217                    }
23218                }
23219            }
23220
23221            Arrays.sort(uidArr);
23222        }
23223
23224        // Process packages with valid entries.
23225        if (isMounted) {
23226            if (DEBUG_SD_INSTALL)
23227                Log.i(TAG, "Loading packages");
23228            loadMediaPackages(processCids, uidArr, externalStorage);
23229            startCleaningPackages();
23230            mInstallerService.onSecureContainersAvailable();
23231        } else {
23232            if (DEBUG_SD_INSTALL)
23233                Log.i(TAG, "Unloading packages");
23234            unloadMediaPackages(processCids, uidArr, reportStatus);
23235        }
23236    }
23237
23238    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23239            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23240        final int size = infos.size();
23241        final String[] packageNames = new String[size];
23242        final int[] packageUids = new int[size];
23243        for (int i = 0; i < size; i++) {
23244            final ApplicationInfo info = infos.get(i);
23245            packageNames[i] = info.packageName;
23246            packageUids[i] = info.uid;
23247        }
23248        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23249                finishedReceiver);
23250    }
23251
23252    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23253            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23254        sendResourcesChangedBroadcast(mediaStatus, replacing,
23255                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23256    }
23257
23258    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23259            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23260        int size = pkgList.length;
23261        if (size > 0) {
23262            // Send broadcasts here
23263            Bundle extras = new Bundle();
23264            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23265            if (uidArr != null) {
23266                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23267            }
23268            if (replacing) {
23269                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23270            }
23271            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23272                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23273            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23274        }
23275    }
23276
23277   /*
23278     * Look at potentially valid container ids from processCids If package
23279     * information doesn't match the one on record or package scanning fails,
23280     * the cid is added to list of removeCids. We currently don't delete stale
23281     * containers.
23282     */
23283    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23284            boolean externalStorage) {
23285        ArrayList<String> pkgList = new ArrayList<String>();
23286        Set<AsecInstallArgs> keys = processCids.keySet();
23287
23288        for (AsecInstallArgs args : keys) {
23289            String codePath = processCids.get(args);
23290            if (DEBUG_SD_INSTALL)
23291                Log.i(TAG, "Loading container : " + args.cid);
23292            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23293            try {
23294                // Make sure there are no container errors first.
23295                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23296                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23297                            + " when installing from sdcard");
23298                    continue;
23299                }
23300                // Check code path here.
23301                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23302                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23303                            + " does not match one in settings " + codePath);
23304                    continue;
23305                }
23306                // Parse package
23307                int parseFlags = mDefParseFlags;
23308                if (args.isExternalAsec()) {
23309                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23310                }
23311                if (args.isFwdLocked()) {
23312                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23313                }
23314
23315                synchronized (mInstallLock) {
23316                    PackageParser.Package pkg = null;
23317                    try {
23318                        // Sadly we don't know the package name yet to freeze it
23319                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23320                                SCAN_IGNORE_FROZEN, 0, null);
23321                    } catch (PackageManagerException e) {
23322                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23323                    }
23324                    // Scan the package
23325                    if (pkg != null) {
23326                        /*
23327                         * TODO why is the lock being held? doPostInstall is
23328                         * called in other places without the lock. This needs
23329                         * to be straightened out.
23330                         */
23331                        // writer
23332                        synchronized (mPackages) {
23333                            retCode = PackageManager.INSTALL_SUCCEEDED;
23334                            pkgList.add(pkg.packageName);
23335                            // Post process args
23336                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23337                                    pkg.applicationInfo.uid);
23338                        }
23339                    } else {
23340                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23341                    }
23342                }
23343
23344            } finally {
23345                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23346                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23347                }
23348            }
23349        }
23350        // writer
23351        synchronized (mPackages) {
23352            // If the platform SDK has changed since the last time we booted,
23353            // we need to re-grant app permission to catch any new ones that
23354            // appear. This is really a hack, and means that apps can in some
23355            // cases get permissions that the user didn't initially explicitly
23356            // allow... it would be nice to have some better way to handle
23357            // this situation.
23358            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23359                    : mSettings.getInternalVersion();
23360            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23361                    : StorageManager.UUID_PRIVATE_INTERNAL;
23362
23363            int updateFlags = UPDATE_PERMISSIONS_ALL;
23364            if (ver.sdkVersion != mSdkVersion) {
23365                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23366                        + mSdkVersion + "; regranting permissions for external");
23367                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23368            }
23369            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23370
23371            // Yay, everything is now upgraded
23372            ver.forceCurrent();
23373
23374            // can downgrade to reader
23375            // Persist settings
23376            mSettings.writeLPr();
23377        }
23378        // Send a broadcast to let everyone know we are done processing
23379        if (pkgList.size() > 0) {
23380            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23381        }
23382    }
23383
23384   /*
23385     * Utility method to unload a list of specified containers
23386     */
23387    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23388        // Just unmount all valid containers.
23389        for (AsecInstallArgs arg : cidArgs) {
23390            synchronized (mInstallLock) {
23391                arg.doPostDeleteLI(false);
23392           }
23393       }
23394   }
23395
23396    /*
23397     * Unload packages mounted on external media. This involves deleting package
23398     * data from internal structures, sending broadcasts about disabled packages,
23399     * gc'ing to free up references, unmounting all secure containers
23400     * corresponding to packages on external media, and posting a
23401     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23402     * that we always have to post this message if status has been requested no
23403     * matter what.
23404     */
23405    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23406            final boolean reportStatus) {
23407        if (DEBUG_SD_INSTALL)
23408            Log.i(TAG, "unloading media packages");
23409        ArrayList<String> pkgList = new ArrayList<String>();
23410        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23411        final Set<AsecInstallArgs> keys = processCids.keySet();
23412        for (AsecInstallArgs args : keys) {
23413            String pkgName = args.getPackageName();
23414            if (DEBUG_SD_INSTALL)
23415                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23416            // Delete package internally
23417            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23418            synchronized (mInstallLock) {
23419                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23420                final boolean res;
23421                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23422                        "unloadMediaPackages")) {
23423                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23424                            null);
23425                }
23426                if (res) {
23427                    pkgList.add(pkgName);
23428                } else {
23429                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23430                    failedList.add(args);
23431                }
23432            }
23433        }
23434
23435        // reader
23436        synchronized (mPackages) {
23437            // We didn't update the settings after removing each package;
23438            // write them now for all packages.
23439            mSettings.writeLPr();
23440        }
23441
23442        // We have to absolutely send UPDATED_MEDIA_STATUS only
23443        // after confirming that all the receivers processed the ordered
23444        // broadcast when packages get disabled, force a gc to clean things up.
23445        // and unload all the containers.
23446        if (pkgList.size() > 0) {
23447            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23448                    new IIntentReceiver.Stub() {
23449                public void performReceive(Intent intent, int resultCode, String data,
23450                        Bundle extras, boolean ordered, boolean sticky,
23451                        int sendingUser) throws RemoteException {
23452                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23453                            reportStatus ? 1 : 0, 1, keys);
23454                    mHandler.sendMessage(msg);
23455                }
23456            });
23457        } else {
23458            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23459                    keys);
23460            mHandler.sendMessage(msg);
23461        }
23462    }
23463
23464    private void loadPrivatePackages(final VolumeInfo vol) {
23465        mHandler.post(new Runnable() {
23466            @Override
23467            public void run() {
23468                loadPrivatePackagesInner(vol);
23469            }
23470        });
23471    }
23472
23473    private void loadPrivatePackagesInner(VolumeInfo vol) {
23474        final String volumeUuid = vol.fsUuid;
23475        if (TextUtils.isEmpty(volumeUuid)) {
23476            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23477            return;
23478        }
23479
23480        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23481        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23482        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23483
23484        final VersionInfo ver;
23485        final List<PackageSetting> packages;
23486        synchronized (mPackages) {
23487            ver = mSettings.findOrCreateVersion(volumeUuid);
23488            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23489        }
23490
23491        for (PackageSetting ps : packages) {
23492            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23493            synchronized (mInstallLock) {
23494                final PackageParser.Package pkg;
23495                try {
23496                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23497                    loaded.add(pkg.applicationInfo);
23498
23499                } catch (PackageManagerException e) {
23500                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23501                }
23502
23503                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23504                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23505                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23506                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23507                }
23508            }
23509        }
23510
23511        // Reconcile app data for all started/unlocked users
23512        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23513        final UserManager um = mContext.getSystemService(UserManager.class);
23514        UserManagerInternal umInternal = getUserManagerInternal();
23515        for (UserInfo user : um.getUsers()) {
23516            final int flags;
23517            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23518                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23519            } else if (umInternal.isUserRunning(user.id)) {
23520                flags = StorageManager.FLAG_STORAGE_DE;
23521            } else {
23522                continue;
23523            }
23524
23525            try {
23526                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23527                synchronized (mInstallLock) {
23528                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23529                }
23530            } catch (IllegalStateException e) {
23531                // Device was probably ejected, and we'll process that event momentarily
23532                Slog.w(TAG, "Failed to prepare storage: " + e);
23533            }
23534        }
23535
23536        synchronized (mPackages) {
23537            int updateFlags = UPDATE_PERMISSIONS_ALL;
23538            if (ver.sdkVersion != mSdkVersion) {
23539                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23540                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23541                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23542            }
23543            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23544
23545            // Yay, everything is now upgraded
23546            ver.forceCurrent();
23547
23548            mSettings.writeLPr();
23549        }
23550
23551        for (PackageFreezer freezer : freezers) {
23552            freezer.close();
23553        }
23554
23555        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23556        sendResourcesChangedBroadcast(true, false, loaded, null);
23557        mLoadedVolumes.add(vol.getId());
23558    }
23559
23560    private void unloadPrivatePackages(final VolumeInfo vol) {
23561        mHandler.post(new Runnable() {
23562            @Override
23563            public void run() {
23564                unloadPrivatePackagesInner(vol);
23565            }
23566        });
23567    }
23568
23569    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23570        final String volumeUuid = vol.fsUuid;
23571        if (TextUtils.isEmpty(volumeUuid)) {
23572            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23573            return;
23574        }
23575
23576        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23577        synchronized (mInstallLock) {
23578        synchronized (mPackages) {
23579            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23580            for (PackageSetting ps : packages) {
23581                if (ps.pkg == null) continue;
23582
23583                final ApplicationInfo info = ps.pkg.applicationInfo;
23584                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23585                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23586
23587                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23588                        "unloadPrivatePackagesInner")) {
23589                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23590                            false, null)) {
23591                        unloaded.add(info);
23592                    } else {
23593                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23594                    }
23595                }
23596
23597                // Try very hard to release any references to this package
23598                // so we don't risk the system server being killed due to
23599                // open FDs
23600                AttributeCache.instance().removePackage(ps.name);
23601            }
23602
23603            mSettings.writeLPr();
23604        }
23605        }
23606
23607        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23608        sendResourcesChangedBroadcast(false, false, unloaded, null);
23609        mLoadedVolumes.remove(vol.getId());
23610
23611        // Try very hard to release any references to this path so we don't risk
23612        // the system server being killed due to open FDs
23613        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23614
23615        for (int i = 0; i < 3; i++) {
23616            System.gc();
23617            System.runFinalization();
23618        }
23619    }
23620
23621    private void assertPackageKnown(String volumeUuid, String packageName)
23622            throws PackageManagerException {
23623        synchronized (mPackages) {
23624            // Normalize package name to handle renamed packages
23625            packageName = normalizePackageNameLPr(packageName);
23626
23627            final PackageSetting ps = mSettings.mPackages.get(packageName);
23628            if (ps == null) {
23629                throw new PackageManagerException("Package " + packageName + " is unknown");
23630            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23631                throw new PackageManagerException(
23632                        "Package " + packageName + " found on unknown volume " + volumeUuid
23633                                + "; expected volume " + ps.volumeUuid);
23634            }
23635        }
23636    }
23637
23638    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23639            throws PackageManagerException {
23640        synchronized (mPackages) {
23641            // Normalize package name to handle renamed packages
23642            packageName = normalizePackageNameLPr(packageName);
23643
23644            final PackageSetting ps = mSettings.mPackages.get(packageName);
23645            if (ps == null) {
23646                throw new PackageManagerException("Package " + packageName + " is unknown");
23647            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23648                throw new PackageManagerException(
23649                        "Package " + packageName + " found on unknown volume " + volumeUuid
23650                                + "; expected volume " + ps.volumeUuid);
23651            } else if (!ps.getInstalled(userId)) {
23652                throw new PackageManagerException(
23653                        "Package " + packageName + " not installed for user " + userId);
23654            }
23655        }
23656    }
23657
23658    private List<String> collectAbsoluteCodePaths() {
23659        synchronized (mPackages) {
23660            List<String> codePaths = new ArrayList<>();
23661            final int packageCount = mSettings.mPackages.size();
23662            for (int i = 0; i < packageCount; i++) {
23663                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23664                codePaths.add(ps.codePath.getAbsolutePath());
23665            }
23666            return codePaths;
23667        }
23668    }
23669
23670    /**
23671     * Examine all apps present on given mounted volume, and destroy apps that
23672     * aren't expected, either due to uninstallation or reinstallation on
23673     * another volume.
23674     */
23675    private void reconcileApps(String volumeUuid) {
23676        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23677        List<File> filesToDelete = null;
23678
23679        final File[] files = FileUtils.listFilesOrEmpty(
23680                Environment.getDataAppDirectory(volumeUuid));
23681        for (File file : files) {
23682            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23683                    && !PackageInstallerService.isStageName(file.getName());
23684            if (!isPackage) {
23685                // Ignore entries which are not packages
23686                continue;
23687            }
23688
23689            String absolutePath = file.getAbsolutePath();
23690
23691            boolean pathValid = false;
23692            final int absoluteCodePathCount = absoluteCodePaths.size();
23693            for (int i = 0; i < absoluteCodePathCount; i++) {
23694                String absoluteCodePath = absoluteCodePaths.get(i);
23695                if (absolutePath.startsWith(absoluteCodePath)) {
23696                    pathValid = true;
23697                    break;
23698                }
23699            }
23700
23701            if (!pathValid) {
23702                if (filesToDelete == null) {
23703                    filesToDelete = new ArrayList<>();
23704                }
23705                filesToDelete.add(file);
23706            }
23707        }
23708
23709        if (filesToDelete != null) {
23710            final int fileToDeleteCount = filesToDelete.size();
23711            for (int i = 0; i < fileToDeleteCount; i++) {
23712                File fileToDelete = filesToDelete.get(i);
23713                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23714                synchronized (mInstallLock) {
23715                    removeCodePathLI(fileToDelete);
23716                }
23717            }
23718        }
23719    }
23720
23721    /**
23722     * Reconcile all app data for the given user.
23723     * <p>
23724     * Verifies that directories exist and that ownership and labeling is
23725     * correct for all installed apps on all mounted volumes.
23726     */
23727    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23728        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23729        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23730            final String volumeUuid = vol.getFsUuid();
23731            synchronized (mInstallLock) {
23732                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23733            }
23734        }
23735    }
23736
23737    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23738            boolean migrateAppData) {
23739        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23740    }
23741
23742    /**
23743     * Reconcile all app data on given mounted volume.
23744     * <p>
23745     * Destroys app data that isn't expected, either due to uninstallation or
23746     * reinstallation on another volume.
23747     * <p>
23748     * Verifies that directories exist and that ownership and labeling is
23749     * correct for all installed apps.
23750     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23751     */
23752    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23753            boolean migrateAppData, boolean onlyCoreApps) {
23754        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23755                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23756        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23757
23758        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23759        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23760
23761        // First look for stale data that doesn't belong, and check if things
23762        // have changed since we did our last restorecon
23763        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23764            if (StorageManager.isFileEncryptedNativeOrEmulated()
23765                    && !StorageManager.isUserKeyUnlocked(userId)) {
23766                throw new RuntimeException(
23767                        "Yikes, someone asked us to reconcile CE storage while " + userId
23768                                + " was still locked; this would have caused massive data loss!");
23769            }
23770
23771            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23772            for (File file : files) {
23773                final String packageName = file.getName();
23774                try {
23775                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23776                } catch (PackageManagerException e) {
23777                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23778                    try {
23779                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23780                                StorageManager.FLAG_STORAGE_CE, 0);
23781                    } catch (InstallerException e2) {
23782                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23783                    }
23784                }
23785            }
23786        }
23787        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23788            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23789            for (File file : files) {
23790                final String packageName = file.getName();
23791                try {
23792                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23793                } catch (PackageManagerException e) {
23794                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23795                    try {
23796                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23797                                StorageManager.FLAG_STORAGE_DE, 0);
23798                    } catch (InstallerException e2) {
23799                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23800                    }
23801                }
23802            }
23803        }
23804
23805        // Ensure that data directories are ready to roll for all packages
23806        // installed for this volume and user
23807        final List<PackageSetting> packages;
23808        synchronized (mPackages) {
23809            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23810        }
23811        int preparedCount = 0;
23812        for (PackageSetting ps : packages) {
23813            final String packageName = ps.name;
23814            if (ps.pkg == null) {
23815                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23816                // TODO: might be due to legacy ASEC apps; we should circle back
23817                // and reconcile again once they're scanned
23818                continue;
23819            }
23820            // Skip non-core apps if requested
23821            if (onlyCoreApps && !ps.pkg.coreApp) {
23822                result.add(packageName);
23823                continue;
23824            }
23825
23826            if (ps.getInstalled(userId)) {
23827                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23828                preparedCount++;
23829            }
23830        }
23831
23832        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23833        return result;
23834    }
23835
23836    /**
23837     * Prepare app data for the given app just after it was installed or
23838     * upgraded. This method carefully only touches users that it's installed
23839     * for, and it forces a restorecon to handle any seinfo changes.
23840     * <p>
23841     * Verifies that directories exist and that ownership and labeling is
23842     * correct for all installed apps. If there is an ownership mismatch, it
23843     * will try recovering system apps by wiping data; third-party app data is
23844     * left intact.
23845     * <p>
23846     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23847     */
23848    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23849        final PackageSetting ps;
23850        synchronized (mPackages) {
23851            ps = mSettings.mPackages.get(pkg.packageName);
23852            mSettings.writeKernelMappingLPr(ps);
23853        }
23854
23855        final UserManager um = mContext.getSystemService(UserManager.class);
23856        UserManagerInternal umInternal = getUserManagerInternal();
23857        for (UserInfo user : um.getUsers()) {
23858            final int flags;
23859            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23860                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23861            } else if (umInternal.isUserRunning(user.id)) {
23862                flags = StorageManager.FLAG_STORAGE_DE;
23863            } else {
23864                continue;
23865            }
23866
23867            if (ps.getInstalled(user.id)) {
23868                // TODO: when user data is locked, mark that we're still dirty
23869                prepareAppDataLIF(pkg, user.id, flags);
23870            }
23871        }
23872    }
23873
23874    /**
23875     * Prepare app data for the given app.
23876     * <p>
23877     * Verifies that directories exist and that ownership and labeling is
23878     * correct for all installed apps. If there is an ownership mismatch, this
23879     * will try recovering system apps by wiping data; third-party app data is
23880     * left intact.
23881     */
23882    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23883        if (pkg == null) {
23884            Slog.wtf(TAG, "Package was null!", new Throwable());
23885            return;
23886        }
23887        prepareAppDataLeafLIF(pkg, userId, flags);
23888        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23889        for (int i = 0; i < childCount; i++) {
23890            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23891        }
23892    }
23893
23894    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23895            boolean maybeMigrateAppData) {
23896        prepareAppDataLIF(pkg, userId, flags);
23897
23898        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23899            // We may have just shuffled around app data directories, so
23900            // prepare them one more time
23901            prepareAppDataLIF(pkg, userId, flags);
23902        }
23903    }
23904
23905    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23906        if (DEBUG_APP_DATA) {
23907            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23908                    + Integer.toHexString(flags));
23909        }
23910
23911        final String volumeUuid = pkg.volumeUuid;
23912        final String packageName = pkg.packageName;
23913        final ApplicationInfo app = pkg.applicationInfo;
23914        final int appId = UserHandle.getAppId(app.uid);
23915
23916        Preconditions.checkNotNull(app.seInfo);
23917
23918        long ceDataInode = -1;
23919        try {
23920            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23921                    appId, app.seInfo, app.targetSdkVersion);
23922        } catch (InstallerException e) {
23923            if (app.isSystemApp()) {
23924                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23925                        + ", but trying to recover: " + e);
23926                destroyAppDataLeafLIF(pkg, userId, flags);
23927                try {
23928                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23929                            appId, app.seInfo, app.targetSdkVersion);
23930                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23931                } catch (InstallerException e2) {
23932                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23933                }
23934            } else {
23935                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23936            }
23937        }
23938
23939        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23940            // TODO: mark this structure as dirty so we persist it!
23941            synchronized (mPackages) {
23942                final PackageSetting ps = mSettings.mPackages.get(packageName);
23943                if (ps != null) {
23944                    ps.setCeDataInode(ceDataInode, userId);
23945                }
23946            }
23947        }
23948
23949        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23950    }
23951
23952    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23953        if (pkg == null) {
23954            Slog.wtf(TAG, "Package was null!", new Throwable());
23955            return;
23956        }
23957        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23958        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23959        for (int i = 0; i < childCount; i++) {
23960            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23961        }
23962    }
23963
23964    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23965        final String volumeUuid = pkg.volumeUuid;
23966        final String packageName = pkg.packageName;
23967        final ApplicationInfo app = pkg.applicationInfo;
23968
23969        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23970            // Create a native library symlink only if we have native libraries
23971            // and if the native libraries are 32 bit libraries. We do not provide
23972            // this symlink for 64 bit libraries.
23973            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23974                final String nativeLibPath = app.nativeLibraryDir;
23975                try {
23976                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23977                            nativeLibPath, userId);
23978                } catch (InstallerException e) {
23979                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23980                }
23981            }
23982        }
23983    }
23984
23985    /**
23986     * For system apps on non-FBE devices, this method migrates any existing
23987     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23988     * requested by the app.
23989     */
23990    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23991        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23992                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23993            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23994                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23995            try {
23996                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23997                        storageTarget);
23998            } catch (InstallerException e) {
23999                logCriticalInfo(Log.WARN,
24000                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24001            }
24002            return true;
24003        } else {
24004            return false;
24005        }
24006    }
24007
24008    public PackageFreezer freezePackage(String packageName, String killReason) {
24009        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24010    }
24011
24012    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24013        return new PackageFreezer(packageName, userId, killReason);
24014    }
24015
24016    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24017            String killReason) {
24018        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24019    }
24020
24021    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24022            String killReason) {
24023        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24024            return new PackageFreezer();
24025        } else {
24026            return freezePackage(packageName, userId, killReason);
24027        }
24028    }
24029
24030    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24031            String killReason) {
24032        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24033    }
24034
24035    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24036            String killReason) {
24037        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24038            return new PackageFreezer();
24039        } else {
24040            return freezePackage(packageName, userId, killReason);
24041        }
24042    }
24043
24044    /**
24045     * Class that freezes and kills the given package upon creation, and
24046     * unfreezes it upon closing. This is typically used when doing surgery on
24047     * app code/data to prevent the app from running while you're working.
24048     */
24049    private class PackageFreezer implements AutoCloseable {
24050        private final String mPackageName;
24051        private final PackageFreezer[] mChildren;
24052
24053        private final boolean mWeFroze;
24054
24055        private final AtomicBoolean mClosed = new AtomicBoolean();
24056        private final CloseGuard mCloseGuard = CloseGuard.get();
24057
24058        /**
24059         * Create and return a stub freezer that doesn't actually do anything,
24060         * typically used when someone requested
24061         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24062         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24063         */
24064        public PackageFreezer() {
24065            mPackageName = null;
24066            mChildren = null;
24067            mWeFroze = false;
24068            mCloseGuard.open("close");
24069        }
24070
24071        public PackageFreezer(String packageName, int userId, String killReason) {
24072            synchronized (mPackages) {
24073                mPackageName = packageName;
24074                mWeFroze = mFrozenPackages.add(mPackageName);
24075
24076                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24077                if (ps != null) {
24078                    killApplication(ps.name, ps.appId, userId, killReason);
24079                }
24080
24081                final PackageParser.Package p = mPackages.get(packageName);
24082                if (p != null && p.childPackages != null) {
24083                    final int N = p.childPackages.size();
24084                    mChildren = new PackageFreezer[N];
24085                    for (int i = 0; i < N; i++) {
24086                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24087                                userId, killReason);
24088                    }
24089                } else {
24090                    mChildren = null;
24091                }
24092            }
24093            mCloseGuard.open("close");
24094        }
24095
24096        @Override
24097        protected void finalize() throws Throwable {
24098            try {
24099                if (mCloseGuard != null) {
24100                    mCloseGuard.warnIfOpen();
24101                }
24102
24103                close();
24104            } finally {
24105                super.finalize();
24106            }
24107        }
24108
24109        @Override
24110        public void close() {
24111            mCloseGuard.close();
24112            if (mClosed.compareAndSet(false, true)) {
24113                synchronized (mPackages) {
24114                    if (mWeFroze) {
24115                        mFrozenPackages.remove(mPackageName);
24116                    }
24117
24118                    if (mChildren != null) {
24119                        for (PackageFreezer freezer : mChildren) {
24120                            freezer.close();
24121                        }
24122                    }
24123                }
24124            }
24125        }
24126    }
24127
24128    /**
24129     * Verify that given package is currently frozen.
24130     */
24131    private void checkPackageFrozen(String packageName) {
24132        synchronized (mPackages) {
24133            if (!mFrozenPackages.contains(packageName)) {
24134                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24135            }
24136        }
24137    }
24138
24139    @Override
24140    public int movePackage(final String packageName, final String volumeUuid) {
24141        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24142
24143        final int callingUid = Binder.getCallingUid();
24144        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24145        final int moveId = mNextMoveId.getAndIncrement();
24146        mHandler.post(new Runnable() {
24147            @Override
24148            public void run() {
24149                try {
24150                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24151                } catch (PackageManagerException e) {
24152                    Slog.w(TAG, "Failed to move " + packageName, e);
24153                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24154                }
24155            }
24156        });
24157        return moveId;
24158    }
24159
24160    private void movePackageInternal(final String packageName, final String volumeUuid,
24161            final int moveId, final int callingUid, UserHandle user)
24162                    throws PackageManagerException {
24163        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24164        final PackageManager pm = mContext.getPackageManager();
24165
24166        final boolean currentAsec;
24167        final String currentVolumeUuid;
24168        final File codeFile;
24169        final String installerPackageName;
24170        final String packageAbiOverride;
24171        final int appId;
24172        final String seinfo;
24173        final String label;
24174        final int targetSdkVersion;
24175        final PackageFreezer freezer;
24176        final int[] installedUserIds;
24177
24178        // reader
24179        synchronized (mPackages) {
24180            final PackageParser.Package pkg = mPackages.get(packageName);
24181            final PackageSetting ps = mSettings.mPackages.get(packageName);
24182            if (pkg == null
24183                    || ps == null
24184                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24185                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24186            }
24187            if (pkg.applicationInfo.isSystemApp()) {
24188                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24189                        "Cannot move system application");
24190            }
24191
24192            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24193            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24194                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24195            if (isInternalStorage && !allow3rdPartyOnInternal) {
24196                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24197                        "3rd party apps are not allowed on internal storage");
24198            }
24199
24200            if (pkg.applicationInfo.isExternalAsec()) {
24201                currentAsec = true;
24202                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24203            } else if (pkg.applicationInfo.isForwardLocked()) {
24204                currentAsec = true;
24205                currentVolumeUuid = "forward_locked";
24206            } else {
24207                currentAsec = false;
24208                currentVolumeUuid = ps.volumeUuid;
24209
24210                final File probe = new File(pkg.codePath);
24211                final File probeOat = new File(probe, "oat");
24212                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24213                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24214                            "Move only supported for modern cluster style installs");
24215                }
24216            }
24217
24218            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24219                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24220                        "Package already moved to " + volumeUuid);
24221            }
24222            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24223                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24224                        "Device admin cannot be moved");
24225            }
24226
24227            if (mFrozenPackages.contains(packageName)) {
24228                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24229                        "Failed to move already frozen package");
24230            }
24231
24232            codeFile = new File(pkg.codePath);
24233            installerPackageName = ps.installerPackageName;
24234            packageAbiOverride = ps.cpuAbiOverrideString;
24235            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24236            seinfo = pkg.applicationInfo.seInfo;
24237            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24238            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24239            freezer = freezePackage(packageName, "movePackageInternal");
24240            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24241        }
24242
24243        final Bundle extras = new Bundle();
24244        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24245        extras.putString(Intent.EXTRA_TITLE, label);
24246        mMoveCallbacks.notifyCreated(moveId, extras);
24247
24248        int installFlags;
24249        final boolean moveCompleteApp;
24250        final File measurePath;
24251
24252        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24253            installFlags = INSTALL_INTERNAL;
24254            moveCompleteApp = !currentAsec;
24255            measurePath = Environment.getDataAppDirectory(volumeUuid);
24256        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24257            installFlags = INSTALL_EXTERNAL;
24258            moveCompleteApp = false;
24259            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24260        } else {
24261            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24262            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24263                    || !volume.isMountedWritable()) {
24264                freezer.close();
24265                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24266                        "Move location not mounted private volume");
24267            }
24268
24269            Preconditions.checkState(!currentAsec);
24270
24271            installFlags = INSTALL_INTERNAL;
24272            moveCompleteApp = true;
24273            measurePath = Environment.getDataAppDirectory(volumeUuid);
24274        }
24275
24276        // If we're moving app data around, we need all the users unlocked
24277        if (moveCompleteApp) {
24278            for (int userId : installedUserIds) {
24279                if (StorageManager.isFileEncryptedNativeOrEmulated()
24280                        && !StorageManager.isUserKeyUnlocked(userId)) {
24281                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24282                            "User " + userId + " must be unlocked");
24283                }
24284            }
24285        }
24286
24287        final PackageStats stats = new PackageStats(null, -1);
24288        synchronized (mInstaller) {
24289            for (int userId : installedUserIds) {
24290                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24291                    freezer.close();
24292                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24293                            "Failed to measure package size");
24294                }
24295            }
24296        }
24297
24298        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24299                + stats.dataSize);
24300
24301        final long startFreeBytes = measurePath.getUsableSpace();
24302        final long sizeBytes;
24303        if (moveCompleteApp) {
24304            sizeBytes = stats.codeSize + stats.dataSize;
24305        } else {
24306            sizeBytes = stats.codeSize;
24307        }
24308
24309        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24310            freezer.close();
24311            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24312                    "Not enough free space to move");
24313        }
24314
24315        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24316
24317        final CountDownLatch installedLatch = new CountDownLatch(1);
24318        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24319            @Override
24320            public void onUserActionRequired(Intent intent) throws RemoteException {
24321                throw new IllegalStateException();
24322            }
24323
24324            @Override
24325            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24326                    Bundle extras) throws RemoteException {
24327                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24328                        + PackageManager.installStatusToString(returnCode, msg));
24329
24330                installedLatch.countDown();
24331                freezer.close();
24332
24333                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24334                switch (status) {
24335                    case PackageInstaller.STATUS_SUCCESS:
24336                        mMoveCallbacks.notifyStatusChanged(moveId,
24337                                PackageManager.MOVE_SUCCEEDED);
24338                        break;
24339                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24340                        mMoveCallbacks.notifyStatusChanged(moveId,
24341                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24342                        break;
24343                    default:
24344                        mMoveCallbacks.notifyStatusChanged(moveId,
24345                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24346                        break;
24347                }
24348            }
24349        };
24350
24351        final MoveInfo move;
24352        if (moveCompleteApp) {
24353            // Kick off a thread to report progress estimates
24354            new Thread() {
24355                @Override
24356                public void run() {
24357                    while (true) {
24358                        try {
24359                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24360                                break;
24361                            }
24362                        } catch (InterruptedException ignored) {
24363                        }
24364
24365                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24366                        final int progress = 10 + (int) MathUtils.constrain(
24367                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24368                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24369                    }
24370                }
24371            }.start();
24372
24373            final String dataAppName = codeFile.getName();
24374            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24375                    dataAppName, appId, seinfo, targetSdkVersion);
24376        } else {
24377            move = null;
24378        }
24379
24380        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24381
24382        final Message msg = mHandler.obtainMessage(INIT_COPY);
24383        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24384        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24385                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24386                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24387                PackageManager.INSTALL_REASON_UNKNOWN);
24388        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24389        msg.obj = params;
24390
24391        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24392                System.identityHashCode(msg.obj));
24393        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24394                System.identityHashCode(msg.obj));
24395
24396        mHandler.sendMessage(msg);
24397    }
24398
24399    @Override
24400    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24401        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24402
24403        final int realMoveId = mNextMoveId.getAndIncrement();
24404        final Bundle extras = new Bundle();
24405        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24406        mMoveCallbacks.notifyCreated(realMoveId, extras);
24407
24408        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24409            @Override
24410            public void onCreated(int moveId, Bundle extras) {
24411                // Ignored
24412            }
24413
24414            @Override
24415            public void onStatusChanged(int moveId, int status, long estMillis) {
24416                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24417            }
24418        };
24419
24420        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24421        storage.setPrimaryStorageUuid(volumeUuid, callback);
24422        return realMoveId;
24423    }
24424
24425    @Override
24426    public int getMoveStatus(int moveId) {
24427        mContext.enforceCallingOrSelfPermission(
24428                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24429        return mMoveCallbacks.mLastStatus.get(moveId);
24430    }
24431
24432    @Override
24433    public void registerMoveCallback(IPackageMoveObserver callback) {
24434        mContext.enforceCallingOrSelfPermission(
24435                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24436        mMoveCallbacks.register(callback);
24437    }
24438
24439    @Override
24440    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24441        mContext.enforceCallingOrSelfPermission(
24442                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24443        mMoveCallbacks.unregister(callback);
24444    }
24445
24446    @Override
24447    public boolean setInstallLocation(int loc) {
24448        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24449                null);
24450        if (getInstallLocation() == loc) {
24451            return true;
24452        }
24453        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24454                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24455            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24456                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24457            return true;
24458        }
24459        return false;
24460   }
24461
24462    @Override
24463    public int getInstallLocation() {
24464        // allow instant app access
24465        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24466                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24467                PackageHelper.APP_INSTALL_AUTO);
24468    }
24469
24470    /** Called by UserManagerService */
24471    void cleanUpUser(UserManagerService userManager, int userHandle) {
24472        synchronized (mPackages) {
24473            mDirtyUsers.remove(userHandle);
24474            mUserNeedsBadging.delete(userHandle);
24475            mSettings.removeUserLPw(userHandle);
24476            mPendingBroadcasts.remove(userHandle);
24477            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24478            removeUnusedPackagesLPw(userManager, userHandle);
24479        }
24480    }
24481
24482    /**
24483     * We're removing userHandle and would like to remove any downloaded packages
24484     * that are no longer in use by any other user.
24485     * @param userHandle the user being removed
24486     */
24487    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24488        final boolean DEBUG_CLEAN_APKS = false;
24489        int [] users = userManager.getUserIds();
24490        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24491        while (psit.hasNext()) {
24492            PackageSetting ps = psit.next();
24493            if (ps.pkg == null) {
24494                continue;
24495            }
24496            final String packageName = ps.pkg.packageName;
24497            // Skip over if system app
24498            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24499                continue;
24500            }
24501            if (DEBUG_CLEAN_APKS) {
24502                Slog.i(TAG, "Checking package " + packageName);
24503            }
24504            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24505            if (keep) {
24506                if (DEBUG_CLEAN_APKS) {
24507                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24508                }
24509            } else {
24510                for (int i = 0; i < users.length; i++) {
24511                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24512                        keep = true;
24513                        if (DEBUG_CLEAN_APKS) {
24514                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24515                                    + users[i]);
24516                        }
24517                        break;
24518                    }
24519                }
24520            }
24521            if (!keep) {
24522                if (DEBUG_CLEAN_APKS) {
24523                    Slog.i(TAG, "  Removing package " + packageName);
24524                }
24525                mHandler.post(new Runnable() {
24526                    public void run() {
24527                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24528                                userHandle, 0);
24529                    } //end run
24530                });
24531            }
24532        }
24533    }
24534
24535    /** Called by UserManagerService */
24536    void createNewUser(int userId, String[] disallowedPackages) {
24537        synchronized (mInstallLock) {
24538            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24539        }
24540        synchronized (mPackages) {
24541            scheduleWritePackageRestrictionsLocked(userId);
24542            scheduleWritePackageListLocked(userId);
24543            applyFactoryDefaultBrowserLPw(userId);
24544            primeDomainVerificationsLPw(userId);
24545        }
24546    }
24547
24548    void onNewUserCreated(final int userId) {
24549        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24550        // If permission review for legacy apps is required, we represent
24551        // dagerous permissions for such apps as always granted runtime
24552        // permissions to keep per user flag state whether review is needed.
24553        // Hence, if a new user is added we have to propagate dangerous
24554        // permission grants for these legacy apps.
24555        if (mPermissionReviewRequired) {
24556            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24557                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24558        }
24559    }
24560
24561    @Override
24562    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24563        mContext.enforceCallingOrSelfPermission(
24564                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24565                "Only package verification agents can read the verifier device identity");
24566
24567        synchronized (mPackages) {
24568            return mSettings.getVerifierDeviceIdentityLPw();
24569        }
24570    }
24571
24572    @Override
24573    public void setPermissionEnforced(String permission, boolean enforced) {
24574        // TODO: Now that we no longer change GID for storage, this should to away.
24575        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24576                "setPermissionEnforced");
24577        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24578            synchronized (mPackages) {
24579                if (mSettings.mReadExternalStorageEnforced == null
24580                        || mSettings.mReadExternalStorageEnforced != enforced) {
24581                    mSettings.mReadExternalStorageEnforced = enforced;
24582                    mSettings.writeLPr();
24583                }
24584            }
24585            // kill any non-foreground processes so we restart them and
24586            // grant/revoke the GID.
24587            final IActivityManager am = ActivityManager.getService();
24588            if (am != null) {
24589                final long token = Binder.clearCallingIdentity();
24590                try {
24591                    am.killProcessesBelowForeground("setPermissionEnforcement");
24592                } catch (RemoteException e) {
24593                } finally {
24594                    Binder.restoreCallingIdentity(token);
24595                }
24596            }
24597        } else {
24598            throw new IllegalArgumentException("No selective enforcement for " + permission);
24599        }
24600    }
24601
24602    @Override
24603    @Deprecated
24604    public boolean isPermissionEnforced(String permission) {
24605        // allow instant applications
24606        return true;
24607    }
24608
24609    @Override
24610    public boolean isStorageLow() {
24611        // allow instant applications
24612        final long token = Binder.clearCallingIdentity();
24613        try {
24614            final DeviceStorageMonitorInternal
24615                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24616            if (dsm != null) {
24617                return dsm.isMemoryLow();
24618            } else {
24619                return false;
24620            }
24621        } finally {
24622            Binder.restoreCallingIdentity(token);
24623        }
24624    }
24625
24626    @Override
24627    public IPackageInstaller getPackageInstaller() {
24628        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24629            return null;
24630        }
24631        return mInstallerService;
24632    }
24633
24634    private boolean userNeedsBadging(int userId) {
24635        int index = mUserNeedsBadging.indexOfKey(userId);
24636        if (index < 0) {
24637            final UserInfo userInfo;
24638            final long token = Binder.clearCallingIdentity();
24639            try {
24640                userInfo = sUserManager.getUserInfo(userId);
24641            } finally {
24642                Binder.restoreCallingIdentity(token);
24643            }
24644            final boolean b;
24645            if (userInfo != null && userInfo.isManagedProfile()) {
24646                b = true;
24647            } else {
24648                b = false;
24649            }
24650            mUserNeedsBadging.put(userId, b);
24651            return b;
24652        }
24653        return mUserNeedsBadging.valueAt(index);
24654    }
24655
24656    @Override
24657    public KeySet getKeySetByAlias(String packageName, String alias) {
24658        if (packageName == null || alias == null) {
24659            return null;
24660        }
24661        synchronized(mPackages) {
24662            final PackageParser.Package pkg = mPackages.get(packageName);
24663            if (pkg == null) {
24664                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24665                throw new IllegalArgumentException("Unknown package: " + packageName);
24666            }
24667            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24668            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24669                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24670                throw new IllegalArgumentException("Unknown package: " + packageName);
24671            }
24672            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24673            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24674        }
24675    }
24676
24677    @Override
24678    public KeySet getSigningKeySet(String packageName) {
24679        if (packageName == null) {
24680            return null;
24681        }
24682        synchronized(mPackages) {
24683            final int callingUid = Binder.getCallingUid();
24684            final int callingUserId = UserHandle.getUserId(callingUid);
24685            final PackageParser.Package pkg = mPackages.get(packageName);
24686            if (pkg == null) {
24687                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24688                throw new IllegalArgumentException("Unknown package: " + packageName);
24689            }
24690            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24691            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24692                // filter and pretend the package doesn't exist
24693                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24694                        + ", uid:" + callingUid);
24695                throw new IllegalArgumentException("Unknown package: " + packageName);
24696            }
24697            if (pkg.applicationInfo.uid != callingUid
24698                    && Process.SYSTEM_UID != callingUid) {
24699                throw new SecurityException("May not access signing KeySet of other apps.");
24700            }
24701            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24702            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24703        }
24704    }
24705
24706    @Override
24707    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24708        final int callingUid = Binder.getCallingUid();
24709        if (getInstantAppPackageName(callingUid) != null) {
24710            return false;
24711        }
24712        if (packageName == null || ks == null) {
24713            return false;
24714        }
24715        synchronized(mPackages) {
24716            final PackageParser.Package pkg = mPackages.get(packageName);
24717            if (pkg == null
24718                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24719                            UserHandle.getUserId(callingUid))) {
24720                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24721                throw new IllegalArgumentException("Unknown package: " + packageName);
24722            }
24723            IBinder ksh = ks.getToken();
24724            if (ksh instanceof KeySetHandle) {
24725                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24726                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24727            }
24728            return false;
24729        }
24730    }
24731
24732    @Override
24733    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24734        final int callingUid = Binder.getCallingUid();
24735        if (getInstantAppPackageName(callingUid) != null) {
24736            return false;
24737        }
24738        if (packageName == null || ks == null) {
24739            return false;
24740        }
24741        synchronized(mPackages) {
24742            final PackageParser.Package pkg = mPackages.get(packageName);
24743            if (pkg == null
24744                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24745                            UserHandle.getUserId(callingUid))) {
24746                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24747                throw new IllegalArgumentException("Unknown package: " + packageName);
24748            }
24749            IBinder ksh = ks.getToken();
24750            if (ksh instanceof KeySetHandle) {
24751                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24752                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24753            }
24754            return false;
24755        }
24756    }
24757
24758    private void deletePackageIfUnusedLPr(final String packageName) {
24759        PackageSetting ps = mSettings.mPackages.get(packageName);
24760        if (ps == null) {
24761            return;
24762        }
24763        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24764            // TODO Implement atomic delete if package is unused
24765            // It is currently possible that the package will be deleted even if it is installed
24766            // after this method returns.
24767            mHandler.post(new Runnable() {
24768                public void run() {
24769                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24770                            0, PackageManager.DELETE_ALL_USERS);
24771                }
24772            });
24773        }
24774    }
24775
24776    /**
24777     * Check and throw if the given before/after packages would be considered a
24778     * downgrade.
24779     */
24780    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24781            throws PackageManagerException {
24782        if (after.versionCode < before.mVersionCode) {
24783            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24784                    "Update version code " + after.versionCode + " is older than current "
24785                    + before.mVersionCode);
24786        } else if (after.versionCode == before.mVersionCode) {
24787            if (after.baseRevisionCode < before.baseRevisionCode) {
24788                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24789                        "Update base revision code " + after.baseRevisionCode
24790                        + " is older than current " + before.baseRevisionCode);
24791            }
24792
24793            if (!ArrayUtils.isEmpty(after.splitNames)) {
24794                for (int i = 0; i < after.splitNames.length; i++) {
24795                    final String splitName = after.splitNames[i];
24796                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24797                    if (j != -1) {
24798                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24799                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24800                                    "Update split " + splitName + " revision code "
24801                                    + after.splitRevisionCodes[i] + " is older than current "
24802                                    + before.splitRevisionCodes[j]);
24803                        }
24804                    }
24805                }
24806            }
24807        }
24808    }
24809
24810    private static class MoveCallbacks extends Handler {
24811        private static final int MSG_CREATED = 1;
24812        private static final int MSG_STATUS_CHANGED = 2;
24813
24814        private final RemoteCallbackList<IPackageMoveObserver>
24815                mCallbacks = new RemoteCallbackList<>();
24816
24817        private final SparseIntArray mLastStatus = new SparseIntArray();
24818
24819        public MoveCallbacks(Looper looper) {
24820            super(looper);
24821        }
24822
24823        public void register(IPackageMoveObserver callback) {
24824            mCallbacks.register(callback);
24825        }
24826
24827        public void unregister(IPackageMoveObserver callback) {
24828            mCallbacks.unregister(callback);
24829        }
24830
24831        @Override
24832        public void handleMessage(Message msg) {
24833            final SomeArgs args = (SomeArgs) msg.obj;
24834            final int n = mCallbacks.beginBroadcast();
24835            for (int i = 0; i < n; i++) {
24836                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24837                try {
24838                    invokeCallback(callback, msg.what, args);
24839                } catch (RemoteException ignored) {
24840                }
24841            }
24842            mCallbacks.finishBroadcast();
24843            args.recycle();
24844        }
24845
24846        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24847                throws RemoteException {
24848            switch (what) {
24849                case MSG_CREATED: {
24850                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24851                    break;
24852                }
24853                case MSG_STATUS_CHANGED: {
24854                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24855                    break;
24856                }
24857            }
24858        }
24859
24860        private void notifyCreated(int moveId, Bundle extras) {
24861            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24862
24863            final SomeArgs args = SomeArgs.obtain();
24864            args.argi1 = moveId;
24865            args.arg2 = extras;
24866            obtainMessage(MSG_CREATED, args).sendToTarget();
24867        }
24868
24869        private void notifyStatusChanged(int moveId, int status) {
24870            notifyStatusChanged(moveId, status, -1);
24871        }
24872
24873        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24874            Slog.v(TAG, "Move " + moveId + " status " + status);
24875
24876            final SomeArgs args = SomeArgs.obtain();
24877            args.argi1 = moveId;
24878            args.argi2 = status;
24879            args.arg3 = estMillis;
24880            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24881
24882            synchronized (mLastStatus) {
24883                mLastStatus.put(moveId, status);
24884            }
24885        }
24886    }
24887
24888    private final static class OnPermissionChangeListeners extends Handler {
24889        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24890
24891        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24892                new RemoteCallbackList<>();
24893
24894        public OnPermissionChangeListeners(Looper looper) {
24895            super(looper);
24896        }
24897
24898        @Override
24899        public void handleMessage(Message msg) {
24900            switch (msg.what) {
24901                case MSG_ON_PERMISSIONS_CHANGED: {
24902                    final int uid = msg.arg1;
24903                    handleOnPermissionsChanged(uid);
24904                } break;
24905            }
24906        }
24907
24908        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24909            mPermissionListeners.register(listener);
24910
24911        }
24912
24913        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24914            mPermissionListeners.unregister(listener);
24915        }
24916
24917        public void onPermissionsChanged(int uid) {
24918            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24919                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24920            }
24921        }
24922
24923        private void handleOnPermissionsChanged(int uid) {
24924            final int count = mPermissionListeners.beginBroadcast();
24925            try {
24926                for (int i = 0; i < count; i++) {
24927                    IOnPermissionsChangeListener callback = mPermissionListeners
24928                            .getBroadcastItem(i);
24929                    try {
24930                        callback.onPermissionsChanged(uid);
24931                    } catch (RemoteException e) {
24932                        Log.e(TAG, "Permission listener is dead", e);
24933                    }
24934                }
24935            } finally {
24936                mPermissionListeners.finishBroadcast();
24937            }
24938        }
24939    }
24940
24941    private class PackageManagerNative extends IPackageManagerNative.Stub {
24942        @Override
24943        public String[] getNamesForUids(int[] uids) throws RemoteException {
24944            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24945            // massage results so they can be parsed by the native binder
24946            for (int i = results.length - 1; i >= 0; --i) {
24947                if (results[i] == null) {
24948                    results[i] = "";
24949                }
24950            }
24951            return results;
24952        }
24953    }
24954
24955    private class PackageManagerInternalImpl extends PackageManagerInternal {
24956        @Override
24957        public void setLocationPackagesProvider(PackagesProvider provider) {
24958            synchronized (mPackages) {
24959                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24960            }
24961        }
24962
24963        @Override
24964        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24965            synchronized (mPackages) {
24966                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24967            }
24968        }
24969
24970        @Override
24971        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24972            synchronized (mPackages) {
24973                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24974            }
24975        }
24976
24977        @Override
24978        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24979            synchronized (mPackages) {
24980                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24981            }
24982        }
24983
24984        @Override
24985        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24986            synchronized (mPackages) {
24987                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24988            }
24989        }
24990
24991        @Override
24992        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24993            synchronized (mPackages) {
24994                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24995            }
24996        }
24997
24998        @Override
24999        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25000            synchronized (mPackages) {
25001                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25002                        packageName, userId);
25003            }
25004        }
25005
25006        @Override
25007        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25008            synchronized (mPackages) {
25009                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25010                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25011                        packageName, userId);
25012            }
25013        }
25014
25015        @Override
25016        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25017            synchronized (mPackages) {
25018                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25019                        packageName, userId);
25020            }
25021        }
25022
25023        @Override
25024        public void setKeepUninstalledPackages(final List<String> packageList) {
25025            Preconditions.checkNotNull(packageList);
25026            List<String> removedFromList = null;
25027            synchronized (mPackages) {
25028                if (mKeepUninstalledPackages != null) {
25029                    final int packagesCount = mKeepUninstalledPackages.size();
25030                    for (int i = 0; i < packagesCount; i++) {
25031                        String oldPackage = mKeepUninstalledPackages.get(i);
25032                        if (packageList != null && packageList.contains(oldPackage)) {
25033                            continue;
25034                        }
25035                        if (removedFromList == null) {
25036                            removedFromList = new ArrayList<>();
25037                        }
25038                        removedFromList.add(oldPackage);
25039                    }
25040                }
25041                mKeepUninstalledPackages = new ArrayList<>(packageList);
25042                if (removedFromList != null) {
25043                    final int removedCount = removedFromList.size();
25044                    for (int i = 0; i < removedCount; i++) {
25045                        deletePackageIfUnusedLPr(removedFromList.get(i));
25046                    }
25047                }
25048            }
25049        }
25050
25051        @Override
25052        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25053            synchronized (mPackages) {
25054                // If we do not support permission review, done.
25055                if (!mPermissionReviewRequired) {
25056                    return false;
25057                }
25058
25059                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25060                if (packageSetting == null) {
25061                    return false;
25062                }
25063
25064                // Permission review applies only to apps not supporting the new permission model.
25065                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25066                    return false;
25067                }
25068
25069                // Legacy apps have the permission and get user consent on launch.
25070                PermissionsState permissionsState = packageSetting.getPermissionsState();
25071                return permissionsState.isPermissionReviewRequired(userId);
25072            }
25073        }
25074
25075        @Override
25076        public PackageInfo getPackageInfo(
25077                String packageName, int flags, int filterCallingUid, int userId) {
25078            return PackageManagerService.this
25079                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25080                            flags, filterCallingUid, userId);
25081        }
25082
25083        @Override
25084        public ApplicationInfo getApplicationInfo(
25085                String packageName, int flags, int filterCallingUid, int userId) {
25086            return PackageManagerService.this
25087                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25088        }
25089
25090        @Override
25091        public ActivityInfo getActivityInfo(
25092                ComponentName component, int flags, int filterCallingUid, int userId) {
25093            return PackageManagerService.this
25094                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25095        }
25096
25097        @Override
25098        public List<ResolveInfo> queryIntentActivities(
25099                Intent intent, int flags, int filterCallingUid, int userId) {
25100            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25101            return PackageManagerService.this
25102                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25103                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25104        }
25105
25106        @Override
25107        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25108                int userId) {
25109            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25110        }
25111
25112        @Override
25113        public void setDeviceAndProfileOwnerPackages(
25114                int deviceOwnerUserId, String deviceOwnerPackage,
25115                SparseArray<String> profileOwnerPackages) {
25116            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25117                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25118        }
25119
25120        @Override
25121        public boolean isPackageDataProtected(int userId, String packageName) {
25122            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25123        }
25124
25125        @Override
25126        public boolean isPackageEphemeral(int userId, String packageName) {
25127            synchronized (mPackages) {
25128                final PackageSetting ps = mSettings.mPackages.get(packageName);
25129                return ps != null ? ps.getInstantApp(userId) : false;
25130            }
25131        }
25132
25133        @Override
25134        public boolean wasPackageEverLaunched(String packageName, int userId) {
25135            synchronized (mPackages) {
25136                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25137            }
25138        }
25139
25140        @Override
25141        public void grantRuntimePermission(String packageName, String name, int userId,
25142                boolean overridePolicy) {
25143            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25144                    overridePolicy);
25145        }
25146
25147        @Override
25148        public void revokeRuntimePermission(String packageName, String name, int userId,
25149                boolean overridePolicy) {
25150            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25151                    overridePolicy);
25152        }
25153
25154        @Override
25155        public String getNameForUid(int uid) {
25156            return PackageManagerService.this.getNameForUid(uid);
25157        }
25158
25159        @Override
25160        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25161                Intent origIntent, String resolvedType, String callingPackage,
25162                Bundle verificationBundle, int userId) {
25163            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25164                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25165                    userId);
25166        }
25167
25168        @Override
25169        public void grantEphemeralAccess(int userId, Intent intent,
25170                int targetAppId, int ephemeralAppId) {
25171            synchronized (mPackages) {
25172                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25173                        targetAppId, ephemeralAppId);
25174            }
25175        }
25176
25177        @Override
25178        public boolean isInstantAppInstallerComponent(ComponentName component) {
25179            synchronized (mPackages) {
25180                return mInstantAppInstallerActivity != null
25181                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25182            }
25183        }
25184
25185        @Override
25186        public void pruneInstantApps() {
25187            mInstantAppRegistry.pruneInstantApps();
25188        }
25189
25190        @Override
25191        public String getSetupWizardPackageName() {
25192            return mSetupWizardPackage;
25193        }
25194
25195        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25196            if (policy != null) {
25197                mExternalSourcesPolicy = policy;
25198            }
25199        }
25200
25201        @Override
25202        public boolean isPackagePersistent(String packageName) {
25203            synchronized (mPackages) {
25204                PackageParser.Package pkg = mPackages.get(packageName);
25205                return pkg != null
25206                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25207                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25208                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25209                        : false;
25210            }
25211        }
25212
25213        @Override
25214        public List<PackageInfo> getOverlayPackages(int userId) {
25215            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25216            synchronized (mPackages) {
25217                for (PackageParser.Package p : mPackages.values()) {
25218                    if (p.mOverlayTarget != null) {
25219                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25220                        if (pkg != null) {
25221                            overlayPackages.add(pkg);
25222                        }
25223                    }
25224                }
25225            }
25226            return overlayPackages;
25227        }
25228
25229        @Override
25230        public List<String> getTargetPackageNames(int userId) {
25231            List<String> targetPackages = new ArrayList<>();
25232            synchronized (mPackages) {
25233                for (PackageParser.Package p : mPackages.values()) {
25234                    if (p.mOverlayTarget == null) {
25235                        targetPackages.add(p.packageName);
25236                    }
25237                }
25238            }
25239            return targetPackages;
25240        }
25241
25242        @Override
25243        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25244                @Nullable List<String> overlayPackageNames) {
25245            synchronized (mPackages) {
25246                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25247                    Slog.e(TAG, "failed to find package " + targetPackageName);
25248                    return false;
25249                }
25250                ArrayList<String> overlayPaths = null;
25251                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25252                    final int N = overlayPackageNames.size();
25253                    overlayPaths = new ArrayList<>(N);
25254                    for (int i = 0; i < N; i++) {
25255                        final String packageName = overlayPackageNames.get(i);
25256                        final PackageParser.Package pkg = mPackages.get(packageName);
25257                        if (pkg == null) {
25258                            Slog.e(TAG, "failed to find package " + packageName);
25259                            return false;
25260                        }
25261                        overlayPaths.add(pkg.baseCodePath);
25262                    }
25263                }
25264
25265                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25266                ps.setOverlayPaths(overlayPaths, userId);
25267                return true;
25268            }
25269        }
25270
25271        @Override
25272        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25273                int flags, int userId) {
25274            return resolveIntentInternal(
25275                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25276        }
25277
25278        @Override
25279        public ResolveInfo resolveService(Intent intent, String resolvedType,
25280                int flags, int userId, int callingUid) {
25281            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25282        }
25283
25284        @Override
25285        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25286            synchronized (mPackages) {
25287                mIsolatedOwners.put(isolatedUid, ownerUid);
25288            }
25289        }
25290
25291        @Override
25292        public void removeIsolatedUid(int isolatedUid) {
25293            synchronized (mPackages) {
25294                mIsolatedOwners.delete(isolatedUid);
25295            }
25296        }
25297
25298        @Override
25299        public int getUidTargetSdkVersion(int uid) {
25300            synchronized (mPackages) {
25301                return getUidTargetSdkVersionLockedLPr(uid);
25302            }
25303        }
25304
25305        @Override
25306        public boolean canAccessInstantApps(int callingUid, int userId) {
25307            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25308        }
25309    }
25310
25311    @Override
25312    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25313        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25314        synchronized (mPackages) {
25315            final long identity = Binder.clearCallingIdentity();
25316            try {
25317                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25318                        packageNames, userId);
25319            } finally {
25320                Binder.restoreCallingIdentity(identity);
25321            }
25322        }
25323    }
25324
25325    @Override
25326    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25327        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25328        synchronized (mPackages) {
25329            final long identity = Binder.clearCallingIdentity();
25330            try {
25331                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25332                        packageNames, userId);
25333            } finally {
25334                Binder.restoreCallingIdentity(identity);
25335            }
25336        }
25337    }
25338
25339    private static void enforceSystemOrPhoneCaller(String tag) {
25340        int callingUid = Binder.getCallingUid();
25341        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25342            throw new SecurityException(
25343                    "Cannot call " + tag + " from UID " + callingUid);
25344        }
25345    }
25346
25347    boolean isHistoricalPackageUsageAvailable() {
25348        return mPackageUsage.isHistoricalPackageUsageAvailable();
25349    }
25350
25351    /**
25352     * Return a <b>copy</b> of the collection of packages known to the package manager.
25353     * @return A copy of the values of mPackages.
25354     */
25355    Collection<PackageParser.Package> getPackages() {
25356        synchronized (mPackages) {
25357            return new ArrayList<>(mPackages.values());
25358        }
25359    }
25360
25361    /**
25362     * Logs process start information (including base APK hash) to the security log.
25363     * @hide
25364     */
25365    @Override
25366    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25367            String apkFile, int pid) {
25368        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25369            return;
25370        }
25371        if (!SecurityLog.isLoggingEnabled()) {
25372            return;
25373        }
25374        Bundle data = new Bundle();
25375        data.putLong("startTimestamp", System.currentTimeMillis());
25376        data.putString("processName", processName);
25377        data.putInt("uid", uid);
25378        data.putString("seinfo", seinfo);
25379        data.putString("apkFile", apkFile);
25380        data.putInt("pid", pid);
25381        Message msg = mProcessLoggingHandler.obtainMessage(
25382                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25383        msg.setData(data);
25384        mProcessLoggingHandler.sendMessage(msg);
25385    }
25386
25387    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25388        return mCompilerStats.getPackageStats(pkgName);
25389    }
25390
25391    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25392        return getOrCreateCompilerPackageStats(pkg.packageName);
25393    }
25394
25395    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25396        return mCompilerStats.getOrCreatePackageStats(pkgName);
25397    }
25398
25399    public void deleteCompilerPackageStats(String pkgName) {
25400        mCompilerStats.deletePackageStats(pkgName);
25401    }
25402
25403    @Override
25404    public int getInstallReason(String packageName, int userId) {
25405        final int callingUid = Binder.getCallingUid();
25406        enforceCrossUserPermission(callingUid, userId,
25407                true /* requireFullPermission */, false /* checkShell */,
25408                "get install reason");
25409        synchronized (mPackages) {
25410            final PackageSetting ps = mSettings.mPackages.get(packageName);
25411            if (filterAppAccessLPr(ps, callingUid, userId)) {
25412                return PackageManager.INSTALL_REASON_UNKNOWN;
25413            }
25414            if (ps != null) {
25415                return ps.getInstallReason(userId);
25416            }
25417        }
25418        return PackageManager.INSTALL_REASON_UNKNOWN;
25419    }
25420
25421    @Override
25422    public boolean canRequestPackageInstalls(String packageName, int userId) {
25423        return canRequestPackageInstallsInternal(packageName, 0, userId,
25424                true /* throwIfPermNotDeclared*/);
25425    }
25426
25427    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25428            boolean throwIfPermNotDeclared) {
25429        int callingUid = Binder.getCallingUid();
25430        int uid = getPackageUid(packageName, 0, userId);
25431        if (callingUid != uid && callingUid != Process.ROOT_UID
25432                && callingUid != Process.SYSTEM_UID) {
25433            throw new SecurityException(
25434                    "Caller uid " + callingUid + " does not own package " + packageName);
25435        }
25436        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25437        if (info == null) {
25438            return false;
25439        }
25440        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25441            return false;
25442        }
25443        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25444        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25445        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25446            if (throwIfPermNotDeclared) {
25447                throw new SecurityException("Need to declare " + appOpPermission
25448                        + " to call this api");
25449            } else {
25450                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25451                return false;
25452            }
25453        }
25454        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25455            return false;
25456        }
25457        if (mExternalSourcesPolicy != null) {
25458            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25459            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25460                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25461            }
25462        }
25463        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25464    }
25465
25466    @Override
25467    public ComponentName getInstantAppResolverSettingsComponent() {
25468        return mInstantAppResolverSettingsComponent;
25469    }
25470
25471    @Override
25472    public ComponentName getInstantAppInstallerComponent() {
25473        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25474            return null;
25475        }
25476        return mInstantAppInstallerActivity == null
25477                ? null : mInstantAppInstallerActivity.getComponentName();
25478    }
25479
25480    @Override
25481    public String getInstantAppAndroidId(String packageName, int userId) {
25482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25483                "getInstantAppAndroidId");
25484        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25485                true /* requireFullPermission */, false /* checkShell */,
25486                "getInstantAppAndroidId");
25487        // Make sure the target is an Instant App.
25488        if (!isInstantApp(packageName, userId)) {
25489            return null;
25490        }
25491        synchronized (mPackages) {
25492            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25493        }
25494    }
25495
25496    boolean canHaveOatDir(String packageName) {
25497        synchronized (mPackages) {
25498            PackageParser.Package p = mPackages.get(packageName);
25499            if (p == null) {
25500                return false;
25501            }
25502            return p.canHaveOatDir();
25503        }
25504    }
25505
25506    private String getOatDir(PackageParser.Package pkg) {
25507        if (!pkg.canHaveOatDir()) {
25508            return null;
25509        }
25510        File codePath = new File(pkg.codePath);
25511        if (codePath.isDirectory()) {
25512            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25513        }
25514        return null;
25515    }
25516
25517    void deleteOatArtifactsOfPackage(String packageName) {
25518        final String[] instructionSets;
25519        final List<String> codePaths;
25520        final String oatDir;
25521        final PackageParser.Package pkg;
25522        synchronized (mPackages) {
25523            pkg = mPackages.get(packageName);
25524        }
25525        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25526        codePaths = pkg.getAllCodePaths();
25527        oatDir = getOatDir(pkg);
25528
25529        for (String codePath : codePaths) {
25530            for (String isa : instructionSets) {
25531                try {
25532                    mInstaller.deleteOdex(codePath, isa, oatDir);
25533                } catch (InstallerException e) {
25534                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25535                }
25536            }
25537        }
25538    }
25539
25540    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25541        Set<String> unusedPackages = new HashSet<>();
25542        long currentTimeInMillis = System.currentTimeMillis();
25543        synchronized (mPackages) {
25544            for (PackageParser.Package pkg : mPackages.values()) {
25545                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25546                if (ps == null) {
25547                    continue;
25548                }
25549                PackageDexUsage.PackageUseInfo packageUseInfo =
25550                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25551                if (PackageManagerServiceUtils
25552                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25553                                downgradeTimeThresholdMillis, packageUseInfo,
25554                                pkg.getLatestPackageUseTimeInMills(),
25555                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25556                    unusedPackages.add(pkg.packageName);
25557                }
25558            }
25559        }
25560        return unusedPackages;
25561    }
25562}
25563
25564interface PackageSender {
25565    void sendPackageBroadcast(final String action, final String pkg,
25566        final Bundle extras, final int flags, final String targetPkg,
25567        final IIntentReceiver finishedReceiver, final int[] userIds);
25568    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25569        boolean includeStopped, int appId, int... userIds);
25570}
25571