PackageManagerService.java revision 05941b396a44bd81c143b727e5c4c630212228e0
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_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
109
110import android.Manifest;
111import android.annotation.IntDef;
112import android.annotation.NonNull;
113import android.annotation.Nullable;
114import android.app.ActivityManager;
115import android.app.AppOpsManager;
116import android.app.IActivityManager;
117import android.app.ResourcesManager;
118import android.app.admin.IDevicePolicyManager;
119import android.app.admin.SecurityLog;
120import android.app.backup.IBackupManager;
121import android.content.BroadcastReceiver;
122import android.content.ComponentName;
123import android.content.ContentResolver;
124import android.content.Context;
125import android.content.IIntentReceiver;
126import android.content.Intent;
127import android.content.IntentFilter;
128import android.content.IntentSender;
129import android.content.IntentSender.SendIntentException;
130import android.content.ServiceConnection;
131import android.content.pm.ActivityInfo;
132import android.content.pm.ApplicationInfo;
133import android.content.pm.AppsQueryHelper;
134import android.content.pm.AuxiliaryResolveInfo;
135import android.content.pm.ChangedPackages;
136import android.content.pm.ComponentInfo;
137import android.content.pm.FallbackCategoryProvider;
138import android.content.pm.FeatureInfo;
139import android.content.pm.IDexModuleRegisterCallback;
140import android.content.pm.IOnPermissionsChangeListener;
141import android.content.pm.IPackageDataObserver;
142import android.content.pm.IPackageDeleteObserver;
143import android.content.pm.IPackageDeleteObserver2;
144import android.content.pm.IPackageInstallObserver2;
145import android.content.pm.IPackageInstaller;
146import android.content.pm.IPackageManager;
147import android.content.pm.IPackageManagerNative;
148import android.content.pm.IPackageMoveObserver;
149import android.content.pm.IPackageStatsObserver;
150import android.content.pm.InstantAppInfo;
151import android.content.pm.InstantAppRequest;
152import android.content.pm.InstantAppResolveInfo;
153import android.content.pm.InstrumentationInfo;
154import android.content.pm.IntentFilterVerificationInfo;
155import android.content.pm.KeySet;
156import android.content.pm.PackageCleanItem;
157import android.content.pm.PackageInfo;
158import android.content.pm.PackageInfoLite;
159import android.content.pm.PackageInstaller;
160import android.content.pm.PackageManager;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageParser;
164import android.content.pm.PackageParser.ActivityIntentInfo;
165import android.content.pm.PackageParser.Package;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.TimingsTraceLog;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.Settings.DatabaseVersion;
286import com.android.server.pm.Settings.VersionInfo;
287import com.android.server.pm.dex.DexManager;
288import com.android.server.pm.dex.DexoptOptions;
289import com.android.server.pm.dex.PackageDexUsage;
290import com.android.server.pm.permission.BasePermission;
291import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
292import com.android.server.pm.permission.PermissionManagerService;
293import com.android.server.pm.permission.PermissionManagerInternal;
294import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
295import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
296import com.android.server.pm.permission.PermissionsState;
297import com.android.server.pm.permission.PermissionsState.PermissionState;
298import com.android.server.storage.DeviceStorageMonitorInternal;
299
300import dalvik.system.CloseGuard;
301import dalvik.system.DexFile;
302import dalvik.system.VMRuntime;
303
304import libcore.io.IoUtils;
305import libcore.io.Streams;
306import libcore.util.EmptyArray;
307
308import org.xmlpull.v1.XmlPullParser;
309import org.xmlpull.v1.XmlPullParserException;
310import org.xmlpull.v1.XmlSerializer;
311
312import java.io.BufferedOutputStream;
313import java.io.BufferedReader;
314import java.io.ByteArrayInputStream;
315import java.io.ByteArrayOutputStream;
316import java.io.File;
317import java.io.FileDescriptor;
318import java.io.FileInputStream;
319import java.io.FileOutputStream;
320import java.io.FileReader;
321import java.io.FilenameFilter;
322import java.io.IOException;
323import java.io.InputStream;
324import java.io.OutputStream;
325import java.io.PrintWriter;
326import java.lang.annotation.Retention;
327import java.lang.annotation.RetentionPolicy;
328import java.nio.charset.StandardCharsets;
329import java.security.DigestInputStream;
330import java.security.MessageDigest;
331import java.security.NoSuchAlgorithmException;
332import java.security.PublicKey;
333import java.security.SecureRandom;
334import java.security.cert.Certificate;
335import java.security.cert.CertificateEncodingException;
336import java.security.cert.CertificateException;
337import java.text.SimpleDateFormat;
338import java.util.ArrayList;
339import java.util.Arrays;
340import java.util.Collection;
341import java.util.Collections;
342import java.util.Comparator;
343import java.util.Date;
344import java.util.HashMap;
345import java.util.HashSet;
346import java.util.Iterator;
347import java.util.List;
348import java.util.Map;
349import java.util.Objects;
350import java.util.Set;
351import java.util.concurrent.CountDownLatch;
352import java.util.concurrent.Future;
353import java.util.concurrent.TimeUnit;
354import java.util.concurrent.atomic.AtomicBoolean;
355import java.util.concurrent.atomic.AtomicInteger;
356import java.util.zip.GZIPInputStream;
357
358/**
359 * Keep track of all those APKs everywhere.
360 * <p>
361 * Internally there are two important locks:
362 * <ul>
363 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
364 * and other related state. It is a fine-grained lock that should only be held
365 * momentarily, as it's one of the most contended locks in the system.
366 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
367 * operations typically involve heavy lifting of application data on disk. Since
368 * {@code installd} is single-threaded, and it's operations can often be slow,
369 * this lock should never be acquired while already holding {@link #mPackages}.
370 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
371 * holding {@link #mInstallLock}.
372 * </ul>
373 * Many internal methods rely on the caller to hold the appropriate locks, and
374 * this contract is expressed through method name suffixes:
375 * <ul>
376 * <li>fooLI(): the caller must hold {@link #mInstallLock}
377 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
378 * being modified must be frozen
379 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
380 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
381 * </ul>
382 * <p>
383 * Because this class is very central to the platform's security; please run all
384 * CTS and unit tests whenever making modifications:
385 *
386 * <pre>
387 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
388 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
389 * </pre>
390 */
391public class PackageManagerService extends IPackageManager.Stub
392        implements PackageSender {
393    static final String TAG = "PackageManager";
394    public static final boolean DEBUG_SETTINGS = false;
395    static final boolean DEBUG_PREFERRED = false;
396    static final boolean DEBUG_UPGRADE = false;
397    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
398    private static final boolean DEBUG_BACKUP = false;
399    private static final boolean DEBUG_INSTALL = false;
400    private static final boolean DEBUG_REMOVE = false;
401    private static final boolean DEBUG_BROADCASTS = false;
402    private static final boolean DEBUG_SHOW_INFO = false;
403    private static final boolean DEBUG_PACKAGE_INFO = false;
404    private static final boolean DEBUG_INTENT_MATCHING = false;
405    public static final boolean DEBUG_PACKAGE_SCANNING = false;
406    private static final boolean DEBUG_VERIFY = false;
407    private static final boolean DEBUG_FILTERS = false;
408    private static final boolean DEBUG_PERMISSIONS = false;
409    private static final boolean DEBUG_SHARED_LIBRARIES = false;
410    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
411
412    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
413    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
414    // user, but by default initialize to this.
415    public static final boolean DEBUG_DEXOPT = false;
416
417    private static final boolean DEBUG_ABI_SELECTION = false;
418    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
419    private static final boolean DEBUG_TRIAGED_MISSING = false;
420    private static final boolean DEBUG_APP_DATA = false;
421
422    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
423    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
424
425    private static final boolean HIDE_EPHEMERAL_APIS = false;
426
427    private static final boolean ENABLE_FREE_CACHE_V2 =
428            SystemProperties.getBoolean("fw.free_cache_v2", true);
429
430    private static final int RADIO_UID = Process.PHONE_UID;
431    private static final int LOG_UID = Process.LOG_UID;
432    private static final int NFC_UID = Process.NFC_UID;
433    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
434    private static final int SHELL_UID = Process.SHELL_UID;
435
436    // Suffix used during package installation when copying/moving
437    // package apks to install directory.
438    private static final String INSTALL_PACKAGE_SUFFIX = "-";
439
440    static final int SCAN_NO_DEX = 1<<1;
441    static final int SCAN_FORCE_DEX = 1<<2;
442    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
443    static final int SCAN_NEW_INSTALL = 1<<4;
444    static final int SCAN_UPDATE_TIME = 1<<5;
445    static final int SCAN_BOOTING = 1<<6;
446    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
447    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
448    static final int SCAN_REPLACING = 1<<9;
449    static final int SCAN_REQUIRE_KNOWN = 1<<10;
450    static final int SCAN_MOVE = 1<<11;
451    static final int SCAN_INITIAL = 1<<12;
452    static final int SCAN_CHECK_ONLY = 1<<13;
453    static final int SCAN_DONT_KILL_APP = 1<<14;
454    static final int SCAN_IGNORE_FROZEN = 1<<15;
455    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
456    static final int SCAN_AS_INSTANT_APP = 1<<17;
457    static final int SCAN_AS_FULL_APP = 1<<18;
458    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
459    /** Should not be with the scan flags */
460    static final int FLAGS_REMOVE_CHATTY = 1<<31;
461
462    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
463    /** Extension of the compressed packages */
464    private final static String COMPRESSED_EXTENSION = ".gz";
465    /** Suffix of stub packages on the system partition */
466    private final static String STUB_SUFFIX = "-Stub";
467
468    private static final int[] EMPTY_INT_ARRAY = new int[0];
469
470    private static final int TYPE_UNKNOWN = 0;
471    private static final int TYPE_ACTIVITY = 1;
472    private static final int TYPE_RECEIVER = 2;
473    private static final int TYPE_SERVICE = 3;
474    private static final int TYPE_PROVIDER = 4;
475    @IntDef(prefix = { "TYPE_" }, value = {
476            TYPE_UNKNOWN,
477            TYPE_ACTIVITY,
478            TYPE_RECEIVER,
479            TYPE_SERVICE,
480            TYPE_PROVIDER,
481    })
482    @Retention(RetentionPolicy.SOURCE)
483    public @interface ComponentType {}
484
485    /**
486     * Timeout (in milliseconds) after which the watchdog should declare that
487     * our handler thread is wedged.  The usual default for such things is one
488     * minute but we sometimes do very lengthy I/O operations on this thread,
489     * such as installing multi-gigabyte applications, so ours needs to be longer.
490     */
491    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
492
493    /**
494     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
495     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
496     * settings entry if available, otherwise we use the hardcoded default.  If it's been
497     * more than this long since the last fstrim, we force one during the boot sequence.
498     *
499     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
500     * one gets run at the next available charging+idle time.  This final mandatory
501     * no-fstrim check kicks in only of the other scheduling criteria is never met.
502     */
503    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
504
505    /**
506     * Whether verification is enabled by default.
507     */
508    private static final boolean DEFAULT_VERIFY_ENABLE = true;
509
510    /**
511     * The default maximum time to wait for the verification agent to return in
512     * milliseconds.
513     */
514    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
515
516    /**
517     * The default response for package verification timeout.
518     *
519     * This can be either PackageManager.VERIFICATION_ALLOW or
520     * PackageManager.VERIFICATION_REJECT.
521     */
522    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
523
524    static final String PLATFORM_PACKAGE_NAME = "android";
525
526    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
527
528    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
529            DEFAULT_CONTAINER_PACKAGE,
530            "com.android.defcontainer.DefaultContainerService");
531
532    private static final String KILL_APP_REASON_GIDS_CHANGED =
533            "permission grant or revoke changed gids";
534
535    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
536            "permissions revoked";
537
538    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
539
540    private static final String PACKAGE_SCHEME = "package";
541
542    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
543
544    /** Permission grant: not grant the permission. */
545    private static final int GRANT_DENIED = 1;
546
547    /** Permission grant: grant the permission as an install permission. */
548    private static final int GRANT_INSTALL = 2;
549
550    /** Permission grant: grant the permission as a runtime one. */
551    private static final int GRANT_RUNTIME = 3;
552
553    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
554    private static final int GRANT_UPGRADE = 4;
555
556    /** Canonical intent used to identify what counts as a "web browser" app */
557    private static final Intent sBrowserIntent;
558    static {
559        sBrowserIntent = new Intent();
560        sBrowserIntent.setAction(Intent.ACTION_VIEW);
561        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
562        sBrowserIntent.setData(Uri.parse("http:"));
563    }
564
565    /**
566     * The set of all protected actions [i.e. those actions for which a high priority
567     * intent filter is disallowed].
568     */
569    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
570    static {
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
574        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
575    }
576
577    // Compilation reasons.
578    public static final int REASON_FIRST_BOOT = 0;
579    public static final int REASON_BOOT = 1;
580    public static final int REASON_INSTALL = 2;
581    public static final int REASON_BACKGROUND_DEXOPT = 3;
582    public static final int REASON_AB_OTA = 4;
583    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
584    public static final int REASON_SHARED = 6;
585
586    public static final int REASON_LAST = REASON_SHARED;
587
588    /** All dangerous permission names in the same order as the events in MetricsEvent */
589    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
590            Manifest.permission.READ_CALENDAR,
591            Manifest.permission.WRITE_CALENDAR,
592            Manifest.permission.CAMERA,
593            Manifest.permission.READ_CONTACTS,
594            Manifest.permission.WRITE_CONTACTS,
595            Manifest.permission.GET_ACCOUNTS,
596            Manifest.permission.ACCESS_FINE_LOCATION,
597            Manifest.permission.ACCESS_COARSE_LOCATION,
598            Manifest.permission.RECORD_AUDIO,
599            Manifest.permission.READ_PHONE_STATE,
600            Manifest.permission.CALL_PHONE,
601            Manifest.permission.READ_CALL_LOG,
602            Manifest.permission.WRITE_CALL_LOG,
603            Manifest.permission.ADD_VOICEMAIL,
604            Manifest.permission.USE_SIP,
605            Manifest.permission.PROCESS_OUTGOING_CALLS,
606            Manifest.permission.READ_CELL_BROADCASTS,
607            Manifest.permission.BODY_SENSORS,
608            Manifest.permission.SEND_SMS,
609            Manifest.permission.RECEIVE_SMS,
610            Manifest.permission.READ_SMS,
611            Manifest.permission.RECEIVE_WAP_PUSH,
612            Manifest.permission.RECEIVE_MMS,
613            Manifest.permission.READ_EXTERNAL_STORAGE,
614            Manifest.permission.WRITE_EXTERNAL_STORAGE,
615            Manifest.permission.READ_PHONE_NUMBERS,
616            Manifest.permission.ANSWER_PHONE_CALLS);
617
618
619    /**
620     * Version number for the package parser cache. Increment this whenever the format or
621     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
622     */
623    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
624
625    /**
626     * Whether the package parser cache is enabled.
627     */
628    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed third-party apps stored */
667    final File mAppInstallDir;
668
669    /**
670     * Directory to which applications installed internally have their
671     * 32 bit native libraries copied.
672     */
673    private File mAppLib32InstallDir;
674
675    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
676    // apps.
677    final File mDrmAppPrivateInstallDir;
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    // System configuration read by SystemConfig.
756    final int[] mGlobalGids;
757    final SparseArray<ArraySet<String>> mSystemPermissions;
758    @GuardedBy("mAvailableFeatures")
759    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
760
761    // If mac_permissions.xml was found for seinfo labeling.
762    boolean mFoundPolicyFile;
763
764    private final InstantAppRegistry mInstantAppRegistry;
765
766    @GuardedBy("mPackages")
767    int mChangedPackagesSequenceNumber;
768    /**
769     * List of changed [installed, removed or updated] packages.
770     * mapping from user id -> sequence number -> package name
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
774    /**
775     * The sequence number of the last change to a package.
776     * mapping from user id -> package name -> sequence number
777     */
778    @GuardedBy("mPackages")
779    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
780
781    class PackageParserCallback implements PackageParser.Callback {
782        @Override public final boolean hasFeature(String feature) {
783            return PackageManagerService.this.hasSystemFeature(feature, 0);
784        }
785
786        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
787                Collection<PackageParser.Package> allPackages, String targetPackageName) {
788            List<PackageParser.Package> overlayPackages = null;
789            for (PackageParser.Package p : allPackages) {
790                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
791                    if (overlayPackages == null) {
792                        overlayPackages = new ArrayList<PackageParser.Package>();
793                    }
794                    overlayPackages.add(p);
795                }
796            }
797            if (overlayPackages != null) {
798                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
799                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
800                        return p1.mOverlayPriority - p2.mOverlayPriority;
801                    }
802                };
803                Collections.sort(overlayPackages, cmp);
804            }
805            return overlayPackages;
806        }
807
808        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
809                String targetPackageName, String targetPath) {
810            if ("android".equals(targetPackageName)) {
811                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
812                // native AssetManager.
813                return null;
814            }
815            List<PackageParser.Package> overlayPackages =
816                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
817            if (overlayPackages == null || overlayPackages.isEmpty()) {
818                return null;
819            }
820            List<String> overlayPathList = null;
821            for (PackageParser.Package overlayPackage : overlayPackages) {
822                if (targetPath == null) {
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                    continue;
828                }
829
830                try {
831                    // Creates idmaps for system to parse correctly the Android manifest of the
832                    // target package.
833                    //
834                    // OverlayManagerService will update each of them with a correct gid from its
835                    // target package app id.
836                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
837                            UserHandle.getSharedAppGid(
838                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
839                    if (overlayPathList == null) {
840                        overlayPathList = new ArrayList<String>();
841                    }
842                    overlayPathList.add(overlayPackage.baseCodePath);
843                } catch (InstallerException e) {
844                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
845                            overlayPackage.baseCodePath);
846                }
847            }
848            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
849        }
850
851        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
852            synchronized (mPackages) {
853                return getStaticOverlayPathsLocked(
854                        mPackages.values(), targetPackageName, targetPath);
855            }
856        }
857
858        @Override public final String[] getOverlayApks(String targetPackageName) {
859            return getStaticOverlayPaths(targetPackageName, null);
860        }
861
862        @Override public final String[] getOverlayPaths(String targetPackageName,
863                String targetPath) {
864            return getStaticOverlayPaths(targetPackageName, targetPath);
865        }
866    }
867
868    class ParallelPackageParserCallback extends PackageParserCallback {
869        List<PackageParser.Package> mOverlayPackages = null;
870
871        void findStaticOverlayPackages() {
872            synchronized (mPackages) {
873                for (PackageParser.Package p : mPackages.values()) {
874                    if (p.mIsStaticOverlay) {
875                        if (mOverlayPackages == null) {
876                            mOverlayPackages = new ArrayList<PackageParser.Package>();
877                        }
878                        mOverlayPackages.add(p);
879                    }
880                }
881            }
882        }
883
884        @Override
885        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
886            // We can trust mOverlayPackages without holding mPackages because package uninstall
887            // can't happen while running parallel parsing.
888            // Moreover holding mPackages on each parsing thread causes dead-lock.
889            return mOverlayPackages == null ? null :
890                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
891        }
892    }
893
894    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
895    final ParallelPackageParserCallback mParallelPackageParserCallback =
896            new ParallelPackageParserCallback();
897
898    public static final class SharedLibraryEntry {
899        public final @Nullable String path;
900        public final @Nullable String apk;
901        public final @NonNull SharedLibraryInfo info;
902
903        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
904                String declaringPackageName, int declaringPackageVersionCode) {
905            path = _path;
906            apk = _apk;
907            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
908                    declaringPackageName, declaringPackageVersionCode), null);
909        }
910    }
911
912    // Currently known shared libraries.
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
915            new ArrayMap<>();
916
917    // All available activities, for your resolving pleasure.
918    final ActivityIntentResolver mActivities =
919            new ActivityIntentResolver();
920
921    // All available receivers, for your resolving pleasure.
922    final ActivityIntentResolver mReceivers =
923            new ActivityIntentResolver();
924
925    // All available services, for your resolving pleasure.
926    final ServiceIntentResolver mServices = new ServiceIntentResolver();
927
928    // All available providers, for your resolving pleasure.
929    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
930
931    // Mapping from provider base names (first directory in content URI codePath)
932    // to the provider information.
933    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
934            new ArrayMap<String, PackageParser.Provider>();
935
936    // Mapping from instrumentation class names to info about them.
937    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
938            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
939
940    // Mapping from permission names to info about them.
941    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
942            new ArrayMap<String, PackageParser.PermissionGroup>();
943
944    // Packages whose data we have transfered into another package, thus
945    // should no longer exist.
946    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
947
948    // Broadcast actions that are only available to the system.
949    @GuardedBy("mProtectedBroadcasts")
950    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
951
952    /** List of packages waiting for verification. */
953    final SparseArray<PackageVerificationState> mPendingVerification
954            = new SparseArray<PackageVerificationState>();
955
956    /** Set of packages associated with each app op permission. */
957    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
958
959    final PackageInstallerService mInstallerService;
960
961    private final PackageDexOptimizer mPackageDexOptimizer;
962    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
963    // is used by other apps).
964    private final DexManager mDexManager;
965
966    private AtomicInteger mNextMoveId = new AtomicInteger();
967    private final MoveCallbacks mMoveCallbacks;
968
969    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970
971    // Cache of users who need badging.
972    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973
974    /** Token for keys in mPendingVerification. */
975    private int mPendingVerificationToken = 0;
976
977    volatile boolean mSystemReady;
978    volatile boolean mSafeMode;
979    volatile boolean mHasSystemUidErrors;
980    private volatile boolean mEphemeralAppsDisabled;
981
982    ApplicationInfo mAndroidApplication;
983    final ActivityInfo mResolveActivity = new ActivityInfo();
984    final ResolveInfo mResolveInfo = new ResolveInfo();
985    ComponentName mResolveComponentName;
986    PackageParser.Package mPlatformPackage;
987    ComponentName mCustomResolverComponentName;
988
989    boolean mResolverReplaced = false;
990
991    private final @Nullable ComponentName mIntentFilterVerifierComponent;
992    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993
994    private int mIntentFilterVerificationToken = 0;
995
996    /** The service connection to the ephemeral resolver */
997    final EphemeralResolverConnection mInstantAppResolverConnection;
998    /** Component used to show resolver settings for Instant Apps */
999    final ComponentName mInstantAppResolverSettingsComponent;
1000
1001    /** Activity used to install instant applications */
1002    ActivityInfo mInstantAppInstallerActivity;
1003    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004
1005    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1006            = new SparseArray<IntentFilterVerificationState>();
1007
1008    // TODO remove this and go through mPermissonManager directly
1009    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1010    private final PermissionManagerInternal mPermissionManager;
1011
1012    // List of packages names to keep cached, even if they are uninstalled for all users
1013    private List<String> mKeepUninstalledPackages;
1014
1015    private UserManagerInternal mUserManagerInternal;
1016
1017    private DeviceIdleController.LocalService mDeviceIdleController;
1018
1019    private File mCacheDir;
1020
1021    private ArraySet<String> mPrivappPermissionsViolations;
1022
1023    private Future<?> mPrepareAppDataFuture;
1024
1025    private static class IFVerificationParams {
1026        PackageParser.Package pkg;
1027        boolean replacing;
1028        int userId;
1029        int verifierUid;
1030
1031        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1032                int _userId, int _verifierUid) {
1033            pkg = _pkg;
1034            replacing = _replacing;
1035            userId = _userId;
1036            replacing = _replacing;
1037            verifierUid = _verifierUid;
1038        }
1039    }
1040
1041    private interface IntentFilterVerifier<T extends IntentFilter> {
1042        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1043                                               T filter, String packageName);
1044        void startVerifications(int userId);
1045        void receiveVerificationResponse(int verificationId);
1046    }
1047
1048    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1049        private Context mContext;
1050        private ComponentName mIntentFilterVerifierComponent;
1051        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1052
1053        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1054            mContext = context;
1055            mIntentFilterVerifierComponent = verifierComponent;
1056        }
1057
1058        private String getDefaultScheme() {
1059            return IntentFilter.SCHEME_HTTPS;
1060        }
1061
1062        @Override
1063        public void startVerifications(int userId) {
1064            // Launch verifications requests
1065            int count = mCurrentIntentFilterVerifications.size();
1066            for (int n=0; n<count; n++) {
1067                int verificationId = mCurrentIntentFilterVerifications.get(n);
1068                final IntentFilterVerificationState ivs =
1069                        mIntentFilterVerificationStates.get(verificationId);
1070
1071                String packageName = ivs.getPackageName();
1072
1073                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1074                final int filterCount = filters.size();
1075                ArraySet<String> domainsSet = new ArraySet<>();
1076                for (int m=0; m<filterCount; m++) {
1077                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1078                    domainsSet.addAll(filter.getHostsList());
1079                }
1080                synchronized (mPackages) {
1081                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1082                            packageName, domainsSet) != null) {
1083                        scheduleWriteSettingsLocked();
1084                    }
1085                }
1086                sendVerificationRequest(verificationId, ivs);
1087            }
1088            mCurrentIntentFilterVerifications.clear();
1089        }
1090
1091        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1092            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1095                    verificationId);
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1098                    getDefaultScheme());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1101                    ivs.getHostsString());
1102            verificationIntent.putExtra(
1103                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1104                    ivs.getPackageName());
1105            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1106            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1107
1108            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1109            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1110                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1111                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1112
1113            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Sending IntentFilter verification broadcast");
1116        }
1117
1118        public void receiveVerificationResponse(int verificationId) {
1119            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1120
1121            final boolean verified = ivs.isVerified();
1122
1123            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1124            final int count = filters.size();
1125            if (DEBUG_DOMAIN_VERIFICATION) {
1126                Slog.i(TAG, "Received verification response " + verificationId
1127                        + " for " + count + " filters, verified=" + verified);
1128            }
1129            for (int n=0; n<count; n++) {
1130                PackageParser.ActivityIntentInfo filter = filters.get(n);
1131                filter.setVerified(verified);
1132
1133                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1134                        + " verified with result:" + verified + " and hosts:"
1135                        + ivs.getHostsString());
1136            }
1137
1138            mIntentFilterVerificationStates.remove(verificationId);
1139
1140            final String packageName = ivs.getPackageName();
1141            IntentFilterVerificationInfo ivi = null;
1142
1143            synchronized (mPackages) {
1144                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1145            }
1146            if (ivi == null) {
1147                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1148                        + verificationId + " packageName:" + packageName);
1149                return;
1150            }
1151            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1152                    "Updating IntentFilterVerificationInfo for package " + packageName
1153                            +" verificationId:" + verificationId);
1154
1155            synchronized (mPackages) {
1156                if (verified) {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1158                } else {
1159                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1160                }
1161                scheduleWriteSettingsLocked();
1162
1163                final int userId = ivs.getUserId();
1164                if (userId != UserHandle.USER_ALL) {
1165                    final int userStatus =
1166                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1167
1168                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1169                    boolean needUpdate = false;
1170
1171                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1172                    // already been set by the User thru the Disambiguation dialog
1173                    switch (userStatus) {
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                            } else {
1178                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1179                            }
1180                            needUpdate = true;
1181                            break;
1182
1183                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1184                            if (verified) {
1185                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1186                                needUpdate = true;
1187                            }
1188                            break;
1189
1190                        default:
1191                            // Nothing to do
1192                    }
1193
1194                    if (needUpdate) {
1195                        mSettings.updateIntentFilterVerificationStatusLPw(
1196                                packageName, updatedStatus, userId);
1197                        scheduleWritePackageRestrictionsLocked(userId);
1198                    }
1199                }
1200            }
1201        }
1202
1203        @Override
1204        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1205                    ActivityIntentInfo filter, String packageName) {
1206            if (!hasValidDomains(filter)) {
1207                return false;
1208            }
1209            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1210            if (ivs == null) {
1211                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1212                        packageName);
1213            }
1214            if (DEBUG_DOMAIN_VERIFICATION) {
1215                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1216            }
1217            ivs.addFilter(filter);
1218            return true;
1219        }
1220
1221        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1222                int userId, int verificationId, String packageName) {
1223            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1224                    verifierUid, userId, packageName);
1225            ivs.setPendingState();
1226            synchronized (mPackages) {
1227                mIntentFilterVerificationStates.append(verificationId, ivs);
1228                mCurrentIntentFilterVerifications.add(verificationId);
1229            }
1230            return ivs;
1231        }
1232    }
1233
1234    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1235        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1236                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1237                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1238    }
1239
1240    // Set of pending broadcasts for aggregating enable/disable of components.
1241    static class PendingPackageBroadcasts {
1242        // for each user id, a map of <package name -> components within that package>
1243        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1244
1245        public PendingPackageBroadcasts() {
1246            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1247        }
1248
1249        public ArrayList<String> get(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            return packages.get(packageName);
1252        }
1253
1254        public void put(int userId, String packageName, ArrayList<String> components) {
1255            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1256            packages.put(packageName, components);
1257        }
1258
1259        public void remove(int userId, String packageName) {
1260            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1261            if (packages != null) {
1262                packages.remove(packageName);
1263            }
1264        }
1265
1266        public void remove(int userId) {
1267            mUidMap.remove(userId);
1268        }
1269
1270        public int userIdCount() {
1271            return mUidMap.size();
1272        }
1273
1274        public int userIdAt(int n) {
1275            return mUidMap.keyAt(n);
1276        }
1277
1278        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1279            return mUidMap.get(userId);
1280        }
1281
1282        public int size() {
1283            // total number of pending broadcast entries across all userIds
1284            int num = 0;
1285            for (int i = 0; i< mUidMap.size(); i++) {
1286                num += mUidMap.valueAt(i).size();
1287            }
1288            return num;
1289        }
1290
1291        public void clear() {
1292            mUidMap.clear();
1293        }
1294
1295        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1296            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1297            if (map == null) {
1298                map = new ArrayMap<String, ArrayList<String>>();
1299                mUidMap.put(userId, map);
1300            }
1301            return map;
1302        }
1303    }
1304    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1305
1306    // Service Connection to remote media container service to copy
1307    // package uri's from external media onto secure containers
1308    // or internal storage.
1309    private IMediaContainerService mContainerService = null;
1310
1311    static final int SEND_PENDING_BROADCAST = 1;
1312    static final int MCS_BOUND = 3;
1313    static final int END_COPY = 4;
1314    static final int INIT_COPY = 5;
1315    static final int MCS_UNBIND = 6;
1316    static final int START_CLEANING_PACKAGE = 7;
1317    static final int FIND_INSTALL_LOC = 8;
1318    static final int POST_INSTALL = 9;
1319    static final int MCS_RECONNECT = 10;
1320    static final int MCS_GIVE_UP = 11;
1321    static final int WRITE_SETTINGS = 13;
1322    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1323    static final int PACKAGE_VERIFIED = 15;
1324    static final int CHECK_PENDING_VERIFICATION = 16;
1325    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1326    static final int INTENT_FILTER_VERIFIED = 18;
1327    static final int WRITE_PACKAGE_LIST = 19;
1328    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1329
1330    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1331
1332    // Delay time in millisecs
1333    static final int BROADCAST_DELAY = 10 * 1000;
1334
1335    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1336            2 * 60 * 60 * 1000L; /* two hours */
1337
1338    static UserManagerService sUserManager;
1339
1340    // Stores a list of users whose package restrictions file needs to be updated
1341    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1342
1343    final private DefaultContainerConnection mDefContainerConn =
1344            new DefaultContainerConnection();
1345    class DefaultContainerConnection implements ServiceConnection {
1346        public void onServiceConnected(ComponentName name, IBinder service) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1348            final IMediaContainerService imcs = IMediaContainerService.Stub
1349                    .asInterface(Binder.allowBlocking(service));
1350            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1351        }
1352
1353        public void onServiceDisconnected(ComponentName name) {
1354            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1355        }
1356    }
1357
1358    // Recordkeeping of restore-after-install operations that are currently in flight
1359    // between the Package Manager and the Backup Manager
1360    static class PostInstallData {
1361        public InstallArgs args;
1362        public PackageInstalledInfo res;
1363
1364        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1365            args = _a;
1366            res = _r;
1367        }
1368    }
1369
1370    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1371    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1372
1373    // XML tags for backup/restore of various bits of state
1374    private static final String TAG_PREFERRED_BACKUP = "pa";
1375    private static final String TAG_DEFAULT_APPS = "da";
1376    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1377
1378    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1379    private static final String TAG_ALL_GRANTS = "rt-grants";
1380    private static final String TAG_GRANT = "grant";
1381    private static final String ATTR_PACKAGE_NAME = "pkg";
1382
1383    private static final String TAG_PERMISSION = "perm";
1384    private static final String ATTR_PERMISSION_NAME = "name";
1385    private static final String ATTR_IS_GRANTED = "g";
1386    private static final String ATTR_USER_SET = "set";
1387    private static final String ATTR_USER_FIXED = "fixed";
1388    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1389
1390    // System/policy permission grants are not backed up
1391    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_POLICY_FIXED
1393            | FLAG_PERMISSION_SYSTEM_FIXED
1394            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1395
1396    // And we back up these user-adjusted states
1397    private static final int USER_RUNTIME_GRANT_MASK =
1398            FLAG_PERMISSION_USER_SET
1399            | FLAG_PERMISSION_USER_FIXED
1400            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1401
1402    final @Nullable String mRequiredVerifierPackage;
1403    final @NonNull String mRequiredInstallerPackage;
1404    final @NonNull String mRequiredUninstallerPackage;
1405    final @Nullable String mSetupWizardPackage;
1406    final @Nullable String mStorageManagerPackage;
1407    final @NonNull String mServicesSystemSharedLibraryPackageName;
1408    final @NonNull String mSharedSystemSharedLibraryPackageName;
1409
1410    final boolean mPermissionReviewRequired;
1411
1412    private final PackageUsage mPackageUsage = new PackageUsage();
1413    private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415    class PackageHandler extends Handler {
1416        private boolean mBound = false;
1417        final ArrayList<HandlerParams> mPendingInstalls =
1418            new ArrayList<HandlerParams>();
1419
1420        private boolean connectToService() {
1421            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1422                    " DefaultContainerService");
1423            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1426                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428                mBound = true;
1429                return true;
1430            }
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432            return false;
1433        }
1434
1435        private void disconnectService() {
1436            mContainerService = null;
1437            mBound = false;
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1439            mContext.unbindService(mDefContainerConn);
1440            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441        }
1442
1443        PackageHandler(Looper looper) {
1444            super(looper);
1445        }
1446
1447        public void handleMessage(Message msg) {
1448            try {
1449                doHandleMessage(msg);
1450            } finally {
1451                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1452            }
1453        }
1454
1455        void doHandleMessage(Message msg) {
1456            switch (msg.what) {
1457                case INIT_COPY: {
1458                    HandlerParams params = (HandlerParams) msg.obj;
1459                    int idx = mPendingInstalls.size();
1460                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1461                    // If a bind was already initiated we dont really
1462                    // need to do anything. The pending install
1463                    // will be processed later on.
1464                    if (!mBound) {
1465                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                System.identityHashCode(mHandler));
1467                        // If this is the only one pending we might
1468                        // have to bind to the service again.
1469                        if (!connectToService()) {
1470                            Slog.e(TAG, "Failed to bind to media container service");
1471                            params.serviceError();
1472                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1473                                    System.identityHashCode(mHandler));
1474                            if (params.traceMethod != null) {
1475                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1476                                        params.traceCookie);
1477                            }
1478                            return;
1479                        } else {
1480                            // Once we bind to the service, the first
1481                            // pending request will be processed.
1482                            mPendingInstalls.add(idx, params);
1483                        }
1484                    } else {
1485                        mPendingInstalls.add(idx, params);
1486                        // Already bound to the service. Just make
1487                        // sure we trigger off processing the first request.
1488                        if (idx == 0) {
1489                            mHandler.sendEmptyMessage(MCS_BOUND);
1490                        }
1491                    }
1492                    break;
1493                }
1494                case MCS_BOUND: {
1495                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1496                    if (msg.obj != null) {
1497                        mContainerService = (IMediaContainerService) msg.obj;
1498                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1499                                System.identityHashCode(mHandler));
1500                    }
1501                    if (mContainerService == null) {
1502                        if (!mBound) {
1503                            // Something seriously wrong since we are not bound and we are not
1504                            // waiting for connection. Bail out.
1505                            Slog.e(TAG, "Cannot bind to media container service");
1506                            for (HandlerParams params : mPendingInstalls) {
1507                                // Indicate service bind error
1508                                params.serviceError();
1509                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                                        System.identityHashCode(params));
1511                                if (params.traceMethod != null) {
1512                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1513                                            params.traceMethod, params.traceCookie);
1514                                }
1515                                return;
1516                            }
1517                            mPendingInstalls.clear();
1518                        } else {
1519                            Slog.w(TAG, "Waiting to connect to media container service");
1520                        }
1521                    } else if (mPendingInstalls.size() > 0) {
1522                        HandlerParams params = mPendingInstalls.get(0);
1523                        if (params != null) {
1524                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1525                                    System.identityHashCode(params));
1526                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1527                            if (params.startCopy()) {
1528                                // We are done...  look for more work or to
1529                                // go idle.
1530                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                        "Checking for more work or unbind...");
1532                                // Delete pending install
1533                                if (mPendingInstalls.size() > 0) {
1534                                    mPendingInstalls.remove(0);
1535                                }
1536                                if (mPendingInstalls.size() == 0) {
1537                                    if (mBound) {
1538                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1539                                                "Posting delayed MCS_UNBIND");
1540                                        removeMessages(MCS_UNBIND);
1541                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1542                                        // Unbind after a little delay, to avoid
1543                                        // continual thrashing.
1544                                        sendMessageDelayed(ubmsg, 10000);
1545                                    }
1546                                } else {
1547                                    // There are more pending requests in queue.
1548                                    // Just post MCS_BOUND message to trigger processing
1549                                    // of next pending install.
1550                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1551                                            "Posting MCS_BOUND for next work");
1552                                    mHandler.sendEmptyMessage(MCS_BOUND);
1553                                }
1554                            }
1555                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1556                        }
1557                    } else {
1558                        // Should never happen ideally.
1559                        Slog.w(TAG, "Empty queue");
1560                    }
1561                    break;
1562                }
1563                case MCS_RECONNECT: {
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1565                    if (mPendingInstalls.size() > 0) {
1566                        if (mBound) {
1567                            disconnectService();
1568                        }
1569                        if (!connectToService()) {
1570                            Slog.e(TAG, "Failed to bind to media container service");
1571                            for (HandlerParams params : mPendingInstalls) {
1572                                // Indicate service bind error
1573                                params.serviceError();
1574                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1575                                        System.identityHashCode(params));
1576                            }
1577                            mPendingInstalls.clear();
1578                        }
1579                    }
1580                    break;
1581                }
1582                case MCS_UNBIND: {
1583                    // If there is no actual work left, then time to unbind.
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1585
1586                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1587                        if (mBound) {
1588                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1589
1590                            disconnectService();
1591                        }
1592                    } else if (mPendingInstalls.size() > 0) {
1593                        // There are more pending requests in queue.
1594                        // Just post MCS_BOUND message to trigger processing
1595                        // of next pending install.
1596                        mHandler.sendEmptyMessage(MCS_BOUND);
1597                    }
1598
1599                    break;
1600                }
1601                case MCS_GIVE_UP: {
1602                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1603                    HandlerParams params = mPendingInstalls.remove(0);
1604                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1605                            System.identityHashCode(params));
1606                    break;
1607                }
1608                case SEND_PENDING_BROADCAST: {
1609                    String packages[];
1610                    ArrayList<String> components[];
1611                    int size = 0;
1612                    int uids[];
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1614                    synchronized (mPackages) {
1615                        if (mPendingBroadcasts == null) {
1616                            return;
1617                        }
1618                        size = mPendingBroadcasts.size();
1619                        if (size <= 0) {
1620                            // Nothing to be done. Just return
1621                            return;
1622                        }
1623                        packages = new String[size];
1624                        components = new ArrayList[size];
1625                        uids = new int[size];
1626                        int i = 0;  // filling out the above arrays
1627
1628                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1629                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1630                            Iterator<Map.Entry<String, ArrayList<String>>> it
1631                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1632                                            .entrySet().iterator();
1633                            while (it.hasNext() && i < size) {
1634                                Map.Entry<String, ArrayList<String>> ent = it.next();
1635                                packages[i] = ent.getKey();
1636                                components[i] = ent.getValue();
1637                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1638                                uids[i] = (ps != null)
1639                                        ? UserHandle.getUid(packageUserId, ps.appId)
1640                                        : -1;
1641                                i++;
1642                            }
1643                        }
1644                        size = i;
1645                        mPendingBroadcasts.clear();
1646                    }
1647                    // Send broadcasts
1648                    for (int i = 0; i < size; i++) {
1649                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1650                    }
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652                    break;
1653                }
1654                case START_CLEANING_PACKAGE: {
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1656                    final String packageName = (String)msg.obj;
1657                    final int userId = msg.arg1;
1658                    final boolean andCode = msg.arg2 != 0;
1659                    synchronized (mPackages) {
1660                        if (userId == UserHandle.USER_ALL) {
1661                            int[] users = sUserManager.getUserIds();
1662                            for (int user : users) {
1663                                mSettings.addPackageToCleanLPw(
1664                                        new PackageCleanItem(user, packageName, andCode));
1665                            }
1666                        } else {
1667                            mSettings.addPackageToCleanLPw(
1668                                    new PackageCleanItem(userId, packageName, andCode));
1669                        }
1670                    }
1671                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1672                    startCleaningPackages();
1673                } break;
1674                case POST_INSTALL: {
1675                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1676
1677                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1678                    final boolean didRestore = (msg.arg2 != 0);
1679                    mRunningInstalls.delete(msg.arg1);
1680
1681                    if (data != null) {
1682                        InstallArgs args = data.args;
1683                        PackageInstalledInfo parentRes = data.res;
1684
1685                        final boolean grantPermissions = (args.installFlags
1686                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1687                        final boolean killApp = (args.installFlags
1688                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1689                        final boolean virtualPreload = ((args.installFlags
1690                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1691                        final String[] grantedPermissions = args.installGrantPermissions;
1692
1693                        // Handle the parent package
1694                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1695                                virtualPreload, grantedPermissions, didRestore,
1696                                args.installerPackageName, args.observer);
1697
1698                        // Handle the child packages
1699                        final int childCount = (parentRes.addedChildPackages != null)
1700                                ? parentRes.addedChildPackages.size() : 0;
1701                        for (int i = 0; i < childCount; i++) {
1702                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1703                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1704                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1705                                    args.installerPackageName, args.observer);
1706                        }
1707
1708                        // Log tracing if needed
1709                        if (args.traceMethod != null) {
1710                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1711                                    args.traceCookie);
1712                        }
1713                    } else {
1714                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1715                    }
1716
1717                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1718                } break;
1719                case WRITE_SETTINGS: {
1720                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1721                    synchronized (mPackages) {
1722                        removeMessages(WRITE_SETTINGS);
1723                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724                        mSettings.writeLPr();
1725                        mDirtyUsers.clear();
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case WRITE_PACKAGE_RESTRICTIONS: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                        for (int userId : mDirtyUsers) {
1734                            mSettings.writePackageRestrictionsLPr(userId);
1735                        }
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_LIST: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_LIST);
1744                        mSettings.writePackageListLPr(msg.arg1);
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case CHECK_PENDING_VERIFICATION: {
1749                    final int verificationId = msg.arg1;
1750                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1751
1752                    if ((state != null) && !state.timeoutExtended()) {
1753                        final InstallArgs args = state.getInstallArgs();
1754                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1755
1756                        Slog.i(TAG, "Verification timed out for " + originUri);
1757                        mPendingVerification.remove(verificationId);
1758
1759                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760
1761                        final UserHandle user = args.getUser();
1762                        if (getDefaultVerificationResponse(user)
1763                                == PackageManager.VERIFICATION_ALLOW) {
1764                            Slog.i(TAG, "Continuing with installation of " + originUri);
1765                            state.setVerifierResponse(Binder.getCallingUid(),
1766                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1767                            broadcastPackageVerified(verificationId, originUri,
1768                                    PackageManager.VERIFICATION_ALLOW, user);
1769                            try {
1770                                ret = args.copyApk(mContainerService, true);
1771                            } catch (RemoteException e) {
1772                                Slog.e(TAG, "Could not contact the ContainerService");
1773                            }
1774                        } else {
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_REJECT, user);
1777                        }
1778
1779                        Trace.asyncTraceEnd(
1780                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1781
1782                        processPendingInstall(args, ret);
1783                        mHandler.sendEmptyMessage(MCS_UNBIND);
1784                    }
1785                    break;
1786                }
1787                case PACKAGE_VERIFIED: {
1788                    final int verificationId = msg.arg1;
1789
1790                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1791                    if (state == null) {
1792                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1793                        break;
1794                    }
1795
1796                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1797
1798                    state.setVerifierResponse(response.callerUid, response.code);
1799
1800                    if (state.isVerificationComplete()) {
1801                        mPendingVerification.remove(verificationId);
1802
1803                        final InstallArgs args = state.getInstallArgs();
1804                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1805
1806                        int ret;
1807                        if (state.isInstallAllowed()) {
1808                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1809                            broadcastPackageVerified(verificationId, originUri,
1810                                    response.code, state.getInstallArgs().getUser());
1811                            try {
1812                                ret = args.copyApk(mContainerService, true);
1813                            } catch (RemoteException e) {
1814                                Slog.e(TAG, "Could not contact the ContainerService");
1815                            }
1816                        } else {
1817                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1818                        }
1819
1820                        Trace.asyncTraceEnd(
1821                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1822
1823                        processPendingInstall(args, ret);
1824                        mHandler.sendEmptyMessage(MCS_UNBIND);
1825                    }
1826
1827                    break;
1828                }
1829                case START_INTENT_FILTER_VERIFICATIONS: {
1830                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1831                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1832                            params.replacing, params.pkg);
1833                    break;
1834                }
1835                case INTENT_FILTER_VERIFIED: {
1836                    final int verificationId = msg.arg1;
1837
1838                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1839                            verificationId);
1840                    if (state == null) {
1841                        Slog.w(TAG, "Invalid IntentFilter verification token "
1842                                + verificationId + " received");
1843                        break;
1844                    }
1845
1846                    final int userId = state.getUserId();
1847
1848                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849                            "Processing IntentFilter verification with token:"
1850                            + verificationId + " and userId:" + userId);
1851
1852                    final IntentFilterVerificationResponse response =
1853                            (IntentFilterVerificationResponse) msg.obj;
1854
1855                    state.setVerifierResponse(response.callerUid, response.code);
1856
1857                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                            "IntentFilter verification with token:" + verificationId
1859                            + " and userId:" + userId
1860                            + " is settings verifier response with response code:"
1861                            + response.code);
1862
1863                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1864                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1865                                + response.getFailedDomainsString());
1866                    }
1867
1868                    if (state.isVerificationComplete()) {
1869                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1870                    } else {
1871                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                                "IntentFilter verification with token:" + verificationId
1873                                + " was not said to be complete");
1874                    }
1875
1876                    break;
1877                }
1878                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1879                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1880                            mInstantAppResolverConnection,
1881                            (InstantAppRequest) msg.obj,
1882                            mInstantAppInstallerActivity,
1883                            mHandler);
1884                }
1885            }
1886        }
1887    }
1888
1889    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1890        @Override
1891        public void onGidsChanged(int appId, int userId) {
1892            mHandler.post(new Runnable() {
1893                @Override
1894                public void run() {
1895                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1896                }
1897            });
1898        }
1899        @Override
1900        public void onPermissionGranted(int uid, int userId) {
1901            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1902
1903            // Not critical; if this is lost, the application has to request again.
1904            synchronized (mPackages) {
1905                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1906            }
1907        }
1908        @Override
1909        public void onInstallPermissionGranted() {
1910            synchronized (mPackages) {
1911                scheduleWriteSettingsLocked();
1912            }
1913        }
1914        @Override
1915        public void onPermissionRevoked(int uid, int userId) {
1916            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1917
1918            synchronized (mPackages) {
1919                // Critical; after this call the application should never have the permission
1920                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1921            }
1922
1923            final int appId = UserHandle.getAppId(uid);
1924            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1925        }
1926        @Override
1927        public void onInstallPermissionRevoked() {
1928            synchronized (mPackages) {
1929                scheduleWriteSettingsLocked();
1930            }
1931        }
1932        @Override
1933        public void onPermissionUpdated(int userId) {
1934            synchronized (mPackages) {
1935                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1936            }
1937        }
1938        @Override
1939        public void onInstallPermissionUpdated() {
1940            synchronized (mPackages) {
1941                scheduleWriteSettingsLocked();
1942            }
1943        }
1944        @Override
1945        public void onPermissionRemoved() {
1946            synchronized (mPackages) {
1947                mSettings.writeLPr();
1948            }
1949        }
1950    };
1951
1952    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1953            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1954            boolean launchedForRestore, String installerPackage,
1955            IPackageInstallObserver2 installObserver) {
1956        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1957            // Send the removed broadcasts
1958            if (res.removedInfo != null) {
1959                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1960            }
1961
1962            // Now that we successfully installed the package, grant runtime
1963            // permissions if requested before broadcasting the install. Also
1964            // for legacy apps in permission review mode we clear the permission
1965            // review flag which is used to emulate runtime permissions for
1966            // legacy apps.
1967            if (grantPermissions) {
1968                final int callingUid = Binder.getCallingUid();
1969                mPermissionManager.grantRequestedRuntimePermissions(
1970                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1971                        mPermissionCallback);
1972            }
1973
1974            final boolean update = res.removedInfo != null
1975                    && res.removedInfo.removedPackage != null;
1976            final String installerPackageName =
1977                    res.installerPackageName != null
1978                            ? res.installerPackageName
1979                            : res.removedInfo != null
1980                                    ? res.removedInfo.installerPackageName
1981                                    : null;
1982
1983            // If this is the first time we have child packages for a disabled privileged
1984            // app that had no children, we grant requested runtime permissions to the new
1985            // children if the parent on the system image had them already granted.
1986            if (res.pkg.parentPackage != null) {
1987                final int callingUid = Binder.getCallingUid();
1988                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1989                        res.pkg, callingUid, mPermissionCallback);
1990            }
1991
1992            synchronized (mPackages) {
1993                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1994            }
1995
1996            final String packageName = res.pkg.applicationInfo.packageName;
1997
1998            // Determine the set of users who are adding this package for
1999            // the first time vs. those who are seeing an update.
2000            int[] firstUsers = EMPTY_INT_ARRAY;
2001            int[] updateUsers = EMPTY_INT_ARRAY;
2002            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2003            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2004            for (int newUser : res.newUsers) {
2005                if (ps.getInstantApp(newUser)) {
2006                    continue;
2007                }
2008                if (allNewUsers) {
2009                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2010                    continue;
2011                }
2012                boolean isNew = true;
2013                for (int origUser : res.origUsers) {
2014                    if (origUser == newUser) {
2015                        isNew = false;
2016                        break;
2017                    }
2018                }
2019                if (isNew) {
2020                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2021                } else {
2022                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2023                }
2024            }
2025
2026            // Send installed broadcasts if the package is not a static shared lib.
2027            if (res.pkg.staticSharedLibName == null) {
2028                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2029
2030                // Send added for users that see the package for the first time
2031                // sendPackageAddedForNewUsers also deals with system apps
2032                int appId = UserHandle.getAppId(res.uid);
2033                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2034                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2035                        virtualPreload /*startReceiver*/, appId, firstUsers);
2036
2037                // Send added for users that don't see the package for the first time
2038                Bundle extras = new Bundle(1);
2039                extras.putInt(Intent.EXTRA_UID, res.uid);
2040                if (update) {
2041                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2042                }
2043                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2044                        extras, 0 /*flags*/,
2045                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2046                if (installerPackageName != null) {
2047                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2048                            extras, 0 /*flags*/,
2049                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2050                }
2051
2052                // Send replaced for users that don't see the package for the first time
2053                if (update) {
2054                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2055                            packageName, extras, 0 /*flags*/,
2056                            null /*targetPackage*/, null /*finishedReceiver*/,
2057                            updateUsers);
2058                    if (installerPackageName != null) {
2059                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2060                                extras, 0 /*flags*/,
2061                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2062                    }
2063                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2064                            null /*package*/, null /*extras*/, 0 /*flags*/,
2065                            packageName /*targetPackage*/,
2066                            null /*finishedReceiver*/, updateUsers);
2067                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2068                    // First-install and we did a restore, so we're responsible for the
2069                    // first-launch broadcast.
2070                    if (DEBUG_BACKUP) {
2071                        Slog.i(TAG, "Post-restore of " + packageName
2072                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2073                    }
2074                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2075                }
2076
2077                // Send broadcast package appeared if forward locked/external for all users
2078                // treat asec-hosted packages like removable media on upgrade
2079                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2080                    if (DEBUG_INSTALL) {
2081                        Slog.i(TAG, "upgrading pkg " + res.pkg
2082                                + " is ASEC-hosted -> AVAILABLE");
2083                    }
2084                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2085                    ArrayList<String> pkgList = new ArrayList<>(1);
2086                    pkgList.add(packageName);
2087                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2088                }
2089            }
2090
2091            // Work that needs to happen on first install within each user
2092            if (firstUsers != null && firstUsers.length > 0) {
2093                synchronized (mPackages) {
2094                    for (int userId : firstUsers) {
2095                        // If this app is a browser and it's newly-installed for some
2096                        // users, clear any default-browser state in those users. The
2097                        // app's nature doesn't depend on the user, so we can just check
2098                        // its browser nature in any user and generalize.
2099                        if (packageIsBrowser(packageName, userId)) {
2100                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2101                        }
2102
2103                        // We may also need to apply pending (restored) runtime
2104                        // permission grants within these users.
2105                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2106                    }
2107                }
2108            }
2109
2110            // Log current value of "unknown sources" setting
2111            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2112                    getUnknownSourcesSettings());
2113
2114            // Remove the replaced package's older resources safely now
2115            // We delete after a gc for applications  on sdcard.
2116            if (res.removedInfo != null && res.removedInfo.args != null) {
2117                Runtime.getRuntime().gc();
2118                synchronized (mInstallLock) {
2119                    res.removedInfo.args.doPostDeleteLI(true);
2120                }
2121            } else {
2122                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2123                // and not block here.
2124                VMRuntime.getRuntime().requestConcurrentGC();
2125            }
2126
2127            // Notify DexManager that the package was installed for new users.
2128            // The updated users should already be indexed and the package code paths
2129            // should not change.
2130            // Don't notify the manager for ephemeral apps as they are not expected to
2131            // survive long enough to benefit of background optimizations.
2132            for (int userId : firstUsers) {
2133                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2134                // There's a race currently where some install events may interleave with an uninstall.
2135                // This can lead to package info being null (b/36642664).
2136                if (info != null) {
2137                    mDexManager.notifyPackageInstalled(info, userId);
2138                }
2139            }
2140        }
2141
2142        // If someone is watching installs - notify them
2143        if (installObserver != null) {
2144            try {
2145                Bundle extras = extrasForInstallResult(res);
2146                installObserver.onPackageInstalled(res.name, res.returnCode,
2147                        res.returnMsg, extras);
2148            } catch (RemoteException e) {
2149                Slog.i(TAG, "Observer no longer exists.");
2150            }
2151        }
2152    }
2153
2154    private StorageEventListener mStorageListener = new StorageEventListener() {
2155        @Override
2156        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2157            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2158                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2159                    final String volumeUuid = vol.getFsUuid();
2160
2161                    // Clean up any users or apps that were removed or recreated
2162                    // while this volume was missing
2163                    sUserManager.reconcileUsers(volumeUuid);
2164                    reconcileApps(volumeUuid);
2165
2166                    // Clean up any install sessions that expired or were
2167                    // cancelled while this volume was missing
2168                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2169
2170                    loadPrivatePackages(vol);
2171
2172                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2173                    unloadPrivatePackages(vol);
2174                }
2175            }
2176        }
2177
2178        @Override
2179        public void onVolumeForgotten(String fsUuid) {
2180            if (TextUtils.isEmpty(fsUuid)) {
2181                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2182                return;
2183            }
2184
2185            // Remove any apps installed on the forgotten volume
2186            synchronized (mPackages) {
2187                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2188                for (PackageSetting ps : packages) {
2189                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2190                    deletePackageVersioned(new VersionedPackage(ps.name,
2191                            PackageManager.VERSION_CODE_HIGHEST),
2192                            new LegacyPackageDeleteObserver(null).getBinder(),
2193                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2194                    // Try very hard to release any references to this package
2195                    // so we don't risk the system server being killed due to
2196                    // open FDs
2197                    AttributeCache.instance().removePackage(ps.name);
2198                }
2199
2200                mSettings.onVolumeForgotten(fsUuid);
2201                mSettings.writeLPr();
2202            }
2203        }
2204    };
2205
2206    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2207        Bundle extras = null;
2208        switch (res.returnCode) {
2209            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2210                extras = new Bundle();
2211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2212                        res.origPermission);
2213                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2214                        res.origPackage);
2215                break;
2216            }
2217            case PackageManager.INSTALL_SUCCEEDED: {
2218                extras = new Bundle();
2219                extras.putBoolean(Intent.EXTRA_REPLACING,
2220                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2221                break;
2222            }
2223        }
2224        return extras;
2225    }
2226
2227    void scheduleWriteSettingsLocked() {
2228        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2229            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2230        }
2231    }
2232
2233    void scheduleWritePackageListLocked(int userId) {
2234        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2235            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2236            msg.arg1 = userId;
2237            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2238        }
2239    }
2240
2241    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2242        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2243        scheduleWritePackageRestrictionsLocked(userId);
2244    }
2245
2246    void scheduleWritePackageRestrictionsLocked(int userId) {
2247        final int[] userIds = (userId == UserHandle.USER_ALL)
2248                ? sUserManager.getUserIds() : new int[]{userId};
2249        for (int nextUserId : userIds) {
2250            if (!sUserManager.exists(nextUserId)) return;
2251            mDirtyUsers.add(nextUserId);
2252            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2253                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2254            }
2255        }
2256    }
2257
2258    public static PackageManagerService main(Context context, Installer installer,
2259            boolean factoryTest, boolean onlyCore) {
2260        // Self-check for initial settings.
2261        PackageManagerServiceCompilerMapping.checkProperties();
2262
2263        PackageManagerService m = new PackageManagerService(context, installer,
2264                factoryTest, onlyCore);
2265        m.enableSystemUserPackages();
2266        ServiceManager.addService("package", m);
2267        final PackageManagerNative pmn = m.new PackageManagerNative();
2268        ServiceManager.addService("package_native", pmn);
2269        return m;
2270    }
2271
2272    private void enableSystemUserPackages() {
2273        if (!UserManager.isSplitSystemUser()) {
2274            return;
2275        }
2276        // For system user, enable apps based on the following conditions:
2277        // - app is whitelisted or belong to one of these groups:
2278        //   -- system app which has no launcher icons
2279        //   -- system app which has INTERACT_ACROSS_USERS permission
2280        //   -- system IME app
2281        // - app is not in the blacklist
2282        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2283        Set<String> enableApps = new ArraySet<>();
2284        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2285                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2286                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2287        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2288        enableApps.addAll(wlApps);
2289        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2290                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2291        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2292        enableApps.removeAll(blApps);
2293        Log.i(TAG, "Applications installed for system user: " + enableApps);
2294        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2295                UserHandle.SYSTEM);
2296        final int allAppsSize = allAps.size();
2297        synchronized (mPackages) {
2298            for (int i = 0; i < allAppsSize; i++) {
2299                String pName = allAps.get(i);
2300                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2301                // Should not happen, but we shouldn't be failing if it does
2302                if (pkgSetting == null) {
2303                    continue;
2304                }
2305                boolean install = enableApps.contains(pName);
2306                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2307                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2308                            + " for system user");
2309                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2310                }
2311            }
2312            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2313        }
2314    }
2315
2316    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2317        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2318                Context.DISPLAY_SERVICE);
2319        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2320    }
2321
2322    /**
2323     * Requests that files preopted on a secondary system partition be copied to the data partition
2324     * if possible.  Note that the actual copying of the files is accomplished by init for security
2325     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2326     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2327     */
2328    private static void requestCopyPreoptedFiles() {
2329        final int WAIT_TIME_MS = 100;
2330        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2331        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2332            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2333            // We will wait for up to 100 seconds.
2334            final long timeStart = SystemClock.uptimeMillis();
2335            final long timeEnd = timeStart + 100 * 1000;
2336            long timeNow = timeStart;
2337            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2338                try {
2339                    Thread.sleep(WAIT_TIME_MS);
2340                } catch (InterruptedException e) {
2341                    // Do nothing
2342                }
2343                timeNow = SystemClock.uptimeMillis();
2344                if (timeNow > timeEnd) {
2345                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2346                    Slog.wtf(TAG, "cppreopt did not finish!");
2347                    break;
2348                }
2349            }
2350
2351            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2352        }
2353    }
2354
2355    public PackageManagerService(Context context, Installer installer,
2356            boolean factoryTest, boolean onlyCore) {
2357        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2358        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2359        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2360                SystemClock.uptimeMillis());
2361
2362        if (mSdkVersion <= 0) {
2363            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2364        }
2365
2366        mContext = context;
2367
2368        mPermissionReviewRequired = context.getResources().getBoolean(
2369                R.bool.config_permissionReviewRequired);
2370
2371        mFactoryTest = factoryTest;
2372        mOnlyCore = onlyCore;
2373        mMetrics = new DisplayMetrics();
2374        mInstaller = installer;
2375
2376        // Create sub-components that provide services / data. Order here is important.
2377        synchronized (mInstallLock) {
2378        synchronized (mPackages) {
2379            // Expose private service for system components to use.
2380            LocalServices.addService(
2381                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2382            sUserManager = new UserManagerService(context, this,
2383                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2384            mPermissionManager = PermissionManagerService.create(context,
2385                    new DefaultPermissionGrantedCallback() {
2386                        @Override
2387                        public void onDefaultRuntimePermissionsGranted(int userId) {
2388                            synchronized(mPackages) {
2389                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2390                            }
2391                        }
2392                    }, mPackages /*externalLock*/);
2393            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2394            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2395        }
2396        }
2397        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409
2410        String separateProcesses = SystemProperties.get("debug.separate_processes");
2411        if (separateProcesses != null && separateProcesses.length() > 0) {
2412            if ("*".equals(separateProcesses)) {
2413                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2414                mSeparateProcesses = null;
2415                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2416            } else {
2417                mDefParseFlags = 0;
2418                mSeparateProcesses = separateProcesses.split(",");
2419                Slog.w(TAG, "Running with debug.separate_processes: "
2420                        + separateProcesses);
2421            }
2422        } else {
2423            mDefParseFlags = 0;
2424            mSeparateProcesses = null;
2425        }
2426
2427        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2428                "*dexopt*");
2429        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2430        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2431
2432        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2433                FgThread.get().getLooper());
2434
2435        getDefaultDisplayMetrics(context, mMetrics);
2436
2437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2438        SystemConfig systemConfig = SystemConfig.getInstance();
2439        mGlobalGids = systemConfig.getGlobalGids();
2440        mSystemPermissions = systemConfig.getSystemPermissions();
2441        mAvailableFeatures = systemConfig.getAvailableFeatures();
2442        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2443
2444        mProtectedPackages = new ProtectedPackages(mContext);
2445
2446        synchronized (mInstallLock) {
2447        // writer
2448        synchronized (mPackages) {
2449            mHandlerThread = new ServiceThread(TAG,
2450                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2451            mHandlerThread.start();
2452            mHandler = new PackageHandler(mHandlerThread.getLooper());
2453            mProcessLoggingHandler = new ProcessLoggingHandler();
2454            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2455            mInstantAppRegistry = new InstantAppRegistry(this);
2456
2457            File dataDir = Environment.getDataDirectory();
2458            mAppInstallDir = new File(dataDir, "app");
2459            mAppLib32InstallDir = new File(dataDir, "app-lib");
2460            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2461
2462            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2463            final int builtInLibCount = libConfig.size();
2464            for (int i = 0; i < builtInLibCount; i++) {
2465                String name = libConfig.keyAt(i);
2466                String path = libConfig.valueAt(i);
2467                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2468                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2469            }
2470
2471            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2472
2473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2474            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2476
2477            // Clean up orphaned packages for which the code path doesn't exist
2478            // and they are an update to a system app - caused by bug/32321269
2479            final int packageSettingCount = mSettings.mPackages.size();
2480            for (int i = packageSettingCount - 1; i >= 0; i--) {
2481                PackageSetting ps = mSettings.mPackages.valueAt(i);
2482                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2483                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2484                    mSettings.mPackages.removeAt(i);
2485                    mSettings.enableSystemPackageLPw(ps.name);
2486                }
2487            }
2488
2489            if (mFirstBoot) {
2490                requestCopyPreoptedFiles();
2491            }
2492
2493            String customResolverActivity = Resources.getSystem().getString(
2494                    R.string.config_customResolverActivity);
2495            if (TextUtils.isEmpty(customResolverActivity)) {
2496                customResolverActivity = null;
2497            } else {
2498                mCustomResolverComponentName = ComponentName.unflattenFromString(
2499                        customResolverActivity);
2500            }
2501
2502            long startTime = SystemClock.uptimeMillis();
2503
2504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2505                    startTime);
2506
2507            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2508            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2509
2510            if (bootClassPath == null) {
2511                Slog.w(TAG, "No BOOTCLASSPATH found!");
2512            }
2513
2514            if (systemServerClassPath == null) {
2515                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2516            }
2517
2518            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2519
2520            final VersionInfo ver = mSettings.getInternalVersion();
2521            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2522            if (mIsUpgrade) {
2523                logCriticalInfo(Log.INFO,
2524                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2525            }
2526
2527            // when upgrading from pre-M, promote system app permissions from install to runtime
2528            mPromoteSystemApps =
2529                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2530
2531            // When upgrading from pre-N, we need to handle package extraction like first boot,
2532            // as there is no profiling data available.
2533            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2534
2535            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2536
2537            // save off the names of pre-existing system packages prior to scanning; we don't
2538            // want to automatically grant runtime permissions for new system apps
2539            if (mPromoteSystemApps) {
2540                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2541                while (pkgSettingIter.hasNext()) {
2542                    PackageSetting ps = pkgSettingIter.next();
2543                    if (isSystemApp(ps)) {
2544                        mExistingSystemPackages.add(ps.name);
2545                    }
2546                }
2547            }
2548
2549            mCacheDir = preparePackageParserCache(mIsUpgrade);
2550
2551            // Set flag to monitor and not change apk file paths when
2552            // scanning install directories.
2553            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2554
2555            if (mIsUpgrade || mFirstBoot) {
2556                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2557            }
2558
2559            // Collect vendor overlay packages. (Do this before scanning any apps.)
2560            // For security and version matching reason, only consider
2561            // overlay packages if they reside in the right directory.
2562            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2563                    | PackageParser.PARSE_IS_SYSTEM
2564                    | PackageParser.PARSE_IS_SYSTEM_DIR
2565                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2566
2567            mParallelPackageParserCallback.findStaticOverlayPackages();
2568
2569            // Find base frameworks (resource packages without code).
2570            scanDirTracedLI(frameworkDir, mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM
2572                    | PackageParser.PARSE_IS_SYSTEM_DIR
2573                    | PackageParser.PARSE_IS_PRIVILEGED,
2574                    scanFlags | SCAN_NO_DEX, 0);
2575
2576            // Collected privileged system packages.
2577            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2578            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2579                    | PackageParser.PARSE_IS_SYSTEM
2580                    | PackageParser.PARSE_IS_SYSTEM_DIR
2581                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2582
2583            // Collect ordinary system packages.
2584            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2585            scanDirTracedLI(systemAppDir, mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2588
2589            // Collect all vendor packages.
2590            File vendorAppDir = new File("/vendor/app");
2591            try {
2592                vendorAppDir = vendorAppDir.getCanonicalFile();
2593            } catch (IOException e) {
2594                // failed to look up canonical path, continue with original one
2595            }
2596            scanDirTracedLI(vendorAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2599
2600            // Collect all OEM packages.
2601            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2602            scanDirTracedLI(oemAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2606
2607            // Prune any system packages that no longer exist.
2608            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2609            // Stub packages must either be replaced with full versions in the /data
2610            // partition or be disabled.
2611            final List<String> stubSystemApps = new ArrayList<>();
2612            if (!mOnlyCore) {
2613                // do this first before mucking with mPackages for the "expecting better" case
2614                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2615                while (pkgIterator.hasNext()) {
2616                    final PackageParser.Package pkg = pkgIterator.next();
2617                    if (pkg.isStub) {
2618                        stubSystemApps.add(pkg.packageName);
2619                    }
2620                }
2621
2622                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2623                while (psit.hasNext()) {
2624                    PackageSetting ps = psit.next();
2625
2626                    /*
2627                     * If this is not a system app, it can't be a
2628                     * disable system app.
2629                     */
2630                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2631                        continue;
2632                    }
2633
2634                    /*
2635                     * If the package is scanned, it's not erased.
2636                     */
2637                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2638                    if (scannedPkg != null) {
2639                        /*
2640                         * If the system app is both scanned and in the
2641                         * disabled packages list, then it must have been
2642                         * added via OTA. Remove it from the currently
2643                         * scanned package so the previously user-installed
2644                         * application can be scanned.
2645                         */
2646                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2647                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2648                                    + ps.name + "; removing system app.  Last known codePath="
2649                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2650                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2651                                    + scannedPkg.mVersionCode);
2652                            removePackageLI(scannedPkg, true);
2653                            mExpectingBetter.put(ps.name, ps.codePath);
2654                        }
2655
2656                        continue;
2657                    }
2658
2659                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2660                        psit.remove();
2661                        logCriticalInfo(Log.WARN, "System package " + ps.name
2662                                + " no longer exists; it's data will be wiped");
2663                        // Actual deletion of code and data will be handled by later
2664                        // reconciliation step
2665                    } else {
2666                        // we still have a disabled system package, but, it still might have
2667                        // been removed. check the code path still exists and check there's
2668                        // still a package. the latter can happen if an OTA keeps the same
2669                        // code path, but, changes the package name.
2670                        final PackageSetting disabledPs =
2671                                mSettings.getDisabledSystemPkgLPr(ps.name);
2672                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2673                                || disabledPs.pkg == null) {
2674                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2675                        }
2676                    }
2677                }
2678            }
2679
2680            //look for any incomplete package installations
2681            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2682            for (int i = 0; i < deletePkgsList.size(); i++) {
2683                // Actual deletion of code and data will be handled by later
2684                // reconciliation step
2685                final String packageName = deletePkgsList.get(i).name;
2686                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2687                synchronized (mPackages) {
2688                    mSettings.removePackageLPw(packageName);
2689                }
2690            }
2691
2692            //delete tmp files
2693            deleteTempPackageFiles();
2694
2695            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2696
2697            // Remove any shared userIDs that have no associated packages
2698            mSettings.pruneSharedUsersLPw();
2699            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2700            final int systemPackagesCount = mPackages.size();
2701            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2702                    + " ms, packageCount: " + systemPackagesCount
2703                    + " , timePerPackage: "
2704                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2705                    + " , cached: " + cachedSystemApps);
2706            if (mIsUpgrade && systemPackagesCount > 0) {
2707                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2708                        ((int) systemScanTime) / systemPackagesCount);
2709            }
2710            if (!mOnlyCore) {
2711                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2712                        SystemClock.uptimeMillis());
2713                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2714
2715                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2716                        | PackageParser.PARSE_FORWARD_LOCK,
2717                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2718
2719                // Remove disable package settings for updated system apps that were
2720                // removed via an OTA. If the update is no longer present, remove the
2721                // app completely. Otherwise, revoke their system privileges.
2722                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2723                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2724                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2725
2726                    final String msg;
2727                    if (deletedPkg == null) {
2728                        // should have found an update, but, we didn't; remove everything
2729                        msg = "Updated system package " + deletedAppName
2730                                + " no longer exists; removing its data";
2731                        // Actual deletion of code and data will be handled by later
2732                        // reconciliation step
2733                    } else {
2734                        // found an update; revoke system privileges
2735                        msg = "Updated system package + " + deletedAppName
2736                                + " no longer exists; revoking system privileges";
2737
2738                        // Don't do anything if a stub is removed from the system image. If
2739                        // we were to remove the uncompressed version from the /data partition,
2740                        // this is where it'd be done.
2741
2742                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2743                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2744                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2745                    }
2746                    logCriticalInfo(Log.WARN, msg);
2747                }
2748
2749                /*
2750                 * Make sure all system apps that we expected to appear on
2751                 * the userdata partition actually showed up. If they never
2752                 * appeared, crawl back and revive the system version.
2753                 */
2754                for (int i = 0; i < mExpectingBetter.size(); i++) {
2755                    final String packageName = mExpectingBetter.keyAt(i);
2756                    if (!mPackages.containsKey(packageName)) {
2757                        final File scanFile = mExpectingBetter.valueAt(i);
2758
2759                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2760                                + " but never showed up; reverting to system");
2761
2762                        int reparseFlags = mDefParseFlags;
2763                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2764                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2765                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2766                                    | PackageParser.PARSE_IS_PRIVILEGED;
2767                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2770                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2771                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2772                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2773                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2774                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2775                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2776                                    | PackageParser.PARSE_IS_OEM;
2777                        } else {
2778                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2779                            continue;
2780                        }
2781
2782                        mSettings.enableSystemPackageLPw(packageName);
2783
2784                        try {
2785                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2786                        } catch (PackageManagerException e) {
2787                            Slog.e(TAG, "Failed to parse original system package: "
2788                                    + e.getMessage());
2789                        }
2790                    }
2791                }
2792
2793                // Uncompress and install any stubbed system applications.
2794                // This must be done last to ensure all stubs are replaced or disabled.
2795                decompressSystemApplications(stubSystemApps, scanFlags);
2796
2797                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2798                                - cachedSystemApps;
2799
2800                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2801                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2802                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2803                        + " ms, packageCount: " + dataPackagesCount
2804                        + " , timePerPackage: "
2805                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2806                        + " , cached: " + cachedNonSystemApps);
2807                if (mIsUpgrade && dataPackagesCount > 0) {
2808                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2809                            ((int) dataScanTime) / dataPackagesCount);
2810                }
2811            }
2812            mExpectingBetter.clear();
2813
2814            // Resolve the storage manager.
2815            mStorageManagerPackage = getStorageManagerPackageName();
2816
2817            // Resolve protected action filters. Only the setup wizard is allowed to
2818            // have a high priority filter for these actions.
2819            mSetupWizardPackage = getSetupWizardPackageName();
2820            if (mProtectedFilters.size() > 0) {
2821                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2822                    Slog.i(TAG, "No setup wizard;"
2823                        + " All protected intents capped to priority 0");
2824                }
2825                for (ActivityIntentInfo filter : mProtectedFilters) {
2826                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2827                        if (DEBUG_FILTERS) {
2828                            Slog.i(TAG, "Found setup wizard;"
2829                                + " allow priority " + filter.getPriority() + ";"
2830                                + " package: " + filter.activity.info.packageName
2831                                + " activity: " + filter.activity.className
2832                                + " priority: " + filter.getPriority());
2833                        }
2834                        // skip setup wizard; allow it to keep the high priority filter
2835                        continue;
2836                    }
2837                    if (DEBUG_FILTERS) {
2838                        Slog.i(TAG, "Protected action; cap priority to 0;"
2839                                + " package: " + filter.activity.info.packageName
2840                                + " activity: " + filter.activity.className
2841                                + " origPrio: " + filter.getPriority());
2842                    }
2843                    filter.setPriority(0);
2844                }
2845            }
2846            mDeferProtectedFilters = false;
2847            mProtectedFilters.clear();
2848
2849            // Now that we know all of the shared libraries, update all clients to have
2850            // the correct library paths.
2851            updateAllSharedLibrariesLPw(null);
2852
2853            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2854                // NOTE: We ignore potential failures here during a system scan (like
2855                // the rest of the commands above) because there's precious little we
2856                // can do about it. A settings error is reported, though.
2857                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2858            }
2859
2860            // Now that we know all the packages we are keeping,
2861            // read and update their last usage times.
2862            mPackageUsage.read(mPackages);
2863            mCompilerStats.read();
2864
2865            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2866                    SystemClock.uptimeMillis());
2867            Slog.i(TAG, "Time to scan packages: "
2868                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2869                    + " seconds");
2870
2871            // If the platform SDK has changed since the last time we booted,
2872            // we need to re-grant app permission to catch any new ones that
2873            // appear.  This is really a hack, and means that apps can in some
2874            // cases get permissions that the user didn't initially explicitly
2875            // allow...  it would be nice to have some better way to handle
2876            // this situation.
2877            int updateFlags = UPDATE_PERMISSIONS_ALL;
2878            if (ver.sdkVersion != mSdkVersion) {
2879                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2880                        + mSdkVersion + "; regranting permissions for internal storage");
2881                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2882            }
2883            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2884            ver.sdkVersion = mSdkVersion;
2885
2886            // If this is the first boot or an update from pre-M, and it is a normal
2887            // boot, then we need to initialize the default preferred apps across
2888            // all defined users.
2889            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2890                for (UserInfo user : sUserManager.getUsers(true)) {
2891                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2892                    applyFactoryDefaultBrowserLPw(user.id);
2893                    primeDomainVerificationsLPw(user.id);
2894                }
2895            }
2896
2897            // Prepare storage for system user really early during boot,
2898            // since core system apps like SettingsProvider and SystemUI
2899            // can't wait for user to start
2900            final int storageFlags;
2901            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2902                storageFlags = StorageManager.FLAG_STORAGE_DE;
2903            } else {
2904                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2905            }
2906            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2907                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2908                    true /* onlyCoreApps */);
2909            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2910                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2911                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2912                traceLog.traceBegin("AppDataFixup");
2913                try {
2914                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2915                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2916                } catch (InstallerException e) {
2917                    Slog.w(TAG, "Trouble fixing GIDs", e);
2918                }
2919                traceLog.traceEnd();
2920
2921                traceLog.traceBegin("AppDataPrepare");
2922                if (deferPackages == null || deferPackages.isEmpty()) {
2923                    return;
2924                }
2925                int count = 0;
2926                for (String pkgName : deferPackages) {
2927                    PackageParser.Package pkg = null;
2928                    synchronized (mPackages) {
2929                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2930                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2931                            pkg = ps.pkg;
2932                        }
2933                    }
2934                    if (pkg != null) {
2935                        synchronized (mInstallLock) {
2936                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2937                                    true /* maybeMigrateAppData */);
2938                        }
2939                        count++;
2940                    }
2941                }
2942                traceLog.traceEnd();
2943                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2944            }, "prepareAppData");
2945
2946            // If this is first boot after an OTA, and a normal boot, then
2947            // we need to clear code cache directories.
2948            // Note that we do *not* clear the application profiles. These remain valid
2949            // across OTAs and are used to drive profile verification (post OTA) and
2950            // profile compilation (without waiting to collect a fresh set of profiles).
2951            if (mIsUpgrade && !onlyCore) {
2952                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2953                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2954                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2955                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2956                        // No apps are running this early, so no need to freeze
2957                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2958                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2959                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2960                    }
2961                }
2962                ver.fingerprint = Build.FINGERPRINT;
2963            }
2964
2965            checkDefaultBrowser();
2966
2967            // clear only after permissions and other defaults have been updated
2968            mExistingSystemPackages.clear();
2969            mPromoteSystemApps = false;
2970
2971            // All the changes are done during package scanning.
2972            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2973
2974            // can downgrade to reader
2975            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2976            mSettings.writeLPr();
2977            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2978            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2979                    SystemClock.uptimeMillis());
2980
2981            if (!mOnlyCore) {
2982                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2983                mRequiredInstallerPackage = getRequiredInstallerLPr();
2984                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2985                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2986                if (mIntentFilterVerifierComponent != null) {
2987                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2988                            mIntentFilterVerifierComponent);
2989                } else {
2990                    mIntentFilterVerifier = null;
2991                }
2992                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2993                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2994                        SharedLibraryInfo.VERSION_UNDEFINED);
2995                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2996                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2997                        SharedLibraryInfo.VERSION_UNDEFINED);
2998            } else {
2999                mRequiredVerifierPackage = null;
3000                mRequiredInstallerPackage = null;
3001                mRequiredUninstallerPackage = null;
3002                mIntentFilterVerifierComponent = null;
3003                mIntentFilterVerifier = null;
3004                mServicesSystemSharedLibraryPackageName = null;
3005                mSharedSystemSharedLibraryPackageName = null;
3006            }
3007
3008            mInstallerService = new PackageInstallerService(context, this);
3009            final Pair<ComponentName, String> instantAppResolverComponent =
3010                    getInstantAppResolverLPr();
3011            if (instantAppResolverComponent != null) {
3012                if (DEBUG_EPHEMERAL) {
3013                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3014                }
3015                mInstantAppResolverConnection = new EphemeralResolverConnection(
3016                        mContext, instantAppResolverComponent.first,
3017                        instantAppResolverComponent.second);
3018                mInstantAppResolverSettingsComponent =
3019                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3020            } else {
3021                mInstantAppResolverConnection = null;
3022                mInstantAppResolverSettingsComponent = null;
3023            }
3024            updateInstantAppInstallerLocked(null);
3025
3026            // Read and update the usage of dex files.
3027            // Do this at the end of PM init so that all the packages have their
3028            // data directory reconciled.
3029            // At this point we know the code paths of the packages, so we can validate
3030            // the disk file and build the internal cache.
3031            // The usage file is expected to be small so loading and verifying it
3032            // should take a fairly small time compare to the other activities (e.g. package
3033            // scanning).
3034            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3035            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3036            for (int userId : currentUserIds) {
3037                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3038            }
3039            mDexManager.load(userPackages);
3040            if (mIsUpgrade) {
3041                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3042                        (int) (SystemClock.uptimeMillis() - startTime));
3043            }
3044        } // synchronized (mPackages)
3045        } // synchronized (mInstallLock)
3046
3047        // Now after opening every single application zip, make sure they
3048        // are all flushed.  Not really needed, but keeps things nice and
3049        // tidy.
3050        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3051        Runtime.getRuntime().gc();
3052        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3053
3054        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3055        FallbackCategoryProvider.loadFallbacks();
3056        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3057
3058        // The initial scanning above does many calls into installd while
3059        // holding the mPackages lock, but we're mostly interested in yelling
3060        // once we have a booted system.
3061        mInstaller.setWarnIfHeld(mPackages);
3062
3063        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3064    }
3065
3066    /**
3067     * Uncompress and install stub applications.
3068     * <p>In order to save space on the system partition, some applications are shipped in a
3069     * compressed form. In addition the compressed bits for the full application, the
3070     * system image contains a tiny stub comprised of only the Android manifest.
3071     * <p>During the first boot, attempt to uncompress and install the full application. If
3072     * the application can't be installed for any reason, disable the stub and prevent
3073     * uncompressing the full application during future boots.
3074     * <p>In order to forcefully attempt an installation of a full application, go to app
3075     * settings and enable the application.
3076     */
3077    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3078        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3079            final String pkgName = stubSystemApps.get(i);
3080            // skip if the system package is already disabled
3081            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3082                stubSystemApps.remove(i);
3083                continue;
3084            }
3085            // skip if the package isn't installed (?!); this should never happen
3086            final PackageParser.Package pkg = mPackages.get(pkgName);
3087            if (pkg == null) {
3088                stubSystemApps.remove(i);
3089                continue;
3090            }
3091            // skip if the package has been disabled by the user
3092            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3093            if (ps != null) {
3094                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3095                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3096                    stubSystemApps.remove(i);
3097                    continue;
3098                }
3099            }
3100
3101            if (DEBUG_COMPRESSION) {
3102                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3103            }
3104
3105            // uncompress the binary to its eventual destination on /data
3106            final File scanFile = decompressPackage(pkg);
3107            if (scanFile == null) {
3108                continue;
3109            }
3110
3111            // install the package to replace the stub on /system
3112            try {
3113                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3114                removePackageLI(pkg, true /*chatty*/);
3115                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3116                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3117                        UserHandle.USER_SYSTEM, "android");
3118                stubSystemApps.remove(i);
3119                continue;
3120            } catch (PackageManagerException e) {
3121                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3122            }
3123
3124            // any failed attempt to install the package will be cleaned up later
3125        }
3126
3127        // disable any stub still left; these failed to install the full application
3128        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3129            final String pkgName = stubSystemApps.get(i);
3130            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3131            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3132                    UserHandle.USER_SYSTEM, "android");
3133            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3134        }
3135    }
3136
3137    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3138        if (DEBUG_COMPRESSION) {
3139            Slog.i(TAG, "Decompress file"
3140                    + "; src: " + srcFile.getAbsolutePath()
3141                    + ", dst: " + dstFile.getAbsolutePath());
3142        }
3143        try (
3144                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3145                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3146        ) {
3147            Streams.copy(fileIn, fileOut);
3148            Os.chmod(dstFile.getAbsolutePath(), 0644);
3149            return PackageManager.INSTALL_SUCCEEDED;
3150        } catch (IOException e) {
3151            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3152                    + "; src: " + srcFile.getAbsolutePath()
3153                    + ", dst: " + dstFile.getAbsolutePath());
3154        }
3155        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3156    }
3157
3158    private File[] getCompressedFiles(String codePath) {
3159        final File stubCodePath = new File(codePath);
3160        final String stubName = stubCodePath.getName();
3161
3162        // The layout of a compressed package on a given partition is as follows :
3163        //
3164        // Compressed artifacts:
3165        //
3166        // /partition/ModuleName/foo.gz
3167        // /partation/ModuleName/bar.gz
3168        //
3169        // Stub artifact:
3170        //
3171        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3172        //
3173        // In other words, stub is on the same partition as the compressed artifacts
3174        // and in a directory that's suffixed with "-Stub".
3175        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3176        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3177            return null;
3178        }
3179
3180        final File stubParentDir = stubCodePath.getParentFile();
3181        if (stubParentDir == null) {
3182            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3183            return null;
3184        }
3185
3186        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3187        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3188            @Override
3189            public boolean accept(File dir, String name) {
3190                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3191            }
3192        });
3193
3194        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3195            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3196        }
3197
3198        return files;
3199    }
3200
3201    private boolean compressedFileExists(String codePath) {
3202        final File[] compressedFiles = getCompressedFiles(codePath);
3203        return compressedFiles != null && compressedFiles.length > 0;
3204    }
3205
3206    /**
3207     * Decompresses the given package on the system image onto
3208     * the /data partition.
3209     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3210     */
3211    private File decompressPackage(PackageParser.Package pkg) {
3212        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3213        if (compressedFiles == null || compressedFiles.length == 0) {
3214            if (DEBUG_COMPRESSION) {
3215                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3216            }
3217            return null;
3218        }
3219        final File dstCodePath =
3220                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3221        int ret = PackageManager.INSTALL_SUCCEEDED;
3222        try {
3223            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3224            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3225            for (File srcFile : compressedFiles) {
3226                final String srcFileName = srcFile.getName();
3227                final String dstFileName = srcFileName.substring(
3228                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3229                final File dstFile = new File(dstCodePath, dstFileName);
3230                ret = decompressFile(srcFile, dstFile);
3231                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3232                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3233                            + "; pkg: " + pkg.packageName
3234                            + ", file: " + dstFileName);
3235                    break;
3236                }
3237            }
3238        } catch (ErrnoException e) {
3239            logCriticalInfo(Log.ERROR, "Failed to decompress"
3240                    + "; pkg: " + pkg.packageName
3241                    + ", err: " + e.errno);
3242        }
3243        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3244            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3245            NativeLibraryHelper.Handle handle = null;
3246            try {
3247                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3248                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3249                        null /*abiOverride*/);
3250            } catch (IOException e) {
3251                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3252                        + "; pkg: " + pkg.packageName);
3253                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3254            } finally {
3255                IoUtils.closeQuietly(handle);
3256            }
3257        }
3258        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3259            if (dstCodePath == null || !dstCodePath.exists()) {
3260                return null;
3261            }
3262            removeCodePathLI(dstCodePath);
3263            return null;
3264        }
3265
3266        // If we have a profile for a compressed APK, copy it to the reference location.
3267        // Since the package is the stub one, remove the stub suffix to get the normal package and
3268        // APK name.
3269        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3270        if (profileFile.exists()) {
3271            try {
3272                // We could also do this lazily before calling dexopt in
3273                // PackageDexOptimizer to prevent this happening on first boot. The issue
3274                // is that we don't have a good way to say "do this only once".
3275                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3276                        pkg.applicationInfo.uid, pkg.packageName)) {
3277                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3278                }
3279            } catch (Exception e) {
3280                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3281            }
3282        }
3283        return dstCodePath;
3284    }
3285
3286    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3287        // we're only interested in updating the installer appliction when 1) it's not
3288        // already set or 2) the modified package is the installer
3289        if (mInstantAppInstallerActivity != null
3290                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3291                        .equals(modifiedPackage)) {
3292            return;
3293        }
3294        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3295    }
3296
3297    private static File preparePackageParserCache(boolean isUpgrade) {
3298        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3299            return null;
3300        }
3301
3302        // Disable package parsing on eng builds to allow for faster incremental development.
3303        if (Build.IS_ENG) {
3304            return null;
3305        }
3306
3307        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3308            Slog.i(TAG, "Disabling package parser cache due to system property.");
3309            return null;
3310        }
3311
3312        // The base directory for the package parser cache lives under /data/system/.
3313        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3314                "package_cache");
3315        if (cacheBaseDir == null) {
3316            return null;
3317        }
3318
3319        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3320        // This also serves to "GC" unused entries when the package cache version changes (which
3321        // can only happen during upgrades).
3322        if (isUpgrade) {
3323            FileUtils.deleteContents(cacheBaseDir);
3324        }
3325
3326
3327        // Return the versioned package cache directory. This is something like
3328        // "/data/system/package_cache/1"
3329        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3330
3331        // The following is a workaround to aid development on non-numbered userdebug
3332        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3333        // the system partition is newer.
3334        //
3335        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3336        // that starts with "eng." to signify that this is an engineering build and not
3337        // destined for release.
3338        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3339            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3340
3341            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3342            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3343            // in general and should not be used for production changes. In this specific case,
3344            // we know that they will work.
3345            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3346            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3347                FileUtils.deleteContents(cacheBaseDir);
3348                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3349            }
3350        }
3351
3352        return cacheDir;
3353    }
3354
3355    @Override
3356    public boolean isFirstBoot() {
3357        // allow instant applications
3358        return mFirstBoot;
3359    }
3360
3361    @Override
3362    public boolean isOnlyCoreApps() {
3363        // allow instant applications
3364        return mOnlyCore;
3365    }
3366
3367    @Override
3368    public boolean isUpgrade() {
3369        // allow instant applications
3370        return mIsUpgrade;
3371    }
3372
3373    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3374        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3375
3376        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3377                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3378                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3379        if (matches.size() == 1) {
3380            return matches.get(0).getComponentInfo().packageName;
3381        } else if (matches.size() == 0) {
3382            Log.e(TAG, "There should probably be a verifier, but, none were found");
3383            return null;
3384        }
3385        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3386    }
3387
3388    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3389        synchronized (mPackages) {
3390            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3391            if (libraryEntry == null) {
3392                throw new IllegalStateException("Missing required shared library:" + name);
3393            }
3394            return libraryEntry.apk;
3395        }
3396    }
3397
3398    private @NonNull String getRequiredInstallerLPr() {
3399        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3400        intent.addCategory(Intent.CATEGORY_DEFAULT);
3401        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3402
3403        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3404                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3405                UserHandle.USER_SYSTEM);
3406        if (matches.size() == 1) {
3407            ResolveInfo resolveInfo = matches.get(0);
3408            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3409                throw new RuntimeException("The installer must be a privileged app");
3410            }
3411            return matches.get(0).getComponentInfo().packageName;
3412        } else {
3413            throw new RuntimeException("There must be exactly one installer; found " + matches);
3414        }
3415    }
3416
3417    private @NonNull String getRequiredUninstallerLPr() {
3418        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3419        intent.addCategory(Intent.CATEGORY_DEFAULT);
3420        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3421
3422        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM);
3425        if (resolveInfo == null ||
3426                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3427            throw new RuntimeException("There must be exactly one uninstaller; found "
3428                    + resolveInfo);
3429        }
3430        return resolveInfo.getComponentInfo().packageName;
3431    }
3432
3433    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3434        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3435
3436        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3437                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3438                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3439        ResolveInfo best = null;
3440        final int N = matches.size();
3441        for (int i = 0; i < N; i++) {
3442            final ResolveInfo cur = matches.get(i);
3443            final String packageName = cur.getComponentInfo().packageName;
3444            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3445                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3446                continue;
3447            }
3448
3449            if (best == null || cur.priority > best.priority) {
3450                best = cur;
3451            }
3452        }
3453
3454        if (best != null) {
3455            return best.getComponentInfo().getComponentName();
3456        }
3457        Slog.w(TAG, "Intent filter verifier not found");
3458        return null;
3459    }
3460
3461    @Override
3462    public @Nullable ComponentName getInstantAppResolverComponent() {
3463        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3464            return null;
3465        }
3466        synchronized (mPackages) {
3467            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3468            if (instantAppResolver == null) {
3469                return null;
3470            }
3471            return instantAppResolver.first;
3472        }
3473    }
3474
3475    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3476        final String[] packageArray =
3477                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3478        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3481            }
3482            return null;
3483        }
3484
3485        final int callingUid = Binder.getCallingUid();
3486        final int resolveFlags =
3487                MATCH_DIRECT_BOOT_AWARE
3488                | MATCH_DIRECT_BOOT_UNAWARE
3489                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3490        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3491        final Intent resolverIntent = new Intent(actionName);
3492        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3493                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3494        // temporarily look for the old action
3495        if (resolvers.size() == 0) {
3496            if (DEBUG_EPHEMERAL) {
3497                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3498            }
3499            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3500            resolverIntent.setAction(actionName);
3501            resolvers = queryIntentServicesInternal(resolverIntent, null,
3502                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3503        }
3504        final int N = resolvers.size();
3505        if (N == 0) {
3506            if (DEBUG_EPHEMERAL) {
3507                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3508            }
3509            return null;
3510        }
3511
3512        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3513        for (int i = 0; i < N; i++) {
3514            final ResolveInfo info = resolvers.get(i);
3515
3516            if (info.serviceInfo == null) {
3517                continue;
3518            }
3519
3520            final String packageName = info.serviceInfo.packageName;
3521            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3522                if (DEBUG_EPHEMERAL) {
3523                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3524                            + " pkg: " + packageName + ", info:" + info);
3525                }
3526                continue;
3527            }
3528
3529            if (DEBUG_EPHEMERAL) {
3530                Slog.v(TAG, "Ephemeral resolver found;"
3531                        + " pkg: " + packageName + ", info:" + info);
3532            }
3533            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3534        }
3535        if (DEBUG_EPHEMERAL) {
3536            Slog.v(TAG, "Ephemeral resolver NOT found");
3537        }
3538        return null;
3539    }
3540
3541    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3542        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3543        intent.addCategory(Intent.CATEGORY_DEFAULT);
3544        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3545
3546        final int resolveFlags =
3547                MATCH_DIRECT_BOOT_AWARE
3548                | MATCH_DIRECT_BOOT_UNAWARE
3549                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3550        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3551                resolveFlags, UserHandle.USER_SYSTEM);
3552        // temporarily look for the old action
3553        if (matches.isEmpty()) {
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3556            }
3557            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3558            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3559                    resolveFlags, UserHandle.USER_SYSTEM);
3560        }
3561        Iterator<ResolveInfo> iter = matches.iterator();
3562        while (iter.hasNext()) {
3563            final ResolveInfo rInfo = iter.next();
3564            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3565            if (ps != null) {
3566                final PermissionsState permissionsState = ps.getPermissionsState();
3567                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3568                    continue;
3569                }
3570            }
3571            iter.remove();
3572        }
3573        if (matches.size() == 0) {
3574            return null;
3575        } else if (matches.size() == 1) {
3576            return (ActivityInfo) matches.get(0).getComponentInfo();
3577        } else {
3578            throw new RuntimeException(
3579                    "There must be at most one ephemeral installer; found " + matches);
3580        }
3581    }
3582
3583    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3584            @NonNull ComponentName resolver) {
3585        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3586                .addCategory(Intent.CATEGORY_DEFAULT)
3587                .setPackage(resolver.getPackageName());
3588        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3589        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3590                UserHandle.USER_SYSTEM);
3591        // temporarily look for the old action
3592        if (matches.isEmpty()) {
3593            if (DEBUG_EPHEMERAL) {
3594                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3595            }
3596            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3597            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3598                    UserHandle.USER_SYSTEM);
3599        }
3600        if (matches.isEmpty()) {
3601            return null;
3602        }
3603        return matches.get(0).getComponentInfo().getComponentName();
3604    }
3605
3606    private void primeDomainVerificationsLPw(int userId) {
3607        if (DEBUG_DOMAIN_VERIFICATION) {
3608            Slog.d(TAG, "Priming domain verifications in user " + userId);
3609        }
3610
3611        SystemConfig systemConfig = SystemConfig.getInstance();
3612        ArraySet<String> packages = systemConfig.getLinkedApps();
3613
3614        for (String packageName : packages) {
3615            PackageParser.Package pkg = mPackages.get(packageName);
3616            if (pkg != null) {
3617                if (!pkg.isSystemApp()) {
3618                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3619                    continue;
3620                }
3621
3622                ArraySet<String> domains = null;
3623                for (PackageParser.Activity a : pkg.activities) {
3624                    for (ActivityIntentInfo filter : a.intents) {
3625                        if (hasValidDomains(filter)) {
3626                            if (domains == null) {
3627                                domains = new ArraySet<String>();
3628                            }
3629                            domains.addAll(filter.getHostsList());
3630                        }
3631                    }
3632                }
3633
3634                if (domains != null && domains.size() > 0) {
3635                    if (DEBUG_DOMAIN_VERIFICATION) {
3636                        Slog.v(TAG, "      + " + packageName);
3637                    }
3638                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3639                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3640                    // and then 'always' in the per-user state actually used for intent resolution.
3641                    final IntentFilterVerificationInfo ivi;
3642                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3643                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3644                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3645                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3646                } else {
3647                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3648                            + "' does not handle web links");
3649                }
3650            } else {
3651                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3652            }
3653        }
3654
3655        scheduleWritePackageRestrictionsLocked(userId);
3656        scheduleWriteSettingsLocked();
3657    }
3658
3659    private void applyFactoryDefaultBrowserLPw(int userId) {
3660        // The default browser app's package name is stored in a string resource,
3661        // with a product-specific overlay used for vendor customization.
3662        String browserPkg = mContext.getResources().getString(
3663                com.android.internal.R.string.default_browser);
3664        if (!TextUtils.isEmpty(browserPkg)) {
3665            // non-empty string => required to be a known package
3666            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3667            if (ps == null) {
3668                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3669                browserPkg = null;
3670            } else {
3671                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3672            }
3673        }
3674
3675        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3676        // default.  If there's more than one, just leave everything alone.
3677        if (browserPkg == null) {
3678            calculateDefaultBrowserLPw(userId);
3679        }
3680    }
3681
3682    private void calculateDefaultBrowserLPw(int userId) {
3683        List<String> allBrowsers = resolveAllBrowserApps(userId);
3684        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3685        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3686    }
3687
3688    private List<String> resolveAllBrowserApps(int userId) {
3689        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3690        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3691                PackageManager.MATCH_ALL, userId);
3692
3693        final int count = list.size();
3694        List<String> result = new ArrayList<String>(count);
3695        for (int i=0; i<count; i++) {
3696            ResolveInfo info = list.get(i);
3697            if (info.activityInfo == null
3698                    || !info.handleAllWebDataURI
3699                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3700                    || result.contains(info.activityInfo.packageName)) {
3701                continue;
3702            }
3703            result.add(info.activityInfo.packageName);
3704        }
3705
3706        return result;
3707    }
3708
3709    private boolean packageIsBrowser(String packageName, int userId) {
3710        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3711                PackageManager.MATCH_ALL, userId);
3712        final int N = list.size();
3713        for (int i = 0; i < N; i++) {
3714            ResolveInfo info = list.get(i);
3715            if (packageName.equals(info.activityInfo.packageName)) {
3716                return true;
3717            }
3718        }
3719        return false;
3720    }
3721
3722    private void checkDefaultBrowser() {
3723        final int myUserId = UserHandle.myUserId();
3724        final String packageName = getDefaultBrowserPackageName(myUserId);
3725        if (packageName != null) {
3726            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3727            if (info == null) {
3728                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3729                synchronized (mPackages) {
3730                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3731                }
3732            }
3733        }
3734    }
3735
3736    @Override
3737    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3738            throws RemoteException {
3739        try {
3740            return super.onTransact(code, data, reply, flags);
3741        } catch (RuntimeException e) {
3742            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3743                Slog.wtf(TAG, "Package Manager Crash", e);
3744            }
3745            throw e;
3746        }
3747    }
3748
3749    static int[] appendInts(int[] cur, int[] add) {
3750        if (add == null) return cur;
3751        if (cur == null) return add;
3752        final int N = add.length;
3753        for (int i=0; i<N; i++) {
3754            cur = appendInt(cur, add[i]);
3755        }
3756        return cur;
3757    }
3758
3759    /**
3760     * Returns whether or not a full application can see an instant application.
3761     * <p>
3762     * Currently, there are three cases in which this can occur:
3763     * <ol>
3764     * <li>The calling application is a "special" process. The special
3765     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3766     *     and {@code 0}</li>
3767     * <li>The calling application has the permission
3768     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3769     * <li>The calling application is the default launcher on the
3770     *     system partition.</li>
3771     * </ol>
3772     */
3773    private boolean canViewInstantApps(int callingUid, int userId) {
3774        if (callingUid == Process.SYSTEM_UID
3775                || callingUid == Process.SHELL_UID
3776                || callingUid == Process.ROOT_UID) {
3777            return true;
3778        }
3779        if (mContext.checkCallingOrSelfPermission(
3780                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3781            return true;
3782        }
3783        if (mContext.checkCallingOrSelfPermission(
3784                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3785            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3786            if (homeComponent != null
3787                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3788                return true;
3789            }
3790        }
3791        return false;
3792    }
3793
3794    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3795        if (!sUserManager.exists(userId)) return null;
3796        if (ps == null) {
3797            return null;
3798        }
3799        PackageParser.Package p = ps.pkg;
3800        if (p == null) {
3801            return null;
3802        }
3803        final int callingUid = Binder.getCallingUid();
3804        // Filter out ephemeral app metadata:
3805        //   * The system/shell/root can see metadata for any app
3806        //   * An installed app can see metadata for 1) other installed apps
3807        //     and 2) ephemeral apps that have explicitly interacted with it
3808        //   * Ephemeral apps can only see their own data and exposed installed apps
3809        //   * Holding a signature permission allows seeing instant apps
3810        if (filterAppAccessLPr(ps, callingUid, userId)) {
3811            return null;
3812        }
3813
3814        final PermissionsState permissionsState = ps.getPermissionsState();
3815
3816        // Compute GIDs only if requested
3817        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3818                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3819        // Compute granted permissions only if package has requested permissions
3820        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3821                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3822        final PackageUserState state = ps.readUserState(userId);
3823
3824        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3825                && ps.isSystem()) {
3826            flags |= MATCH_ANY_USER;
3827        }
3828
3829        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3830                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3831
3832        if (packageInfo == null) {
3833            return null;
3834        }
3835
3836        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3837                resolveExternalPackageNameLPr(p);
3838
3839        return packageInfo;
3840    }
3841
3842    @Override
3843    public void checkPackageStartable(String packageName, int userId) {
3844        final int callingUid = Binder.getCallingUid();
3845        if (getInstantAppPackageName(callingUid) != null) {
3846            throw new SecurityException("Instant applications don't have access to this method");
3847        }
3848        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3849        synchronized (mPackages) {
3850            final PackageSetting ps = mSettings.mPackages.get(packageName);
3851            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3852                throw new SecurityException("Package " + packageName + " was not found!");
3853            }
3854
3855            if (!ps.getInstalled(userId)) {
3856                throw new SecurityException(
3857                        "Package " + packageName + " was not installed for user " + userId + "!");
3858            }
3859
3860            if (mSafeMode && !ps.isSystem()) {
3861                throw new SecurityException("Package " + packageName + " not a system app!");
3862            }
3863
3864            if (mFrozenPackages.contains(packageName)) {
3865                throw new SecurityException("Package " + packageName + " is currently frozen!");
3866            }
3867
3868            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3869                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3870            }
3871        }
3872    }
3873
3874    @Override
3875    public boolean isPackageAvailable(String packageName, int userId) {
3876        if (!sUserManager.exists(userId)) return false;
3877        final int callingUid = Binder.getCallingUid();
3878        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3879                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3880        synchronized (mPackages) {
3881            PackageParser.Package p = mPackages.get(packageName);
3882            if (p != null) {
3883                final PackageSetting ps = (PackageSetting) p.mExtras;
3884                if (filterAppAccessLPr(ps, callingUid, userId)) {
3885                    return false;
3886                }
3887                if (ps != null) {
3888                    final PackageUserState state = ps.readUserState(userId);
3889                    if (state != null) {
3890                        return PackageParser.isAvailable(state);
3891                    }
3892                }
3893            }
3894        }
3895        return false;
3896    }
3897
3898    @Override
3899    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3900        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3901                flags, Binder.getCallingUid(), userId);
3902    }
3903
3904    @Override
3905    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3906            int flags, int userId) {
3907        return getPackageInfoInternal(versionedPackage.getPackageName(),
3908                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3909    }
3910
3911    /**
3912     * Important: The provided filterCallingUid is used exclusively to filter out packages
3913     * that can be seen based on user state. It's typically the original caller uid prior
3914     * to clearing. Because it can only be provided by trusted code, it's value can be
3915     * trusted and will be used as-is; unlike userId which will be validated by this method.
3916     */
3917    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3918            int flags, int filterCallingUid, int userId) {
3919        if (!sUserManager.exists(userId)) return null;
3920        flags = updateFlagsForPackage(flags, userId, packageName);
3921        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3922                false /* requireFullPermission */, false /* checkShell */, "get package info");
3923
3924        // reader
3925        synchronized (mPackages) {
3926            // Normalize package name to handle renamed packages and static libs
3927            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3928
3929            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3930            if (matchFactoryOnly) {
3931                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3932                if (ps != null) {
3933                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3934                        return null;
3935                    }
3936                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3937                        return null;
3938                    }
3939                    return generatePackageInfo(ps, flags, userId);
3940                }
3941            }
3942
3943            PackageParser.Package p = mPackages.get(packageName);
3944            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3945                return null;
3946            }
3947            if (DEBUG_PACKAGE_INFO)
3948                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3949            if (p != null) {
3950                final PackageSetting ps = (PackageSetting) p.mExtras;
3951                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3952                    return null;
3953                }
3954                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3955                    return null;
3956                }
3957                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3958            }
3959            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3960                final PackageSetting ps = mSettings.mPackages.get(packageName);
3961                if (ps == null) return null;
3962                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3963                    return null;
3964                }
3965                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3966                    return null;
3967                }
3968                return generatePackageInfo(ps, flags, userId);
3969            }
3970        }
3971        return null;
3972    }
3973
3974    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3975        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3976            return true;
3977        }
3978        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3979            return true;
3980        }
3981        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3982            return true;
3983        }
3984        return false;
3985    }
3986
3987    private boolean isComponentVisibleToInstantApp(
3988            @Nullable ComponentName component, @ComponentType int type) {
3989        if (type == TYPE_ACTIVITY) {
3990            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3991            return activity != null
3992                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3993                    : false;
3994        } else if (type == TYPE_RECEIVER) {
3995            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3996            return activity != null
3997                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3998                    : false;
3999        } else if (type == TYPE_SERVICE) {
4000            final PackageParser.Service service = mServices.mServices.get(component);
4001            return service != null
4002                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4003                    : false;
4004        } else if (type == TYPE_PROVIDER) {
4005            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4006            return provider != null
4007                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4008                    : false;
4009        } else if (type == TYPE_UNKNOWN) {
4010            return isComponentVisibleToInstantApp(component);
4011        }
4012        return false;
4013    }
4014
4015    /**
4016     * Returns whether or not access to the application should be filtered.
4017     * <p>
4018     * Access may be limited based upon whether the calling or target applications
4019     * are instant applications.
4020     *
4021     * @see #canAccessInstantApps(int)
4022     */
4023    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4024            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4025        // if we're in an isolated process, get the real calling UID
4026        if (Process.isIsolated(callingUid)) {
4027            callingUid = mIsolatedOwners.get(callingUid);
4028        }
4029        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4030        final boolean callerIsInstantApp = instantAppPkgName != null;
4031        if (ps == null) {
4032            if (callerIsInstantApp) {
4033                // pretend the application exists, but, needs to be filtered
4034                return true;
4035            }
4036            return false;
4037        }
4038        // if the target and caller are the same application, don't filter
4039        if (isCallerSameApp(ps.name, callingUid)) {
4040            return false;
4041        }
4042        if (callerIsInstantApp) {
4043            // request for a specific component; if it hasn't been explicitly exposed, filter
4044            if (component != null) {
4045                return !isComponentVisibleToInstantApp(component, componentType);
4046            }
4047            // request for application; if no components have been explicitly exposed, filter
4048            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4049        }
4050        if (ps.getInstantApp(userId)) {
4051            // caller can see all components of all instant applications, don't filter
4052            if (canViewInstantApps(callingUid, userId)) {
4053                return false;
4054            }
4055            // request for a specific instant application component, filter
4056            if (component != null) {
4057                return true;
4058            }
4059            // request for an instant application; if the caller hasn't been granted access, filter
4060            return !mInstantAppRegistry.isInstantAccessGranted(
4061                    userId, UserHandle.getAppId(callingUid), ps.appId);
4062        }
4063        return false;
4064    }
4065
4066    /**
4067     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4068     */
4069    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4070        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4071    }
4072
4073    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4074            int flags) {
4075        // Callers can access only the libs they depend on, otherwise they need to explicitly
4076        // ask for the shared libraries given the caller is allowed to access all static libs.
4077        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4078            // System/shell/root get to see all static libs
4079            final int appId = UserHandle.getAppId(uid);
4080            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4081                    || appId == Process.ROOT_UID) {
4082                return false;
4083            }
4084        }
4085
4086        // No package means no static lib as it is always on internal storage
4087        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4088            return false;
4089        }
4090
4091        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4092                ps.pkg.staticSharedLibVersion);
4093        if (libEntry == null) {
4094            return false;
4095        }
4096
4097        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4098        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4099        if (uidPackageNames == null) {
4100            return true;
4101        }
4102
4103        for (String uidPackageName : uidPackageNames) {
4104            if (ps.name.equals(uidPackageName)) {
4105                return false;
4106            }
4107            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4108            if (uidPs != null) {
4109                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4110                        libEntry.info.getName());
4111                if (index < 0) {
4112                    continue;
4113                }
4114                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4115                    return false;
4116                }
4117            }
4118        }
4119        return true;
4120    }
4121
4122    @Override
4123    public String[] currentToCanonicalPackageNames(String[] names) {
4124        final int callingUid = Binder.getCallingUid();
4125        if (getInstantAppPackageName(callingUid) != null) {
4126            return names;
4127        }
4128        final String[] out = new String[names.length];
4129        // reader
4130        synchronized (mPackages) {
4131            final int callingUserId = UserHandle.getUserId(callingUid);
4132            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4133            for (int i=names.length-1; i>=0; i--) {
4134                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4135                boolean translateName = false;
4136                if (ps != null && ps.realName != null) {
4137                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4138                    translateName = !targetIsInstantApp
4139                            || canViewInstantApps
4140                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4141                                    UserHandle.getAppId(callingUid), ps.appId);
4142                }
4143                out[i] = translateName ? ps.realName : names[i];
4144            }
4145        }
4146        return out;
4147    }
4148
4149    @Override
4150    public String[] canonicalToCurrentPackageNames(String[] names) {
4151        final int callingUid = Binder.getCallingUid();
4152        if (getInstantAppPackageName(callingUid) != null) {
4153            return names;
4154        }
4155        final String[] out = new String[names.length];
4156        // reader
4157        synchronized (mPackages) {
4158            final int callingUserId = UserHandle.getUserId(callingUid);
4159            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4160            for (int i=names.length-1; i>=0; i--) {
4161                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4162                boolean translateName = false;
4163                if (cur != null) {
4164                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4165                    final boolean targetIsInstantApp =
4166                            ps != null && ps.getInstantApp(callingUserId);
4167                    translateName = !targetIsInstantApp
4168                            || canViewInstantApps
4169                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4170                                    UserHandle.getAppId(callingUid), ps.appId);
4171                }
4172                out[i] = translateName ? cur : names[i];
4173            }
4174        }
4175        return out;
4176    }
4177
4178    @Override
4179    public int getPackageUid(String packageName, int flags, int userId) {
4180        if (!sUserManager.exists(userId)) return -1;
4181        final int callingUid = Binder.getCallingUid();
4182        flags = updateFlagsForPackage(flags, userId, packageName);
4183        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4184                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4185
4186        // reader
4187        synchronized (mPackages) {
4188            final PackageParser.Package p = mPackages.get(packageName);
4189            if (p != null && p.isMatch(flags)) {
4190                PackageSetting ps = (PackageSetting) p.mExtras;
4191                if (filterAppAccessLPr(ps, callingUid, userId)) {
4192                    return -1;
4193                }
4194                return UserHandle.getUid(userId, p.applicationInfo.uid);
4195            }
4196            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4197                final PackageSetting ps = mSettings.mPackages.get(packageName);
4198                if (ps != null && ps.isMatch(flags)
4199                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4200                    return UserHandle.getUid(userId, ps.appId);
4201                }
4202            }
4203        }
4204
4205        return -1;
4206    }
4207
4208    @Override
4209    public int[] getPackageGids(String packageName, int flags, int userId) {
4210        if (!sUserManager.exists(userId)) return null;
4211        final int callingUid = Binder.getCallingUid();
4212        flags = updateFlagsForPackage(flags, userId, packageName);
4213        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4214                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4215
4216        // reader
4217        synchronized (mPackages) {
4218            final PackageParser.Package p = mPackages.get(packageName);
4219            if (p != null && p.isMatch(flags)) {
4220                PackageSetting ps = (PackageSetting) p.mExtras;
4221                if (filterAppAccessLPr(ps, callingUid, userId)) {
4222                    return null;
4223                }
4224                // TODO: Shouldn't this be checking for package installed state for userId and
4225                // return null?
4226                return ps.getPermissionsState().computeGids(userId);
4227            }
4228            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4229                final PackageSetting ps = mSettings.mPackages.get(packageName);
4230                if (ps != null && ps.isMatch(flags)
4231                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4232                    return ps.getPermissionsState().computeGids(userId);
4233                }
4234            }
4235        }
4236
4237        return null;
4238    }
4239
4240    @Override
4241    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4242        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4243    }
4244
4245    @Override
4246    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4247            int flags) {
4248        // TODO Move this to PermissionManager when mPermissionGroups is moved there
4249        synchronized (mPackages) {
4250            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4251                // This is thrown as NameNotFoundException
4252                return null;
4253            }
4254        }
4255        return new ParceledListSlice<>(
4256                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()));
4257    }
4258
4259    @Override
4260    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4261        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4262            return null;
4263        }
4264        // reader
4265        synchronized (mPackages) {
4266            return PackageParser.generatePermissionGroupInfo(
4267                    mPermissionGroups.get(name), flags);
4268        }
4269    }
4270
4271    @Override
4272    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4273        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4274            return ParceledListSlice.emptyList();
4275        }
4276        // reader
4277        synchronized (mPackages) {
4278            final int N = mPermissionGroups.size();
4279            ArrayList<PermissionGroupInfo> out
4280                    = new ArrayList<PermissionGroupInfo>(N);
4281            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4282                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4283            }
4284            return new ParceledListSlice<>(out);
4285        }
4286    }
4287
4288    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4289            int filterCallingUid, int userId) {
4290        if (!sUserManager.exists(userId)) return null;
4291        PackageSetting ps = mSettings.mPackages.get(packageName);
4292        if (ps != null) {
4293            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4294                return null;
4295            }
4296            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4297                return null;
4298            }
4299            if (ps.pkg == null) {
4300                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4301                if (pInfo != null) {
4302                    return pInfo.applicationInfo;
4303                }
4304                return null;
4305            }
4306            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4307                    ps.readUserState(userId), userId);
4308            if (ai != null) {
4309                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4310            }
4311            return ai;
4312        }
4313        return null;
4314    }
4315
4316    @Override
4317    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4318        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4319    }
4320
4321    /**
4322     * Important: The provided filterCallingUid is used exclusively to filter out applications
4323     * that can be seen based on user state. It's typically the original caller uid prior
4324     * to clearing. Because it can only be provided by trusted code, it's value can be
4325     * trusted and will be used as-is; unlike userId which will be validated by this method.
4326     */
4327    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4328            int filterCallingUid, int userId) {
4329        if (!sUserManager.exists(userId)) return null;
4330        flags = updateFlagsForApplication(flags, userId, packageName);
4331        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4332                false /* requireFullPermission */, false /* checkShell */, "get application info");
4333
4334        // writer
4335        synchronized (mPackages) {
4336            // Normalize package name to handle renamed packages and static libs
4337            packageName = resolveInternalPackageNameLPr(packageName,
4338                    PackageManager.VERSION_CODE_HIGHEST);
4339
4340            PackageParser.Package p = mPackages.get(packageName);
4341            if (DEBUG_PACKAGE_INFO) Log.v(
4342                    TAG, "getApplicationInfo " + packageName
4343                    + ": " + p);
4344            if (p != null) {
4345                PackageSetting ps = mSettings.mPackages.get(packageName);
4346                if (ps == null) return null;
4347                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4348                    return null;
4349                }
4350                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4351                    return null;
4352                }
4353                // Note: isEnabledLP() does not apply here - always return info
4354                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4355                        p, flags, ps.readUserState(userId), userId);
4356                if (ai != null) {
4357                    ai.packageName = resolveExternalPackageNameLPr(p);
4358                }
4359                return ai;
4360            }
4361            if ("android".equals(packageName)||"system".equals(packageName)) {
4362                return mAndroidApplication;
4363            }
4364            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4365                // Already generates the external package name
4366                return generateApplicationInfoFromSettingsLPw(packageName,
4367                        flags, filterCallingUid, userId);
4368            }
4369        }
4370        return null;
4371    }
4372
4373    private String normalizePackageNameLPr(String packageName) {
4374        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4375        return normalizedPackageName != null ? normalizedPackageName : packageName;
4376    }
4377
4378    @Override
4379    public void deletePreloadsFileCache() {
4380        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4381            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4382        }
4383        File dir = Environment.getDataPreloadsFileCacheDirectory();
4384        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4385        FileUtils.deleteContents(dir);
4386    }
4387
4388    @Override
4389    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4390            final int storageFlags, final IPackageDataObserver observer) {
4391        mContext.enforceCallingOrSelfPermission(
4392                android.Manifest.permission.CLEAR_APP_CACHE, null);
4393        mHandler.post(() -> {
4394            boolean success = false;
4395            try {
4396                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4397                success = true;
4398            } catch (IOException e) {
4399                Slog.w(TAG, e);
4400            }
4401            if (observer != null) {
4402                try {
4403                    observer.onRemoveCompleted(null, success);
4404                } catch (RemoteException e) {
4405                    Slog.w(TAG, e);
4406                }
4407            }
4408        });
4409    }
4410
4411    @Override
4412    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4413            final int storageFlags, final IntentSender pi) {
4414        mContext.enforceCallingOrSelfPermission(
4415                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4416        mHandler.post(() -> {
4417            boolean success = false;
4418            try {
4419                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4420                success = true;
4421            } catch (IOException e) {
4422                Slog.w(TAG, e);
4423            }
4424            if (pi != null) {
4425                try {
4426                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4427                } catch (SendIntentException e) {
4428                    Slog.w(TAG, e);
4429                }
4430            }
4431        });
4432    }
4433
4434    /**
4435     * Blocking call to clear various types of cached data across the system
4436     * until the requested bytes are available.
4437     */
4438    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4439        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4440        final File file = storage.findPathForUuid(volumeUuid);
4441        if (file.getUsableSpace() >= bytes) return;
4442
4443        if (ENABLE_FREE_CACHE_V2) {
4444            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4445                    volumeUuid);
4446            final boolean aggressive = (storageFlags
4447                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4448            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4449
4450            // 1. Pre-flight to determine if we have any chance to succeed
4451            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4452            if (internalVolume && (aggressive || SystemProperties
4453                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4454                deletePreloadsFileCache();
4455                if (file.getUsableSpace() >= bytes) return;
4456            }
4457
4458            // 3. Consider parsed APK data (aggressive only)
4459            if (internalVolume && aggressive) {
4460                FileUtils.deleteContents(mCacheDir);
4461                if (file.getUsableSpace() >= bytes) return;
4462            }
4463
4464            // 4. Consider cached app data (above quotas)
4465            try {
4466                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4467                        Installer.FLAG_FREE_CACHE_V2);
4468            } catch (InstallerException ignored) {
4469            }
4470            if (file.getUsableSpace() >= bytes) return;
4471
4472            // 5. Consider shared libraries with refcount=0 and age>min cache period
4473            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4474                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4475                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4476                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4477                return;
4478            }
4479
4480            // 6. Consider dexopt output (aggressive only)
4481            // TODO: Implement
4482
4483            // 7. Consider installed instant apps unused longer than min cache period
4484            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4485                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4486                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4487                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4488                return;
4489            }
4490
4491            // 8. Consider cached app data (below quotas)
4492            try {
4493                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4494                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4495            } catch (InstallerException ignored) {
4496            }
4497            if (file.getUsableSpace() >= bytes) return;
4498
4499            // 9. Consider DropBox entries
4500            // TODO: Implement
4501
4502            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4503            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4504                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4505                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4506                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4507                return;
4508            }
4509        } else {
4510            try {
4511                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4512            } catch (InstallerException ignored) {
4513            }
4514            if (file.getUsableSpace() >= bytes) return;
4515        }
4516
4517        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4518    }
4519
4520    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4521            throws IOException {
4522        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4523        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4524
4525        List<VersionedPackage> packagesToDelete = null;
4526        final long now = System.currentTimeMillis();
4527
4528        synchronized (mPackages) {
4529            final int[] allUsers = sUserManager.getUserIds();
4530            final int libCount = mSharedLibraries.size();
4531            for (int i = 0; i < libCount; i++) {
4532                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4533                if (versionedLib == null) {
4534                    continue;
4535                }
4536                final int versionCount = versionedLib.size();
4537                for (int j = 0; j < versionCount; j++) {
4538                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4539                    // Skip packages that are not static shared libs.
4540                    if (!libInfo.isStatic()) {
4541                        break;
4542                    }
4543                    // Important: We skip static shared libs used for some user since
4544                    // in such a case we need to keep the APK on the device. The check for
4545                    // a lib being used for any user is performed by the uninstall call.
4546                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4547                    // Resolve the package name - we use synthetic package names internally
4548                    final String internalPackageName = resolveInternalPackageNameLPr(
4549                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4550                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4551                    // Skip unused static shared libs cached less than the min period
4552                    // to prevent pruning a lib needed by a subsequently installed package.
4553                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4554                        continue;
4555                    }
4556                    if (packagesToDelete == null) {
4557                        packagesToDelete = new ArrayList<>();
4558                    }
4559                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4560                            declaringPackage.getVersionCode()));
4561                }
4562            }
4563        }
4564
4565        if (packagesToDelete != null) {
4566            final int packageCount = packagesToDelete.size();
4567            for (int i = 0; i < packageCount; i++) {
4568                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4569                // Delete the package synchronously (will fail of the lib used for any user).
4570                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4571                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4572                                == PackageManager.DELETE_SUCCEEDED) {
4573                    if (volume.getUsableSpace() >= neededSpace) {
4574                        return true;
4575                    }
4576                }
4577            }
4578        }
4579
4580        return false;
4581    }
4582
4583    /**
4584     * Update given flags based on encryption status of current user.
4585     */
4586    private int updateFlags(int flags, int userId) {
4587        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4588                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4589            // Caller expressed an explicit opinion about what encryption
4590            // aware/unaware components they want to see, so fall through and
4591            // give them what they want
4592        } else {
4593            // Caller expressed no opinion, so match based on user state
4594            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4595                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4596            } else {
4597                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4598            }
4599        }
4600        return flags;
4601    }
4602
4603    private UserManagerInternal getUserManagerInternal() {
4604        if (mUserManagerInternal == null) {
4605            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4606        }
4607        return mUserManagerInternal;
4608    }
4609
4610    private DeviceIdleController.LocalService getDeviceIdleController() {
4611        if (mDeviceIdleController == null) {
4612            mDeviceIdleController =
4613                    LocalServices.getService(DeviceIdleController.LocalService.class);
4614        }
4615        return mDeviceIdleController;
4616    }
4617
4618    /**
4619     * Update given flags when being used to request {@link PackageInfo}.
4620     */
4621    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4622        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4623        boolean triaged = true;
4624        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4625                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4626            // Caller is asking for component details, so they'd better be
4627            // asking for specific encryption matching behavior, or be triaged
4628            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4629                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4630                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4631                triaged = false;
4632            }
4633        }
4634        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4635                | PackageManager.MATCH_SYSTEM_ONLY
4636                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4637            triaged = false;
4638        }
4639        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4640            mPermissionManager.enforceCrossUserPermission(
4641                    Binder.getCallingUid(), userId, false, false,
4642                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4643                    + Debug.getCallers(5));
4644        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4645                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4646            // If the caller wants all packages and has a restricted profile associated with it,
4647            // then match all users. This is to make sure that launchers that need to access work
4648            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4649            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4650            flags |= PackageManager.MATCH_ANY_USER;
4651        }
4652        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4653            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4654                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4655        }
4656        return updateFlags(flags, userId);
4657    }
4658
4659    /**
4660     * Update given flags when being used to request {@link ApplicationInfo}.
4661     */
4662    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4663        return updateFlagsForPackage(flags, userId, cookie);
4664    }
4665
4666    /**
4667     * Update given flags when being used to request {@link ComponentInfo}.
4668     */
4669    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4670        if (cookie instanceof Intent) {
4671            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4672                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4673            }
4674        }
4675
4676        boolean triaged = true;
4677        // Caller is asking for component details, so they'd better be
4678        // asking for specific encryption matching behavior, or be triaged
4679        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4680                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4681                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4682            triaged = false;
4683        }
4684        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4685            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4686                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4687        }
4688
4689        return updateFlags(flags, userId);
4690    }
4691
4692    /**
4693     * Update given intent when being used to request {@link ResolveInfo}.
4694     */
4695    private Intent updateIntentForResolve(Intent intent) {
4696        if (intent.getSelector() != null) {
4697            intent = intent.getSelector();
4698        }
4699        if (DEBUG_PREFERRED) {
4700            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4701        }
4702        return intent;
4703    }
4704
4705    /**
4706     * Update given flags when being used to request {@link ResolveInfo}.
4707     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4708     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4709     * flag set. However, this flag is only honoured in three circumstances:
4710     * <ul>
4711     * <li>when called from a system process</li>
4712     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4713     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4714     * action and a {@code android.intent.category.BROWSABLE} category</li>
4715     * </ul>
4716     */
4717    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4718        return updateFlagsForResolve(flags, userId, intent, callingUid,
4719                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4720    }
4721    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4722            boolean wantInstantApps) {
4723        return updateFlagsForResolve(flags, userId, intent, callingUid,
4724                wantInstantApps, false /*onlyExposedExplicitly*/);
4725    }
4726    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4727            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4728        // Safe mode means we shouldn't match any third-party components
4729        if (mSafeMode) {
4730            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4731        }
4732        if (getInstantAppPackageName(callingUid) != null) {
4733            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4734            if (onlyExposedExplicitly) {
4735                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4736            }
4737            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4738            flags |= PackageManager.MATCH_INSTANT;
4739        } else {
4740            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4741            final boolean allowMatchInstant =
4742                    (wantInstantApps
4743                            && Intent.ACTION_VIEW.equals(intent.getAction())
4744                            && hasWebURI(intent))
4745                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4746            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4747                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4748            if (!allowMatchInstant) {
4749                flags &= ~PackageManager.MATCH_INSTANT;
4750            }
4751        }
4752        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4753    }
4754
4755    @Override
4756    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4757        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4758    }
4759
4760    /**
4761     * Important: The provided filterCallingUid is used exclusively to filter out activities
4762     * that can be seen based on user state. It's typically the original caller uid prior
4763     * to clearing. Because it can only be provided by trusted code, it's value can be
4764     * trusted and will be used as-is; unlike userId which will be validated by this method.
4765     */
4766    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4767            int filterCallingUid, int userId) {
4768        if (!sUserManager.exists(userId)) return null;
4769        flags = updateFlagsForComponent(flags, userId, component);
4770        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4771                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4772        synchronized (mPackages) {
4773            PackageParser.Activity a = mActivities.mActivities.get(component);
4774
4775            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4776            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4777                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4778                if (ps == null) return null;
4779                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4780                    return null;
4781                }
4782                return PackageParser.generateActivityInfo(
4783                        a, flags, ps.readUserState(userId), userId);
4784            }
4785            if (mResolveComponentName.equals(component)) {
4786                return PackageParser.generateActivityInfo(
4787                        mResolveActivity, flags, new PackageUserState(), userId);
4788            }
4789        }
4790        return null;
4791    }
4792
4793    @Override
4794    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4795            String resolvedType) {
4796        synchronized (mPackages) {
4797            if (component.equals(mResolveComponentName)) {
4798                // The resolver supports EVERYTHING!
4799                return true;
4800            }
4801            final int callingUid = Binder.getCallingUid();
4802            final int callingUserId = UserHandle.getUserId(callingUid);
4803            PackageParser.Activity a = mActivities.mActivities.get(component);
4804            if (a == null) {
4805                return false;
4806            }
4807            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4808            if (ps == null) {
4809                return false;
4810            }
4811            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4812                return false;
4813            }
4814            for (int i=0; i<a.intents.size(); i++) {
4815                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4816                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4817                    return true;
4818                }
4819            }
4820            return false;
4821        }
4822    }
4823
4824    @Override
4825    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4826        if (!sUserManager.exists(userId)) return null;
4827        final int callingUid = Binder.getCallingUid();
4828        flags = updateFlagsForComponent(flags, userId, component);
4829        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4830                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4831        synchronized (mPackages) {
4832            PackageParser.Activity a = mReceivers.mActivities.get(component);
4833            if (DEBUG_PACKAGE_INFO) Log.v(
4834                TAG, "getReceiverInfo " + component + ": " + a);
4835            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4836                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4837                if (ps == null) return null;
4838                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4839                    return null;
4840                }
4841                return PackageParser.generateActivityInfo(
4842                        a, flags, ps.readUserState(userId), userId);
4843            }
4844        }
4845        return null;
4846    }
4847
4848    @Override
4849    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4850            int flags, int userId) {
4851        if (!sUserManager.exists(userId)) return null;
4852        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4853        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4854            return null;
4855        }
4856
4857        flags = updateFlagsForPackage(flags, userId, null);
4858
4859        final boolean canSeeStaticLibraries =
4860                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4861                        == PERMISSION_GRANTED
4862                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4863                        == PERMISSION_GRANTED
4864                || canRequestPackageInstallsInternal(packageName,
4865                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4866                        false  /* throwIfPermNotDeclared*/)
4867                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4868                        == PERMISSION_GRANTED;
4869
4870        synchronized (mPackages) {
4871            List<SharedLibraryInfo> result = null;
4872
4873            final int libCount = mSharedLibraries.size();
4874            for (int i = 0; i < libCount; i++) {
4875                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4876                if (versionedLib == null) {
4877                    continue;
4878                }
4879
4880                final int versionCount = versionedLib.size();
4881                for (int j = 0; j < versionCount; j++) {
4882                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4883                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4884                        break;
4885                    }
4886                    final long identity = Binder.clearCallingIdentity();
4887                    try {
4888                        PackageInfo packageInfo = getPackageInfoVersioned(
4889                                libInfo.getDeclaringPackage(), flags
4890                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4891                        if (packageInfo == null) {
4892                            continue;
4893                        }
4894                    } finally {
4895                        Binder.restoreCallingIdentity(identity);
4896                    }
4897
4898                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4899                            libInfo.getVersion(), libInfo.getType(),
4900                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4901                            flags, userId));
4902
4903                    if (result == null) {
4904                        result = new ArrayList<>();
4905                    }
4906                    result.add(resLibInfo);
4907                }
4908            }
4909
4910            return result != null ? new ParceledListSlice<>(result) : null;
4911        }
4912    }
4913
4914    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4915            SharedLibraryInfo libInfo, int flags, int userId) {
4916        List<VersionedPackage> versionedPackages = null;
4917        final int packageCount = mSettings.mPackages.size();
4918        for (int i = 0; i < packageCount; i++) {
4919            PackageSetting ps = mSettings.mPackages.valueAt(i);
4920
4921            if (ps == null) {
4922                continue;
4923            }
4924
4925            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4926                continue;
4927            }
4928
4929            final String libName = libInfo.getName();
4930            if (libInfo.isStatic()) {
4931                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4932                if (libIdx < 0) {
4933                    continue;
4934                }
4935                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4936                    continue;
4937                }
4938                if (versionedPackages == null) {
4939                    versionedPackages = new ArrayList<>();
4940                }
4941                // If the dependent is a static shared lib, use the public package name
4942                String dependentPackageName = ps.name;
4943                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4944                    dependentPackageName = ps.pkg.manifestPackageName;
4945                }
4946                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4947            } else if (ps.pkg != null) {
4948                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4949                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4950                    if (versionedPackages == null) {
4951                        versionedPackages = new ArrayList<>();
4952                    }
4953                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4954                }
4955            }
4956        }
4957
4958        return versionedPackages;
4959    }
4960
4961    @Override
4962    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4963        if (!sUserManager.exists(userId)) return null;
4964        final int callingUid = Binder.getCallingUid();
4965        flags = updateFlagsForComponent(flags, userId, component);
4966        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4967                false /* requireFullPermission */, false /* checkShell */, "get service info");
4968        synchronized (mPackages) {
4969            PackageParser.Service s = mServices.mServices.get(component);
4970            if (DEBUG_PACKAGE_INFO) Log.v(
4971                TAG, "getServiceInfo " + component + ": " + s);
4972            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4973                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4974                if (ps == null) return null;
4975                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4976                    return null;
4977                }
4978                return PackageParser.generateServiceInfo(
4979                        s, flags, ps.readUserState(userId), userId);
4980            }
4981        }
4982        return null;
4983    }
4984
4985    @Override
4986    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4987        if (!sUserManager.exists(userId)) return null;
4988        final int callingUid = Binder.getCallingUid();
4989        flags = updateFlagsForComponent(flags, userId, component);
4990        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4991                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4992        synchronized (mPackages) {
4993            PackageParser.Provider p = mProviders.mProviders.get(component);
4994            if (DEBUG_PACKAGE_INFO) Log.v(
4995                TAG, "getProviderInfo " + component + ": " + p);
4996            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4997                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4998                if (ps == null) return null;
4999                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5000                    return null;
5001                }
5002                return PackageParser.generateProviderInfo(
5003                        p, flags, ps.readUserState(userId), userId);
5004            }
5005        }
5006        return null;
5007    }
5008
5009    @Override
5010    public String[] getSystemSharedLibraryNames() {
5011        // allow instant applications
5012        synchronized (mPackages) {
5013            Set<String> libs = null;
5014            final int libCount = mSharedLibraries.size();
5015            for (int i = 0; i < libCount; i++) {
5016                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5017                if (versionedLib == null) {
5018                    continue;
5019                }
5020                final int versionCount = versionedLib.size();
5021                for (int j = 0; j < versionCount; j++) {
5022                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5023                    if (!libEntry.info.isStatic()) {
5024                        if (libs == null) {
5025                            libs = new ArraySet<>();
5026                        }
5027                        libs.add(libEntry.info.getName());
5028                        break;
5029                    }
5030                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5031                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5032                            UserHandle.getUserId(Binder.getCallingUid()),
5033                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5034                        if (libs == null) {
5035                            libs = new ArraySet<>();
5036                        }
5037                        libs.add(libEntry.info.getName());
5038                        break;
5039                    }
5040                }
5041            }
5042
5043            if (libs != null) {
5044                String[] libsArray = new String[libs.size()];
5045                libs.toArray(libsArray);
5046                return libsArray;
5047            }
5048
5049            return null;
5050        }
5051    }
5052
5053    @Override
5054    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5055        // allow instant applications
5056        synchronized (mPackages) {
5057            return mServicesSystemSharedLibraryPackageName;
5058        }
5059    }
5060
5061    @Override
5062    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5063        // allow instant applications
5064        synchronized (mPackages) {
5065            return mSharedSystemSharedLibraryPackageName;
5066        }
5067    }
5068
5069    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5070        for (int i = userList.length - 1; i >= 0; --i) {
5071            final int userId = userList[i];
5072            // don't add instant app to the list of updates
5073            if (pkgSetting.getInstantApp(userId)) {
5074                continue;
5075            }
5076            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5077            if (changedPackages == null) {
5078                changedPackages = new SparseArray<>();
5079                mChangedPackages.put(userId, changedPackages);
5080            }
5081            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5082            if (sequenceNumbers == null) {
5083                sequenceNumbers = new HashMap<>();
5084                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5085            }
5086            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5087            if (sequenceNumber != null) {
5088                changedPackages.remove(sequenceNumber);
5089            }
5090            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5091            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5092        }
5093        mChangedPackagesSequenceNumber++;
5094    }
5095
5096    @Override
5097    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5098        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5099            return null;
5100        }
5101        synchronized (mPackages) {
5102            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5103                return null;
5104            }
5105            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5106            if (changedPackages == null) {
5107                return null;
5108            }
5109            final List<String> packageNames =
5110                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5111            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5112                final String packageName = changedPackages.get(i);
5113                if (packageName != null) {
5114                    packageNames.add(packageName);
5115                }
5116            }
5117            return packageNames.isEmpty()
5118                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5124        // allow instant applications
5125        ArrayList<FeatureInfo> res;
5126        synchronized (mAvailableFeatures) {
5127            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5128            res.addAll(mAvailableFeatures.values());
5129        }
5130        final FeatureInfo fi = new FeatureInfo();
5131        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5132                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5133        res.add(fi);
5134
5135        return new ParceledListSlice<>(res);
5136    }
5137
5138    @Override
5139    public boolean hasSystemFeature(String name, int version) {
5140        // allow instant applications
5141        synchronized (mAvailableFeatures) {
5142            final FeatureInfo feat = mAvailableFeatures.get(name);
5143            if (feat == null) {
5144                return false;
5145            } else {
5146                return feat.version >= version;
5147            }
5148        }
5149    }
5150
5151    @Override
5152    public int checkPermission(String permName, String pkgName, int userId) {
5153        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5154    }
5155
5156    @Override
5157    public int checkUidPermission(String permName, int uid) {
5158        final int callingUid = Binder.getCallingUid();
5159        final int callingUserId = UserHandle.getUserId(callingUid);
5160        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5161        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5162        final int userId = UserHandle.getUserId(uid);
5163        if (!sUserManager.exists(userId)) {
5164            return PackageManager.PERMISSION_DENIED;
5165        }
5166
5167        synchronized (mPackages) {
5168            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5169            if (obj != null) {
5170                if (obj instanceof SharedUserSetting) {
5171                    if (isCallerInstantApp) {
5172                        return PackageManager.PERMISSION_DENIED;
5173                    }
5174                } else if (obj instanceof PackageSetting) {
5175                    final PackageSetting ps = (PackageSetting) obj;
5176                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5177                        return PackageManager.PERMISSION_DENIED;
5178                    }
5179                }
5180                final SettingBase settingBase = (SettingBase) obj;
5181                final PermissionsState permissionsState = settingBase.getPermissionsState();
5182                if (permissionsState.hasPermission(permName, userId)) {
5183                    if (isUidInstantApp) {
5184                        if (mPermissionManager.isPermissionInstant(permName)) {
5185                            return PackageManager.PERMISSION_GRANTED;
5186                        }
5187                    } else {
5188                        return PackageManager.PERMISSION_GRANTED;
5189                    }
5190                }
5191                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5192                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5193                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5194                    return PackageManager.PERMISSION_GRANTED;
5195                }
5196            } else {
5197                ArraySet<String> perms = mSystemPermissions.get(uid);
5198                if (perms != null) {
5199                    if (perms.contains(permName)) {
5200                        return PackageManager.PERMISSION_GRANTED;
5201                    }
5202                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5203                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5204                        return PackageManager.PERMISSION_GRANTED;
5205                    }
5206                }
5207            }
5208        }
5209
5210        return PackageManager.PERMISSION_DENIED;
5211    }
5212
5213    @Override
5214    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5215        if (UserHandle.getCallingUserId() != userId) {
5216            mContext.enforceCallingPermission(
5217                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5218                    "isPermissionRevokedByPolicy for user " + userId);
5219        }
5220
5221        if (checkPermission(permission, packageName, userId)
5222                == PackageManager.PERMISSION_GRANTED) {
5223            return false;
5224        }
5225
5226        final int callingUid = Binder.getCallingUid();
5227        if (getInstantAppPackageName(callingUid) != null) {
5228            if (!isCallerSameApp(packageName, callingUid)) {
5229                return false;
5230            }
5231        } else {
5232            if (isInstantApp(packageName, userId)) {
5233                return false;
5234            }
5235        }
5236
5237        final long identity = Binder.clearCallingIdentity();
5238        try {
5239            final int flags = getPermissionFlags(permission, packageName, userId);
5240            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5241        } finally {
5242            Binder.restoreCallingIdentity(identity);
5243        }
5244    }
5245
5246    @Override
5247    public String getPermissionControllerPackageName() {
5248        synchronized (mPackages) {
5249            return mRequiredInstallerPackage;
5250        }
5251    }
5252
5253    boolean addPermission(PermissionInfo info, final boolean async) {
5254        return mPermissionManager.addPermission(
5255                info, async, getCallingUid(), new PermissionCallback() {
5256                    @Override
5257                    public void onPermissionChanged() {
5258                        if (!async) {
5259                            mSettings.writeLPr();
5260                        } else {
5261                            scheduleWriteSettingsLocked();
5262                        }
5263                    }
5264                });
5265    }
5266
5267    @Override
5268    public boolean addPermission(PermissionInfo info) {
5269        synchronized (mPackages) {
5270            return addPermission(info, false);
5271        }
5272    }
5273
5274    @Override
5275    public boolean addPermissionAsync(PermissionInfo info) {
5276        synchronized (mPackages) {
5277            return addPermission(info, true);
5278        }
5279    }
5280
5281    @Override
5282    public void removePermission(String permName) {
5283        mPermissionManager.removePermission(permName, getCallingUid(), mPermissionCallback);
5284    }
5285
5286    @Override
5287    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5288        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5289                getCallingUid(), userId, mPermissionCallback);
5290    }
5291
5292    @Override
5293    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5294        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5295                getCallingUid(), userId, mPermissionCallback);
5296    }
5297
5298    /**
5299     * Get the first event id for the permission.
5300     *
5301     * <p>There are four events for each permission: <ul>
5302     *     <li>Request permission: first id + 0</li>
5303     *     <li>Grant permission: first id + 1</li>
5304     *     <li>Request for permission denied: first id + 2</li>
5305     *     <li>Revoke permission: first id + 3</li>
5306     * </ul></p>
5307     *
5308     * @param name name of the permission
5309     *
5310     * @return The first event id for the permission
5311     */
5312    private static int getBaseEventId(@NonNull String name) {
5313        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5314
5315        if (eventIdIndex == -1) {
5316            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5317                    || Build.IS_USER) {
5318                Log.i(TAG, "Unknown permission " + name);
5319
5320                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5321            } else {
5322                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5323                //
5324                // Also update
5325                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5326                // - metrics_constants.proto
5327                throw new IllegalStateException("Unknown permission " + name);
5328            }
5329        }
5330
5331        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5332    }
5333
5334    /**
5335     * Log that a permission was revoked.
5336     *
5337     * @param context Context of the caller
5338     * @param name name of the permission
5339     * @param packageName package permission if for
5340     */
5341    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5342            @NonNull String packageName) {
5343        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5344    }
5345
5346    /**
5347     * Log that a permission request was granted.
5348     *
5349     * @param context Context of the caller
5350     * @param name name of the permission
5351     * @param packageName package permission if for
5352     */
5353    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5354            @NonNull String packageName) {
5355        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5356    }
5357
5358    @Override
5359    public void resetRuntimePermissions() {
5360        mContext.enforceCallingOrSelfPermission(
5361                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5362                "revokeRuntimePermission");
5363
5364        int callingUid = Binder.getCallingUid();
5365        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5366            mContext.enforceCallingOrSelfPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "resetRuntimePermissions");
5369        }
5370
5371        synchronized (mPackages) {
5372            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5373            for (int userId : UserManagerService.getInstance().getUserIds()) {
5374                final int packageCount = mPackages.size();
5375                for (int i = 0; i < packageCount; i++) {
5376                    PackageParser.Package pkg = mPackages.valueAt(i);
5377                    if (!(pkg.mExtras instanceof PackageSetting)) {
5378                        continue;
5379                    }
5380                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5381                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5382                }
5383            }
5384        }
5385    }
5386
5387    @Override
5388    public int getPermissionFlags(String permName, String packageName, int userId) {
5389        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5390    }
5391
5392    @Override
5393    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5394            int flagValues, int userId) {
5395        mPermissionManager.updatePermissionFlags(
5396                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5397                mPermissionCallback);
5398    }
5399
5400    /**
5401     * Update the permission flags for all packages and runtime permissions of a user in order
5402     * to allow device or profile owner to remove POLICY_FIXED.
5403     */
5404    @Override
5405    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5406        synchronized (mPackages) {
5407            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5408                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5409                    mPermissionCallback);
5410            if (changed) {
5411                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5412            }
5413        }
5414    }
5415
5416    @Override
5417    public boolean shouldShowRequestPermissionRationale(String permissionName,
5418            String packageName, int userId) {
5419        if (UserHandle.getCallingUserId() != userId) {
5420            mContext.enforceCallingPermission(
5421                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5422                    "canShowRequestPermissionRationale for user " + userId);
5423        }
5424
5425        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5426        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5427            return false;
5428        }
5429
5430        if (checkPermission(permissionName, packageName, userId)
5431                == PackageManager.PERMISSION_GRANTED) {
5432            return false;
5433        }
5434
5435        final int flags;
5436
5437        final long identity = Binder.clearCallingIdentity();
5438        try {
5439            flags = getPermissionFlags(permissionName,
5440                    packageName, userId);
5441        } finally {
5442            Binder.restoreCallingIdentity(identity);
5443        }
5444
5445        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5446                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5447                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5448
5449        if ((flags & fixedFlags) != 0) {
5450            return false;
5451        }
5452
5453        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5454    }
5455
5456    @Override
5457    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5458        mContext.enforceCallingOrSelfPermission(
5459                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5460                "addOnPermissionsChangeListener");
5461
5462        synchronized (mPackages) {
5463            mOnPermissionChangeListeners.addListenerLocked(listener);
5464        }
5465    }
5466
5467    @Override
5468    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5469        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5470            throw new SecurityException("Instant applications don't have access to this method");
5471        }
5472        synchronized (mPackages) {
5473            mOnPermissionChangeListeners.removeListenerLocked(listener);
5474        }
5475    }
5476
5477    @Override
5478    public boolean isProtectedBroadcast(String actionName) {
5479        // allow instant applications
5480        synchronized (mProtectedBroadcasts) {
5481            if (mProtectedBroadcasts.contains(actionName)) {
5482                return true;
5483            } else if (actionName != null) {
5484                // TODO: remove these terrible hacks
5485                if (actionName.startsWith("android.net.netmon.lingerExpired")
5486                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5487                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5488                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5489                    return true;
5490                }
5491            }
5492        }
5493        return false;
5494    }
5495
5496    @Override
5497    public int checkSignatures(String pkg1, String pkg2) {
5498        synchronized (mPackages) {
5499            final PackageParser.Package p1 = mPackages.get(pkg1);
5500            final PackageParser.Package p2 = mPackages.get(pkg2);
5501            if (p1 == null || p1.mExtras == null
5502                    || p2 == null || p2.mExtras == null) {
5503                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5504            }
5505            final int callingUid = Binder.getCallingUid();
5506            final int callingUserId = UserHandle.getUserId(callingUid);
5507            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5508            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5509            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5510                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512            }
5513            return compareSignatures(p1.mSignatures, p2.mSignatures);
5514        }
5515    }
5516
5517    @Override
5518    public int checkUidSignatures(int uid1, int uid2) {
5519        final int callingUid = Binder.getCallingUid();
5520        final int callingUserId = UserHandle.getUserId(callingUid);
5521        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5522        // Map to base uids.
5523        uid1 = UserHandle.getAppId(uid1);
5524        uid2 = UserHandle.getAppId(uid2);
5525        // reader
5526        synchronized (mPackages) {
5527            Signature[] s1;
5528            Signature[] s2;
5529            Object obj = mSettings.getUserIdLPr(uid1);
5530            if (obj != null) {
5531                if (obj instanceof SharedUserSetting) {
5532                    if (isCallerInstantApp) {
5533                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5534                    }
5535                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5536                } else if (obj instanceof PackageSetting) {
5537                    final PackageSetting ps = (PackageSetting) obj;
5538                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5539                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5540                    }
5541                    s1 = ps.signatures.mSignatures;
5542                } else {
5543                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5544                }
5545            } else {
5546                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5547            }
5548            obj = mSettings.getUserIdLPr(uid2);
5549            if (obj != null) {
5550                if (obj instanceof SharedUserSetting) {
5551                    if (isCallerInstantApp) {
5552                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5553                    }
5554                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5555                } else if (obj instanceof PackageSetting) {
5556                    final PackageSetting ps = (PackageSetting) obj;
5557                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5558                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5559                    }
5560                    s2 = ps.signatures.mSignatures;
5561                } else {
5562                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5563                }
5564            } else {
5565                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566            }
5567            return compareSignatures(s1, s2);
5568        }
5569    }
5570
5571    /**
5572     * This method should typically only be used when granting or revoking
5573     * permissions, since the app may immediately restart after this call.
5574     * <p>
5575     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5576     * guard your work against the app being relaunched.
5577     */
5578    private void killUid(int appId, int userId, String reason) {
5579        final long identity = Binder.clearCallingIdentity();
5580        try {
5581            IActivityManager am = ActivityManager.getService();
5582            if (am != null) {
5583                try {
5584                    am.killUid(appId, userId, reason);
5585                } catch (RemoteException e) {
5586                    /* ignore - same process */
5587                }
5588            }
5589        } finally {
5590            Binder.restoreCallingIdentity(identity);
5591        }
5592    }
5593
5594    /**
5595     * Compares two sets of signatures. Returns:
5596     * <br />
5597     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5598     * <br />
5599     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5600     * <br />
5601     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5602     * <br />
5603     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5604     * <br />
5605     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5606     */
5607    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5608        if (s1 == null) {
5609            return s2 == null
5610                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5611                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5612        }
5613
5614        if (s2 == null) {
5615            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5616        }
5617
5618        if (s1.length != s2.length) {
5619            return PackageManager.SIGNATURE_NO_MATCH;
5620        }
5621
5622        // Since both signature sets are of size 1, we can compare without HashSets.
5623        if (s1.length == 1) {
5624            return s1[0].equals(s2[0]) ?
5625                    PackageManager.SIGNATURE_MATCH :
5626                    PackageManager.SIGNATURE_NO_MATCH;
5627        }
5628
5629        ArraySet<Signature> set1 = new ArraySet<Signature>();
5630        for (Signature sig : s1) {
5631            set1.add(sig);
5632        }
5633        ArraySet<Signature> set2 = new ArraySet<Signature>();
5634        for (Signature sig : s2) {
5635            set2.add(sig);
5636        }
5637        // Make sure s2 contains all signatures in s1.
5638        if (set1.equals(set2)) {
5639            return PackageManager.SIGNATURE_MATCH;
5640        }
5641        return PackageManager.SIGNATURE_NO_MATCH;
5642    }
5643
5644    /**
5645     * If the database version for this type of package (internal storage or
5646     * external storage) is less than the version where package signatures
5647     * were updated, return true.
5648     */
5649    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5650        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5651        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5652    }
5653
5654    /**
5655     * Used for backward compatibility to make sure any packages with
5656     * certificate chains get upgraded to the new style. {@code existingSigs}
5657     * will be in the old format (since they were stored on disk from before the
5658     * system upgrade) and {@code scannedSigs} will be in the newer format.
5659     */
5660    private int compareSignaturesCompat(PackageSignatures existingSigs,
5661            PackageParser.Package scannedPkg) {
5662        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5663            return PackageManager.SIGNATURE_NO_MATCH;
5664        }
5665
5666        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5667        for (Signature sig : existingSigs.mSignatures) {
5668            existingSet.add(sig);
5669        }
5670        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5671        for (Signature sig : scannedPkg.mSignatures) {
5672            try {
5673                Signature[] chainSignatures = sig.getChainSignatures();
5674                for (Signature chainSig : chainSignatures) {
5675                    scannedCompatSet.add(chainSig);
5676                }
5677            } catch (CertificateEncodingException e) {
5678                scannedCompatSet.add(sig);
5679            }
5680        }
5681        /*
5682         * Make sure the expanded scanned set contains all signatures in the
5683         * existing one.
5684         */
5685        if (scannedCompatSet.equals(existingSet)) {
5686            // Migrate the old signatures to the new scheme.
5687            existingSigs.assignSignatures(scannedPkg.mSignatures);
5688            // The new KeySets will be re-added later in the scanning process.
5689            synchronized (mPackages) {
5690                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5691            }
5692            return PackageManager.SIGNATURE_MATCH;
5693        }
5694        return PackageManager.SIGNATURE_NO_MATCH;
5695    }
5696
5697    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5698        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5699        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5700    }
5701
5702    private int compareSignaturesRecover(PackageSignatures existingSigs,
5703            PackageParser.Package scannedPkg) {
5704        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5705            return PackageManager.SIGNATURE_NO_MATCH;
5706        }
5707
5708        String msg = null;
5709        try {
5710            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5711                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5712                        + scannedPkg.packageName);
5713                return PackageManager.SIGNATURE_MATCH;
5714            }
5715        } catch (CertificateException e) {
5716            msg = e.getMessage();
5717        }
5718
5719        logCriticalInfo(Log.INFO,
5720                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5721        return PackageManager.SIGNATURE_NO_MATCH;
5722    }
5723
5724    @Override
5725    public List<String> getAllPackages() {
5726        final int callingUid = Binder.getCallingUid();
5727        final int callingUserId = UserHandle.getUserId(callingUid);
5728        synchronized (mPackages) {
5729            if (canViewInstantApps(callingUid, callingUserId)) {
5730                return new ArrayList<String>(mPackages.keySet());
5731            }
5732            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5733            final List<String> result = new ArrayList<>();
5734            if (instantAppPkgName != null) {
5735                // caller is an instant application; filter unexposed applications
5736                for (PackageParser.Package pkg : mPackages.values()) {
5737                    if (!pkg.visibleToInstantApps) {
5738                        continue;
5739                    }
5740                    result.add(pkg.packageName);
5741                }
5742            } else {
5743                // caller is a normal application; filter instant applications
5744                for (PackageParser.Package pkg : mPackages.values()) {
5745                    final PackageSetting ps =
5746                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5747                    if (ps != null
5748                            && ps.getInstantApp(callingUserId)
5749                            && !mInstantAppRegistry.isInstantAccessGranted(
5750                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5751                        continue;
5752                    }
5753                    result.add(pkg.packageName);
5754                }
5755            }
5756            return result;
5757        }
5758    }
5759
5760    @Override
5761    public String[] getPackagesForUid(int uid) {
5762        final int callingUid = Binder.getCallingUid();
5763        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5764        final int userId = UserHandle.getUserId(uid);
5765        uid = UserHandle.getAppId(uid);
5766        // reader
5767        synchronized (mPackages) {
5768            Object obj = mSettings.getUserIdLPr(uid);
5769            if (obj instanceof SharedUserSetting) {
5770                if (isCallerInstantApp) {
5771                    return null;
5772                }
5773                final SharedUserSetting sus = (SharedUserSetting) obj;
5774                final int N = sus.packages.size();
5775                String[] res = new String[N];
5776                final Iterator<PackageSetting> it = sus.packages.iterator();
5777                int i = 0;
5778                while (it.hasNext()) {
5779                    PackageSetting ps = it.next();
5780                    if (ps.getInstalled(userId)) {
5781                        res[i++] = ps.name;
5782                    } else {
5783                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5784                    }
5785                }
5786                return res;
5787            } else if (obj instanceof PackageSetting) {
5788                final PackageSetting ps = (PackageSetting) obj;
5789                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5790                    return new String[]{ps.name};
5791                }
5792            }
5793        }
5794        return null;
5795    }
5796
5797    @Override
5798    public String getNameForUid(int uid) {
5799        final int callingUid = Binder.getCallingUid();
5800        if (getInstantAppPackageName(callingUid) != null) {
5801            return null;
5802        }
5803        synchronized (mPackages) {
5804            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5805            if (obj instanceof SharedUserSetting) {
5806                final SharedUserSetting sus = (SharedUserSetting) obj;
5807                return sus.name + ":" + sus.userId;
5808            } else if (obj instanceof PackageSetting) {
5809                final PackageSetting ps = (PackageSetting) obj;
5810                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5811                    return null;
5812                }
5813                return ps.name;
5814            }
5815            return null;
5816        }
5817    }
5818
5819    @Override
5820    public String[] getNamesForUids(int[] uids) {
5821        if (uids == null || uids.length == 0) {
5822            return null;
5823        }
5824        final int callingUid = Binder.getCallingUid();
5825        if (getInstantAppPackageName(callingUid) != null) {
5826            return null;
5827        }
5828        final String[] names = new String[uids.length];
5829        synchronized (mPackages) {
5830            for (int i = uids.length - 1; i >= 0; i--) {
5831                final int uid = uids[i];
5832                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5833                if (obj instanceof SharedUserSetting) {
5834                    final SharedUserSetting sus = (SharedUserSetting) obj;
5835                    names[i] = "shared:" + sus.name;
5836                } else if (obj instanceof PackageSetting) {
5837                    final PackageSetting ps = (PackageSetting) obj;
5838                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5839                        names[i] = null;
5840                    } else {
5841                        names[i] = ps.name;
5842                    }
5843                } else {
5844                    names[i] = null;
5845                }
5846            }
5847        }
5848        return names;
5849    }
5850
5851    @Override
5852    public int getUidForSharedUser(String sharedUserName) {
5853        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5854            return -1;
5855        }
5856        if (sharedUserName == null) {
5857            return -1;
5858        }
5859        // reader
5860        synchronized (mPackages) {
5861            SharedUserSetting suid;
5862            try {
5863                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5864                if (suid != null) {
5865                    return suid.userId;
5866                }
5867            } catch (PackageManagerException ignore) {
5868                // can't happen, but, still need to catch it
5869            }
5870            return -1;
5871        }
5872    }
5873
5874    @Override
5875    public int getFlagsForUid(int uid) {
5876        final int callingUid = Binder.getCallingUid();
5877        if (getInstantAppPackageName(callingUid) != null) {
5878            return 0;
5879        }
5880        synchronized (mPackages) {
5881            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5882            if (obj instanceof SharedUserSetting) {
5883                final SharedUserSetting sus = (SharedUserSetting) obj;
5884                return sus.pkgFlags;
5885            } else if (obj instanceof PackageSetting) {
5886                final PackageSetting ps = (PackageSetting) obj;
5887                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5888                    return 0;
5889                }
5890                return ps.pkgFlags;
5891            }
5892        }
5893        return 0;
5894    }
5895
5896    @Override
5897    public int getPrivateFlagsForUid(int uid) {
5898        final int callingUid = Binder.getCallingUid();
5899        if (getInstantAppPackageName(callingUid) != null) {
5900            return 0;
5901        }
5902        synchronized (mPackages) {
5903            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5904            if (obj instanceof SharedUserSetting) {
5905                final SharedUserSetting sus = (SharedUserSetting) obj;
5906                return sus.pkgPrivateFlags;
5907            } else if (obj instanceof PackageSetting) {
5908                final PackageSetting ps = (PackageSetting) obj;
5909                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5910                    return 0;
5911                }
5912                return ps.pkgPrivateFlags;
5913            }
5914        }
5915        return 0;
5916    }
5917
5918    @Override
5919    public boolean isUidPrivileged(int uid) {
5920        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5921            return false;
5922        }
5923        uid = UserHandle.getAppId(uid);
5924        // reader
5925        synchronized (mPackages) {
5926            Object obj = mSettings.getUserIdLPr(uid);
5927            if (obj instanceof SharedUserSetting) {
5928                final SharedUserSetting sus = (SharedUserSetting) obj;
5929                final Iterator<PackageSetting> it = sus.packages.iterator();
5930                while (it.hasNext()) {
5931                    if (it.next().isPrivileged()) {
5932                        return true;
5933                    }
5934                }
5935            } else if (obj instanceof PackageSetting) {
5936                final PackageSetting ps = (PackageSetting) obj;
5937                return ps.isPrivileged();
5938            }
5939        }
5940        return false;
5941    }
5942
5943    @Override
5944    public String[] getAppOpPermissionPackages(String permissionName) {
5945        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5946            return null;
5947        }
5948        synchronized (mPackages) {
5949            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5950            if (pkgs == null) {
5951                return null;
5952            }
5953            return pkgs.toArray(new String[pkgs.size()]);
5954        }
5955    }
5956
5957    @Override
5958    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5959            int flags, int userId) {
5960        return resolveIntentInternal(
5961                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5962    }
5963
5964    /**
5965     * Normally instant apps can only be resolved when they're visible to the caller.
5966     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5967     * since we need to allow the system to start any installed application.
5968     */
5969    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5970            int flags, int userId, boolean resolveForStart) {
5971        try {
5972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5973
5974            if (!sUserManager.exists(userId)) return null;
5975            final int callingUid = Binder.getCallingUid();
5976            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5977            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5978                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5979
5980            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5981            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5982                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5983            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5984
5985            final ResolveInfo bestChoice =
5986                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5987            return bestChoice;
5988        } finally {
5989            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5990        }
5991    }
5992
5993    @Override
5994    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5995        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5996            throw new SecurityException(
5997                    "findPersistentPreferredActivity can only be run by the system");
5998        }
5999        if (!sUserManager.exists(userId)) {
6000            return null;
6001        }
6002        final int callingUid = Binder.getCallingUid();
6003        intent = updateIntentForResolve(intent);
6004        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6005        final int flags = updateFlagsForResolve(
6006                0, userId, intent, callingUid, false /*includeInstantApps*/);
6007        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6008                userId);
6009        synchronized (mPackages) {
6010            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6011                    userId);
6012        }
6013    }
6014
6015    @Override
6016    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6017            IntentFilter filter, int match, ComponentName activity) {
6018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6019            return;
6020        }
6021        final int userId = UserHandle.getCallingUserId();
6022        if (DEBUG_PREFERRED) {
6023            Log.v(TAG, "setLastChosenActivity intent=" + intent
6024                + " resolvedType=" + resolvedType
6025                + " flags=" + flags
6026                + " filter=" + filter
6027                + " match=" + match
6028                + " activity=" + activity);
6029            filter.dump(new PrintStreamPrinter(System.out), "    ");
6030        }
6031        intent.setComponent(null);
6032        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6033                userId);
6034        // Find any earlier preferred or last chosen entries and nuke them
6035        findPreferredActivity(intent, resolvedType,
6036                flags, query, 0, false, true, false, userId);
6037        // Add the new activity as the last chosen for this filter
6038        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6039                "Setting last chosen");
6040    }
6041
6042    @Override
6043    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6045            return null;
6046        }
6047        final int userId = UserHandle.getCallingUserId();
6048        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6049        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6050                userId);
6051        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6052                false, false, false, userId);
6053    }
6054
6055    /**
6056     * Returns whether or not instant apps have been disabled remotely.
6057     */
6058    private boolean isEphemeralDisabled() {
6059        return mEphemeralAppsDisabled;
6060    }
6061
6062    private boolean isInstantAppAllowed(
6063            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6064            boolean skipPackageCheck) {
6065        if (mInstantAppResolverConnection == null) {
6066            return false;
6067        }
6068        if (mInstantAppInstallerActivity == null) {
6069            return false;
6070        }
6071        if (intent.getComponent() != null) {
6072            return false;
6073        }
6074        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6075            return false;
6076        }
6077        if (!skipPackageCheck && intent.getPackage() != null) {
6078            return false;
6079        }
6080        final boolean isWebUri = hasWebURI(intent);
6081        if (!isWebUri || intent.getData().getHost() == null) {
6082            return false;
6083        }
6084        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6085        // Or if there's already an ephemeral app installed that handles the action
6086        synchronized (mPackages) {
6087            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6088            for (int n = 0; n < count; n++) {
6089                final ResolveInfo info = resolvedActivities.get(n);
6090                final String packageName = info.activityInfo.packageName;
6091                final PackageSetting ps = mSettings.mPackages.get(packageName);
6092                if (ps != null) {
6093                    // only check domain verification status if the app is not a browser
6094                    if (!info.handleAllWebDataURI) {
6095                        // Try to get the status from User settings first
6096                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6097                        final int status = (int) (packedStatus >> 32);
6098                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6099                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6100                            if (DEBUG_EPHEMERAL) {
6101                                Slog.v(TAG, "DENY instant app;"
6102                                    + " pkg: " + packageName + ", status: " + status);
6103                            }
6104                            return false;
6105                        }
6106                    }
6107                    if (ps.getInstantApp(userId)) {
6108                        if (DEBUG_EPHEMERAL) {
6109                            Slog.v(TAG, "DENY instant app installed;"
6110                                    + " pkg: " + packageName);
6111                        }
6112                        return false;
6113                    }
6114                }
6115            }
6116        }
6117        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6118        return true;
6119    }
6120
6121    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6122            Intent origIntent, String resolvedType, String callingPackage,
6123            Bundle verificationBundle, int userId) {
6124        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6125                new InstantAppRequest(responseObj, origIntent, resolvedType,
6126                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6127        mHandler.sendMessage(msg);
6128    }
6129
6130    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6131            int flags, List<ResolveInfo> query, int userId) {
6132        if (query != null) {
6133            final int N = query.size();
6134            if (N == 1) {
6135                return query.get(0);
6136            } else if (N > 1) {
6137                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6138                // If there is more than one activity with the same priority,
6139                // then let the user decide between them.
6140                ResolveInfo r0 = query.get(0);
6141                ResolveInfo r1 = query.get(1);
6142                if (DEBUG_INTENT_MATCHING || debug) {
6143                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6144                            + r1.activityInfo.name + "=" + r1.priority);
6145                }
6146                // If the first activity has a higher priority, or a different
6147                // default, then it is always desirable to pick it.
6148                if (r0.priority != r1.priority
6149                        || r0.preferredOrder != r1.preferredOrder
6150                        || r0.isDefault != r1.isDefault) {
6151                    return query.get(0);
6152                }
6153                // If we have saved a preference for a preferred activity for
6154                // this Intent, use that.
6155                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6156                        flags, query, r0.priority, true, false, debug, userId);
6157                if (ri != null) {
6158                    return ri;
6159                }
6160                // If we have an ephemeral app, use it
6161                for (int i = 0; i < N; i++) {
6162                    ri = query.get(i);
6163                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6164                        final String packageName = ri.activityInfo.packageName;
6165                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6166                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6167                        final int status = (int)(packedStatus >> 32);
6168                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6169                            return ri;
6170                        }
6171                    }
6172                }
6173                ri = new ResolveInfo(mResolveInfo);
6174                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6175                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6176                // If all of the options come from the same package, show the application's
6177                // label and icon instead of the generic resolver's.
6178                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6179                // and then throw away the ResolveInfo itself, meaning that the caller loses
6180                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6181                // a fallback for this case; we only set the target package's resources on
6182                // the ResolveInfo, not the ActivityInfo.
6183                final String intentPackage = intent.getPackage();
6184                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6185                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6186                    ri.resolvePackageName = intentPackage;
6187                    if (userNeedsBadging(userId)) {
6188                        ri.noResourceId = true;
6189                    } else {
6190                        ri.icon = appi.icon;
6191                    }
6192                    ri.iconResourceId = appi.icon;
6193                    ri.labelRes = appi.labelRes;
6194                }
6195                ri.activityInfo.applicationInfo = new ApplicationInfo(
6196                        ri.activityInfo.applicationInfo);
6197                if (userId != 0) {
6198                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6199                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6200                }
6201                // Make sure that the resolver is displayable in car mode
6202                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6203                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6204                return ri;
6205            }
6206        }
6207        return null;
6208    }
6209
6210    /**
6211     * Return true if the given list is not empty and all of its contents have
6212     * an activityInfo with the given package name.
6213     */
6214    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6215        if (ArrayUtils.isEmpty(list)) {
6216            return false;
6217        }
6218        for (int i = 0, N = list.size(); i < N; i++) {
6219            final ResolveInfo ri = list.get(i);
6220            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6221            if (ai == null || !packageName.equals(ai.packageName)) {
6222                return false;
6223            }
6224        }
6225        return true;
6226    }
6227
6228    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6229            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6230        final int N = query.size();
6231        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6232                .get(userId);
6233        // Get the list of persistent preferred activities that handle the intent
6234        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6235        List<PersistentPreferredActivity> pprefs = ppir != null
6236                ? ppir.queryIntent(intent, resolvedType,
6237                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6238                        userId)
6239                : null;
6240        if (pprefs != null && pprefs.size() > 0) {
6241            final int M = pprefs.size();
6242            for (int i=0; i<M; i++) {
6243                final PersistentPreferredActivity ppa = pprefs.get(i);
6244                if (DEBUG_PREFERRED || debug) {
6245                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6246                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6247                            + "\n  component=" + ppa.mComponent);
6248                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6249                }
6250                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6251                        flags | MATCH_DISABLED_COMPONENTS, userId);
6252                if (DEBUG_PREFERRED || debug) {
6253                    Slog.v(TAG, "Found persistent preferred activity:");
6254                    if (ai != null) {
6255                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6256                    } else {
6257                        Slog.v(TAG, "  null");
6258                    }
6259                }
6260                if (ai == null) {
6261                    // This previously registered persistent preferred activity
6262                    // component is no longer known. Ignore it and do NOT remove it.
6263                    continue;
6264                }
6265                for (int j=0; j<N; j++) {
6266                    final ResolveInfo ri = query.get(j);
6267                    if (!ri.activityInfo.applicationInfo.packageName
6268                            .equals(ai.applicationInfo.packageName)) {
6269                        continue;
6270                    }
6271                    if (!ri.activityInfo.name.equals(ai.name)) {
6272                        continue;
6273                    }
6274                    //  Found a persistent preference that can handle the intent.
6275                    if (DEBUG_PREFERRED || debug) {
6276                        Slog.v(TAG, "Returning persistent preferred activity: " +
6277                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6278                    }
6279                    return ri;
6280                }
6281            }
6282        }
6283        return null;
6284    }
6285
6286    // TODO: handle preferred activities missing while user has amnesia
6287    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6288            List<ResolveInfo> query, int priority, boolean always,
6289            boolean removeMatches, boolean debug, int userId) {
6290        if (!sUserManager.exists(userId)) return null;
6291        final int callingUid = Binder.getCallingUid();
6292        flags = updateFlagsForResolve(
6293                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6294        intent = updateIntentForResolve(intent);
6295        // writer
6296        synchronized (mPackages) {
6297            // Try to find a matching persistent preferred activity.
6298            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6299                    debug, userId);
6300
6301            // If a persistent preferred activity matched, use it.
6302            if (pri != null) {
6303                return pri;
6304            }
6305
6306            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6307            // Get the list of preferred activities that handle the intent
6308            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6309            List<PreferredActivity> prefs = pir != null
6310                    ? pir.queryIntent(intent, resolvedType,
6311                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6312                            userId)
6313                    : null;
6314            if (prefs != null && prefs.size() > 0) {
6315                boolean changed = false;
6316                try {
6317                    // First figure out how good the original match set is.
6318                    // We will only allow preferred activities that came
6319                    // from the same match quality.
6320                    int match = 0;
6321
6322                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6323
6324                    final int N = query.size();
6325                    for (int j=0; j<N; j++) {
6326                        final ResolveInfo ri = query.get(j);
6327                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6328                                + ": 0x" + Integer.toHexString(match));
6329                        if (ri.match > match) {
6330                            match = ri.match;
6331                        }
6332                    }
6333
6334                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6335                            + Integer.toHexString(match));
6336
6337                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6338                    final int M = prefs.size();
6339                    for (int i=0; i<M; i++) {
6340                        final PreferredActivity pa = prefs.get(i);
6341                        if (DEBUG_PREFERRED || debug) {
6342                            Slog.v(TAG, "Checking PreferredActivity ds="
6343                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6344                                    + "\n  component=" + pa.mPref.mComponent);
6345                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6346                        }
6347                        if (pa.mPref.mMatch != match) {
6348                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6349                                    + Integer.toHexString(pa.mPref.mMatch));
6350                            continue;
6351                        }
6352                        // If it's not an "always" type preferred activity and that's what we're
6353                        // looking for, skip it.
6354                        if (always && !pa.mPref.mAlways) {
6355                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6356                            continue;
6357                        }
6358                        final ActivityInfo ai = getActivityInfo(
6359                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6360                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6361                                userId);
6362                        if (DEBUG_PREFERRED || debug) {
6363                            Slog.v(TAG, "Found preferred activity:");
6364                            if (ai != null) {
6365                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6366                            } else {
6367                                Slog.v(TAG, "  null");
6368                            }
6369                        }
6370                        if (ai == null) {
6371                            // This previously registered preferred activity
6372                            // component is no longer known.  Most likely an update
6373                            // to the app was installed and in the new version this
6374                            // component no longer exists.  Clean it up by removing
6375                            // it from the preferred activities list, and skip it.
6376                            Slog.w(TAG, "Removing dangling preferred activity: "
6377                                    + pa.mPref.mComponent);
6378                            pir.removeFilter(pa);
6379                            changed = true;
6380                            continue;
6381                        }
6382                        for (int j=0; j<N; j++) {
6383                            final ResolveInfo ri = query.get(j);
6384                            if (!ri.activityInfo.applicationInfo.packageName
6385                                    .equals(ai.applicationInfo.packageName)) {
6386                                continue;
6387                            }
6388                            if (!ri.activityInfo.name.equals(ai.name)) {
6389                                continue;
6390                            }
6391
6392                            if (removeMatches) {
6393                                pir.removeFilter(pa);
6394                                changed = true;
6395                                if (DEBUG_PREFERRED) {
6396                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6397                                }
6398                                break;
6399                            }
6400
6401                            // Okay we found a previously set preferred or last chosen app.
6402                            // If the result set is different from when this
6403                            // was created, and is not a subset of the preferred set, we need to
6404                            // clear it and re-ask the user their preference, if we're looking for
6405                            // an "always" type entry.
6406                            if (always && !pa.mPref.sameSet(query)) {
6407                                if (pa.mPref.isSuperset(query)) {
6408                                    // some components of the set are no longer present in
6409                                    // the query, but the preferred activity can still be reused
6410                                    if (DEBUG_PREFERRED) {
6411                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6412                                                + " still valid as only non-preferred components"
6413                                                + " were removed for " + intent + " type "
6414                                                + resolvedType);
6415                                    }
6416                                    // remove obsolete components and re-add the up-to-date filter
6417                                    PreferredActivity freshPa = new PreferredActivity(pa,
6418                                            pa.mPref.mMatch,
6419                                            pa.mPref.discardObsoleteComponents(query),
6420                                            pa.mPref.mComponent,
6421                                            pa.mPref.mAlways);
6422                                    pir.removeFilter(pa);
6423                                    pir.addFilter(freshPa);
6424                                    changed = true;
6425                                } else {
6426                                    Slog.i(TAG,
6427                                            "Result set changed, dropping preferred activity for "
6428                                                    + intent + " type " + resolvedType);
6429                                    if (DEBUG_PREFERRED) {
6430                                        Slog.v(TAG, "Removing preferred activity since set changed "
6431                                                + pa.mPref.mComponent);
6432                                    }
6433                                    pir.removeFilter(pa);
6434                                    // Re-add the filter as a "last chosen" entry (!always)
6435                                    PreferredActivity lastChosen = new PreferredActivity(
6436                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6437                                    pir.addFilter(lastChosen);
6438                                    changed = true;
6439                                    return null;
6440                                }
6441                            }
6442
6443                            // Yay! Either the set matched or we're looking for the last chosen
6444                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6445                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6446                            return ri;
6447                        }
6448                    }
6449                } finally {
6450                    if (changed) {
6451                        if (DEBUG_PREFERRED) {
6452                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6453                        }
6454                        scheduleWritePackageRestrictionsLocked(userId);
6455                    }
6456                }
6457            }
6458        }
6459        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6460        return null;
6461    }
6462
6463    /*
6464     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6465     */
6466    @Override
6467    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6468            int targetUserId) {
6469        mContext.enforceCallingOrSelfPermission(
6470                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6471        List<CrossProfileIntentFilter> matches =
6472                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6473        if (matches != null) {
6474            int size = matches.size();
6475            for (int i = 0; i < size; i++) {
6476                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6477            }
6478        }
6479        if (hasWebURI(intent)) {
6480            // cross-profile app linking works only towards the parent.
6481            final int callingUid = Binder.getCallingUid();
6482            final UserInfo parent = getProfileParent(sourceUserId);
6483            synchronized(mPackages) {
6484                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6485                        false /*includeInstantApps*/);
6486                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6487                        intent, resolvedType, flags, sourceUserId, parent.id);
6488                return xpDomainInfo != null;
6489            }
6490        }
6491        return false;
6492    }
6493
6494    private UserInfo getProfileParent(int userId) {
6495        final long identity = Binder.clearCallingIdentity();
6496        try {
6497            return sUserManager.getProfileParent(userId);
6498        } finally {
6499            Binder.restoreCallingIdentity(identity);
6500        }
6501    }
6502
6503    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6504            String resolvedType, int userId) {
6505        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6506        if (resolver != null) {
6507            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6508        }
6509        return null;
6510    }
6511
6512    @Override
6513    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6514            String resolvedType, int flags, int userId) {
6515        try {
6516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6517
6518            return new ParceledListSlice<>(
6519                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6520        } finally {
6521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6522        }
6523    }
6524
6525    /**
6526     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6527     * instant, returns {@code null}.
6528     */
6529    private String getInstantAppPackageName(int callingUid) {
6530        synchronized (mPackages) {
6531            // If the caller is an isolated app use the owner's uid for the lookup.
6532            if (Process.isIsolated(callingUid)) {
6533                callingUid = mIsolatedOwners.get(callingUid);
6534            }
6535            final int appId = UserHandle.getAppId(callingUid);
6536            final Object obj = mSettings.getUserIdLPr(appId);
6537            if (obj instanceof PackageSetting) {
6538                final PackageSetting ps = (PackageSetting) obj;
6539                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6540                return isInstantApp ? ps.pkg.packageName : null;
6541            }
6542        }
6543        return null;
6544    }
6545
6546    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6547            String resolvedType, int flags, int userId) {
6548        return queryIntentActivitiesInternal(
6549                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6550                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6551    }
6552
6553    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6554            String resolvedType, int flags, int filterCallingUid, int userId,
6555            boolean resolveForStart, boolean allowDynamicSplits) {
6556        if (!sUserManager.exists(userId)) return Collections.emptyList();
6557        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6558        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6559                false /* requireFullPermission */, false /* checkShell */,
6560                "query intent activities");
6561        final String pkgName = intent.getPackage();
6562        ComponentName comp = intent.getComponent();
6563        if (comp == null) {
6564            if (intent.getSelector() != null) {
6565                intent = intent.getSelector();
6566                comp = intent.getComponent();
6567            }
6568        }
6569
6570        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6571                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6572        if (comp != null) {
6573            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6574            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6575            if (ai != null) {
6576                // When specifying an explicit component, we prevent the activity from being
6577                // used when either 1) the calling package is normal and the activity is within
6578                // an ephemeral application or 2) the calling package is ephemeral and the
6579                // activity is not visible to ephemeral applications.
6580                final boolean matchInstantApp =
6581                        (flags & PackageManager.MATCH_INSTANT) != 0;
6582                final boolean matchVisibleToInstantAppOnly =
6583                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6584                final boolean matchExplicitlyVisibleOnly =
6585                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6586                final boolean isCallerInstantApp =
6587                        instantAppPkgName != null;
6588                final boolean isTargetSameInstantApp =
6589                        comp.getPackageName().equals(instantAppPkgName);
6590                final boolean isTargetInstantApp =
6591                        (ai.applicationInfo.privateFlags
6592                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6593                final boolean isTargetVisibleToInstantApp =
6594                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6595                final boolean isTargetExplicitlyVisibleToInstantApp =
6596                        isTargetVisibleToInstantApp
6597                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6598                final boolean isTargetHiddenFromInstantApp =
6599                        !isTargetVisibleToInstantApp
6600                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6601                final boolean blockResolution =
6602                        !isTargetSameInstantApp
6603                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6604                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6605                                        && isTargetHiddenFromInstantApp));
6606                if (!blockResolution) {
6607                    final ResolveInfo ri = new ResolveInfo();
6608                    ri.activityInfo = ai;
6609                    list.add(ri);
6610                }
6611            }
6612            return applyPostResolutionFilter(
6613                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6614        }
6615
6616        // reader
6617        boolean sortResult = false;
6618        boolean addEphemeral = false;
6619        List<ResolveInfo> result;
6620        final boolean ephemeralDisabled = isEphemeralDisabled();
6621        synchronized (mPackages) {
6622            if (pkgName == null) {
6623                List<CrossProfileIntentFilter> matchingFilters =
6624                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6625                // Check for results that need to skip the current profile.
6626                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6627                        resolvedType, flags, userId);
6628                if (xpResolveInfo != null) {
6629                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6630                    xpResult.add(xpResolveInfo);
6631                    return applyPostResolutionFilter(
6632                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6633                            allowDynamicSplits, filterCallingUid, userId);
6634                }
6635
6636                // Check for results in the current profile.
6637                result = filterIfNotSystemUser(mActivities.queryIntent(
6638                        intent, resolvedType, flags, userId), userId);
6639                addEphemeral = !ephemeralDisabled
6640                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6641                // Check for cross profile results.
6642                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6643                xpResolveInfo = queryCrossProfileIntents(
6644                        matchingFilters, intent, resolvedType, flags, userId,
6645                        hasNonNegativePriorityResult);
6646                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6647                    boolean isVisibleToUser = filterIfNotSystemUser(
6648                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6649                    if (isVisibleToUser) {
6650                        result.add(xpResolveInfo);
6651                        sortResult = true;
6652                    }
6653                }
6654                if (hasWebURI(intent)) {
6655                    CrossProfileDomainInfo xpDomainInfo = null;
6656                    final UserInfo parent = getProfileParent(userId);
6657                    if (parent != null) {
6658                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6659                                flags, userId, parent.id);
6660                    }
6661                    if (xpDomainInfo != null) {
6662                        if (xpResolveInfo != null) {
6663                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6664                            // in the result.
6665                            result.remove(xpResolveInfo);
6666                        }
6667                        if (result.size() == 0 && !addEphemeral) {
6668                            // No result in current profile, but found candidate in parent user.
6669                            // And we are not going to add emphemeral app, so we can return the
6670                            // result straight away.
6671                            result.add(xpDomainInfo.resolveInfo);
6672                            return applyPostResolutionFilter(result, instantAppPkgName,
6673                                    allowDynamicSplits, filterCallingUid, userId);
6674                        }
6675                    } else if (result.size() <= 1 && !addEphemeral) {
6676                        // No result in parent user and <= 1 result in current profile, and we
6677                        // are not going to add emphemeral app, so we can return the result without
6678                        // further processing.
6679                        return applyPostResolutionFilter(result, instantAppPkgName,
6680                                allowDynamicSplits, filterCallingUid, userId);
6681                    }
6682                    // We have more than one candidate (combining results from current and parent
6683                    // profile), so we need filtering and sorting.
6684                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6685                            intent, flags, result, xpDomainInfo, userId);
6686                    sortResult = true;
6687                }
6688            } else {
6689                final PackageParser.Package pkg = mPackages.get(pkgName);
6690                result = null;
6691                if (pkg != null) {
6692                    result = filterIfNotSystemUser(
6693                            mActivities.queryIntentForPackage(
6694                                    intent, resolvedType, flags, pkg.activities, userId),
6695                            userId);
6696                }
6697                if (result == null || result.size() == 0) {
6698                    // the caller wants to resolve for a particular package; however, there
6699                    // were no installed results, so, try to find an ephemeral result
6700                    addEphemeral = !ephemeralDisabled
6701                            && isInstantAppAllowed(
6702                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6703                    if (result == null) {
6704                        result = new ArrayList<>();
6705                    }
6706                }
6707            }
6708        }
6709        if (addEphemeral) {
6710            result = maybeAddInstantAppInstaller(
6711                    result, intent, resolvedType, flags, userId, resolveForStart);
6712        }
6713        if (sortResult) {
6714            Collections.sort(result, mResolvePrioritySorter);
6715        }
6716        return applyPostResolutionFilter(
6717                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6718    }
6719
6720    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6721            String resolvedType, int flags, int userId, boolean resolveForStart) {
6722        // first, check to see if we've got an instant app already installed
6723        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6724        ResolveInfo localInstantApp = null;
6725        boolean blockResolution = false;
6726        if (!alreadyResolvedLocally) {
6727            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6728                    flags
6729                        | PackageManager.GET_RESOLVED_FILTER
6730                        | PackageManager.MATCH_INSTANT
6731                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6732                    userId);
6733            for (int i = instantApps.size() - 1; i >= 0; --i) {
6734                final ResolveInfo info = instantApps.get(i);
6735                final String packageName = info.activityInfo.packageName;
6736                final PackageSetting ps = mSettings.mPackages.get(packageName);
6737                if (ps.getInstantApp(userId)) {
6738                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6739                    final int status = (int)(packedStatus >> 32);
6740                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6741                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6742                        // there's a local instant application installed, but, the user has
6743                        // chosen to never use it; skip resolution and don't acknowledge
6744                        // an instant application is even available
6745                        if (DEBUG_EPHEMERAL) {
6746                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6747                        }
6748                        blockResolution = true;
6749                        break;
6750                    } else {
6751                        // we have a locally installed instant application; skip resolution
6752                        // but acknowledge there's an instant application available
6753                        if (DEBUG_EPHEMERAL) {
6754                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6755                        }
6756                        localInstantApp = info;
6757                        break;
6758                    }
6759                }
6760            }
6761        }
6762        // no app installed, let's see if one's available
6763        AuxiliaryResolveInfo auxiliaryResponse = null;
6764        if (!blockResolution) {
6765            if (localInstantApp == null) {
6766                // we don't have an instant app locally, resolve externally
6767                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6768                final InstantAppRequest requestObject = new InstantAppRequest(
6769                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6770                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6771                        resolveForStart);
6772                auxiliaryResponse =
6773                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6774                                mContext, mInstantAppResolverConnection, requestObject);
6775                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6776            } else {
6777                // we have an instant application locally, but, we can't admit that since
6778                // callers shouldn't be able to determine prior browsing. create a dummy
6779                // auxiliary response so the downstream code behaves as if there's an
6780                // instant application available externally. when it comes time to start
6781                // the instant application, we'll do the right thing.
6782                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6783                auxiliaryResponse = new AuxiliaryResolveInfo(
6784                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6785                        ai.versionCode, null /*failureIntent*/);
6786            }
6787        }
6788        if (auxiliaryResponse != null) {
6789            if (DEBUG_EPHEMERAL) {
6790                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6791            }
6792            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6793            final PackageSetting ps =
6794                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6795            if (ps != null) {
6796                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6797                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6798                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6799                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6800                // make sure this resolver is the default
6801                ephemeralInstaller.isDefault = true;
6802                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6803                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6804                // add a non-generic filter
6805                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6806                ephemeralInstaller.filter.addDataPath(
6807                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6808                ephemeralInstaller.isInstantAppAvailable = true;
6809                result.add(ephemeralInstaller);
6810            }
6811        }
6812        return result;
6813    }
6814
6815    private static class CrossProfileDomainInfo {
6816        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6817        ResolveInfo resolveInfo;
6818        /* Best domain verification status of the activities found in the other profile */
6819        int bestDomainVerificationStatus;
6820    }
6821
6822    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6823            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6824        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6825                sourceUserId)) {
6826            return null;
6827        }
6828        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6829                resolvedType, flags, parentUserId);
6830
6831        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6832            return null;
6833        }
6834        CrossProfileDomainInfo result = null;
6835        int size = resultTargetUser.size();
6836        for (int i = 0; i < size; i++) {
6837            ResolveInfo riTargetUser = resultTargetUser.get(i);
6838            // Intent filter verification is only for filters that specify a host. So don't return
6839            // those that handle all web uris.
6840            if (riTargetUser.handleAllWebDataURI) {
6841                continue;
6842            }
6843            String packageName = riTargetUser.activityInfo.packageName;
6844            PackageSetting ps = mSettings.mPackages.get(packageName);
6845            if (ps == null) {
6846                continue;
6847            }
6848            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6849            int status = (int)(verificationState >> 32);
6850            if (result == null) {
6851                result = new CrossProfileDomainInfo();
6852                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6853                        sourceUserId, parentUserId);
6854                result.bestDomainVerificationStatus = status;
6855            } else {
6856                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6857                        result.bestDomainVerificationStatus);
6858            }
6859        }
6860        // Don't consider matches with status NEVER across profiles.
6861        if (result != null && result.bestDomainVerificationStatus
6862                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6863            return null;
6864        }
6865        return result;
6866    }
6867
6868    /**
6869     * Verification statuses are ordered from the worse to the best, except for
6870     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6871     */
6872    private int bestDomainVerificationStatus(int status1, int status2) {
6873        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6874            return status2;
6875        }
6876        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6877            return status1;
6878        }
6879        return (int) MathUtils.max(status1, status2);
6880    }
6881
6882    private boolean isUserEnabled(int userId) {
6883        long callingId = Binder.clearCallingIdentity();
6884        try {
6885            UserInfo userInfo = sUserManager.getUserInfo(userId);
6886            return userInfo != null && userInfo.isEnabled();
6887        } finally {
6888            Binder.restoreCallingIdentity(callingId);
6889        }
6890    }
6891
6892    /**
6893     * Filter out activities with systemUserOnly flag set, when current user is not System.
6894     *
6895     * @return filtered list
6896     */
6897    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6898        if (userId == UserHandle.USER_SYSTEM) {
6899            return resolveInfos;
6900        }
6901        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6902            ResolveInfo info = resolveInfos.get(i);
6903            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6904                resolveInfos.remove(i);
6905            }
6906        }
6907        return resolveInfos;
6908    }
6909
6910    /**
6911     * Filters out ephemeral activities.
6912     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6913     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6914     *
6915     * @param resolveInfos The pre-filtered list of resolved activities
6916     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6917     *          is performed.
6918     * @return A filtered list of resolved activities.
6919     */
6920    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6921            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6922        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6923            final ResolveInfo info = resolveInfos.get(i);
6924            // allow activities that are defined in the provided package
6925            if (allowDynamicSplits
6926                    && info.activityInfo.splitName != null
6927                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6928                            info.activityInfo.splitName)) {
6929                // requested activity is defined in a split that hasn't been installed yet.
6930                // add the installer to the resolve list
6931                if (DEBUG_INSTALL) {
6932                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6933                }
6934                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6935                final ComponentName installFailureActivity = findInstallFailureActivity(
6936                        info.activityInfo.packageName,  filterCallingUid, userId);
6937                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6938                        info.activityInfo.packageName, info.activityInfo.splitName,
6939                        installFailureActivity,
6940                        info.activityInfo.applicationInfo.versionCode,
6941                        null /*failureIntent*/);
6942                // make sure this resolver is the default
6943                installerInfo.isDefault = true;
6944                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6945                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6946                // add a non-generic filter
6947                installerInfo.filter = new IntentFilter();
6948                // load resources from the correct package
6949                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6950                resolveInfos.set(i, installerInfo);
6951                continue;
6952            }
6953            // caller is a full app, don't need to apply any other filtering
6954            if (ephemeralPkgName == null) {
6955                continue;
6956            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6957                // caller is same app; don't need to apply any other filtering
6958                continue;
6959            }
6960            // allow activities that have been explicitly exposed to ephemeral apps
6961            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6962            if (!isEphemeralApp
6963                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6964                continue;
6965            }
6966            resolveInfos.remove(i);
6967        }
6968        return resolveInfos;
6969    }
6970
6971    /**
6972     * Returns the activity component that can handle install failures.
6973     * <p>By default, the instant application installer handles failures. However, an
6974     * application may want to handle failures on its own. Applications do this by
6975     * creating an activity with an intent filter that handles the action
6976     * {@link Intent#ACTION_INSTALL_FAILURE}.
6977     */
6978    private @Nullable ComponentName findInstallFailureActivity(
6979            String packageName, int filterCallingUid, int userId) {
6980        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6981        failureActivityIntent.setPackage(packageName);
6982        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6983        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6984                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6985                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6986        final int NR = result.size();
6987        if (NR > 0) {
6988            for (int i = 0; i < NR; i++) {
6989                final ResolveInfo info = result.get(i);
6990                if (info.activityInfo.splitName != null) {
6991                    continue;
6992                }
6993                return new ComponentName(packageName, info.activityInfo.name);
6994            }
6995        }
6996        return null;
6997    }
6998
6999    /**
7000     * @param resolveInfos list of resolve infos in descending priority order
7001     * @return if the list contains a resolve info with non-negative priority
7002     */
7003    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7004        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7005    }
7006
7007    private static boolean hasWebURI(Intent intent) {
7008        if (intent.getData() == null) {
7009            return false;
7010        }
7011        final String scheme = intent.getScheme();
7012        if (TextUtils.isEmpty(scheme)) {
7013            return false;
7014        }
7015        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7016    }
7017
7018    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7019            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7020            int userId) {
7021        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7022
7023        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7024            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7025                    candidates.size());
7026        }
7027
7028        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7029        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7030        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7031        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7032        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7033        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7034
7035        synchronized (mPackages) {
7036            final int count = candidates.size();
7037            // First, try to use linked apps. Partition the candidates into four lists:
7038            // one for the final results, one for the "do not use ever", one for "undefined status"
7039            // and finally one for "browser app type".
7040            for (int n=0; n<count; n++) {
7041                ResolveInfo info = candidates.get(n);
7042                String packageName = info.activityInfo.packageName;
7043                PackageSetting ps = mSettings.mPackages.get(packageName);
7044                if (ps != null) {
7045                    // Add to the special match all list (Browser use case)
7046                    if (info.handleAllWebDataURI) {
7047                        matchAllList.add(info);
7048                        continue;
7049                    }
7050                    // Try to get the status from User settings first
7051                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7052                    int status = (int)(packedStatus >> 32);
7053                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7054                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7055                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7056                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7057                                    + " : linkgen=" + linkGeneration);
7058                        }
7059                        // Use link-enabled generation as preferredOrder, i.e.
7060                        // prefer newly-enabled over earlier-enabled.
7061                        info.preferredOrder = linkGeneration;
7062                        alwaysList.add(info);
7063                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7064                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7065                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7066                        }
7067                        neverList.add(info);
7068                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7069                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7070                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7071                        }
7072                        alwaysAskList.add(info);
7073                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7074                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7075                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7076                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7077                        }
7078                        undefinedList.add(info);
7079                    }
7080                }
7081            }
7082
7083            // We'll want to include browser possibilities in a few cases
7084            boolean includeBrowser = false;
7085
7086            // First try to add the "always" resolution(s) for the current user, if any
7087            if (alwaysList.size() > 0) {
7088                result.addAll(alwaysList);
7089            } else {
7090                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7091                result.addAll(undefinedList);
7092                // Maybe add one for the other profile.
7093                if (xpDomainInfo != null && (
7094                        xpDomainInfo.bestDomainVerificationStatus
7095                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7096                    result.add(xpDomainInfo.resolveInfo);
7097                }
7098                includeBrowser = true;
7099            }
7100
7101            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7102            // If there were 'always' entries their preferred order has been set, so we also
7103            // back that off to make the alternatives equivalent
7104            if (alwaysAskList.size() > 0) {
7105                for (ResolveInfo i : result) {
7106                    i.preferredOrder = 0;
7107                }
7108                result.addAll(alwaysAskList);
7109                includeBrowser = true;
7110            }
7111
7112            if (includeBrowser) {
7113                // Also add browsers (all of them or only the default one)
7114                if (DEBUG_DOMAIN_VERIFICATION) {
7115                    Slog.v(TAG, "   ...including browsers in candidate set");
7116                }
7117                if ((matchFlags & MATCH_ALL) != 0) {
7118                    result.addAll(matchAllList);
7119                } else {
7120                    // Browser/generic handling case.  If there's a default browser, go straight
7121                    // to that (but only if there is no other higher-priority match).
7122                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7123                    int maxMatchPrio = 0;
7124                    ResolveInfo defaultBrowserMatch = null;
7125                    final int numCandidates = matchAllList.size();
7126                    for (int n = 0; n < numCandidates; n++) {
7127                        ResolveInfo info = matchAllList.get(n);
7128                        // track the highest overall match priority...
7129                        if (info.priority > maxMatchPrio) {
7130                            maxMatchPrio = info.priority;
7131                        }
7132                        // ...and the highest-priority default browser match
7133                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7134                            if (defaultBrowserMatch == null
7135                                    || (defaultBrowserMatch.priority < info.priority)) {
7136                                if (debug) {
7137                                    Slog.v(TAG, "Considering default browser match " + info);
7138                                }
7139                                defaultBrowserMatch = info;
7140                            }
7141                        }
7142                    }
7143                    if (defaultBrowserMatch != null
7144                            && defaultBrowserMatch.priority >= maxMatchPrio
7145                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7146                    {
7147                        if (debug) {
7148                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7149                        }
7150                        result.add(defaultBrowserMatch);
7151                    } else {
7152                        result.addAll(matchAllList);
7153                    }
7154                }
7155
7156                // If there is nothing selected, add all candidates and remove the ones that the user
7157                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7158                if (result.size() == 0) {
7159                    result.addAll(candidates);
7160                    result.removeAll(neverList);
7161                }
7162            }
7163        }
7164        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7165            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7166                    result.size());
7167            for (ResolveInfo info : result) {
7168                Slog.v(TAG, "  + " + info.activityInfo);
7169            }
7170        }
7171        return result;
7172    }
7173
7174    // Returns a packed value as a long:
7175    //
7176    // high 'int'-sized word: link status: undefined/ask/never/always.
7177    // low 'int'-sized word: relative priority among 'always' results.
7178    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7179        long result = ps.getDomainVerificationStatusForUser(userId);
7180        // if none available, get the master status
7181        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7182            if (ps.getIntentFilterVerificationInfo() != null) {
7183                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7184            }
7185        }
7186        return result;
7187    }
7188
7189    private ResolveInfo querySkipCurrentProfileIntents(
7190            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7191            int flags, int sourceUserId) {
7192        if (matchingFilters != null) {
7193            int size = matchingFilters.size();
7194            for (int i = 0; i < size; i ++) {
7195                CrossProfileIntentFilter filter = matchingFilters.get(i);
7196                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7197                    // Checking if there are activities in the target user that can handle the
7198                    // intent.
7199                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7200                            resolvedType, flags, sourceUserId);
7201                    if (resolveInfo != null) {
7202                        return resolveInfo;
7203                    }
7204                }
7205            }
7206        }
7207        return null;
7208    }
7209
7210    // Return matching ResolveInfo in target user if any.
7211    private ResolveInfo queryCrossProfileIntents(
7212            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7213            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7214        if (matchingFilters != null) {
7215            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7216            // match the same intent. For performance reasons, it is better not to
7217            // run queryIntent twice for the same userId
7218            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7219            int size = matchingFilters.size();
7220            for (int i = 0; i < size; i++) {
7221                CrossProfileIntentFilter filter = matchingFilters.get(i);
7222                int targetUserId = filter.getTargetUserId();
7223                boolean skipCurrentProfile =
7224                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7225                boolean skipCurrentProfileIfNoMatchFound =
7226                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7227                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7228                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7229                    // Checking if there are activities in the target user that can handle the
7230                    // intent.
7231                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7232                            resolvedType, flags, sourceUserId);
7233                    if (resolveInfo != null) return resolveInfo;
7234                    alreadyTriedUserIds.put(targetUserId, true);
7235                }
7236            }
7237        }
7238        return null;
7239    }
7240
7241    /**
7242     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7243     * will forward the intent to the filter's target user.
7244     * Otherwise, returns null.
7245     */
7246    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7247            String resolvedType, int flags, int sourceUserId) {
7248        int targetUserId = filter.getTargetUserId();
7249        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7250                resolvedType, flags, targetUserId);
7251        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7252            // If all the matches in the target profile are suspended, return null.
7253            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7254                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7255                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7256                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7257                            targetUserId);
7258                }
7259            }
7260        }
7261        return null;
7262    }
7263
7264    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7265            int sourceUserId, int targetUserId) {
7266        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7267        long ident = Binder.clearCallingIdentity();
7268        boolean targetIsProfile;
7269        try {
7270            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7271        } finally {
7272            Binder.restoreCallingIdentity(ident);
7273        }
7274        String className;
7275        if (targetIsProfile) {
7276            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7277        } else {
7278            className = FORWARD_INTENT_TO_PARENT;
7279        }
7280        ComponentName forwardingActivityComponentName = new ComponentName(
7281                mAndroidApplication.packageName, className);
7282        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7283                sourceUserId);
7284        if (!targetIsProfile) {
7285            forwardingActivityInfo.showUserIcon = targetUserId;
7286            forwardingResolveInfo.noResourceId = true;
7287        }
7288        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7289        forwardingResolveInfo.priority = 0;
7290        forwardingResolveInfo.preferredOrder = 0;
7291        forwardingResolveInfo.match = 0;
7292        forwardingResolveInfo.isDefault = true;
7293        forwardingResolveInfo.filter = filter;
7294        forwardingResolveInfo.targetUserId = targetUserId;
7295        return forwardingResolveInfo;
7296    }
7297
7298    @Override
7299    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7300            Intent[] specifics, String[] specificTypes, Intent intent,
7301            String resolvedType, int flags, int userId) {
7302        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7303                specificTypes, intent, resolvedType, flags, userId));
7304    }
7305
7306    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7307            Intent[] specifics, String[] specificTypes, Intent intent,
7308            String resolvedType, int flags, int userId) {
7309        if (!sUserManager.exists(userId)) return Collections.emptyList();
7310        final int callingUid = Binder.getCallingUid();
7311        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7312                false /*includeInstantApps*/);
7313        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7314                false /*requireFullPermission*/, false /*checkShell*/,
7315                "query intent activity options");
7316        final String resultsAction = intent.getAction();
7317
7318        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7319                | PackageManager.GET_RESOLVED_FILTER, userId);
7320
7321        if (DEBUG_INTENT_MATCHING) {
7322            Log.v(TAG, "Query " + intent + ": " + results);
7323        }
7324
7325        int specificsPos = 0;
7326        int N;
7327
7328        // todo: note that the algorithm used here is O(N^2).  This
7329        // isn't a problem in our current environment, but if we start running
7330        // into situations where we have more than 5 or 10 matches then this
7331        // should probably be changed to something smarter...
7332
7333        // First we go through and resolve each of the specific items
7334        // that were supplied, taking care of removing any corresponding
7335        // duplicate items in the generic resolve list.
7336        if (specifics != null) {
7337            for (int i=0; i<specifics.length; i++) {
7338                final Intent sintent = specifics[i];
7339                if (sintent == null) {
7340                    continue;
7341                }
7342
7343                if (DEBUG_INTENT_MATCHING) {
7344                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7345                }
7346
7347                String action = sintent.getAction();
7348                if (resultsAction != null && resultsAction.equals(action)) {
7349                    // If this action was explicitly requested, then don't
7350                    // remove things that have it.
7351                    action = null;
7352                }
7353
7354                ResolveInfo ri = null;
7355                ActivityInfo ai = null;
7356
7357                ComponentName comp = sintent.getComponent();
7358                if (comp == null) {
7359                    ri = resolveIntent(
7360                        sintent,
7361                        specificTypes != null ? specificTypes[i] : null,
7362                            flags, userId);
7363                    if (ri == null) {
7364                        continue;
7365                    }
7366                    if (ri == mResolveInfo) {
7367                        // ACK!  Must do something better with this.
7368                    }
7369                    ai = ri.activityInfo;
7370                    comp = new ComponentName(ai.applicationInfo.packageName,
7371                            ai.name);
7372                } else {
7373                    ai = getActivityInfo(comp, flags, userId);
7374                    if (ai == null) {
7375                        continue;
7376                    }
7377                }
7378
7379                // Look for any generic query activities that are duplicates
7380                // of this specific one, and remove them from the results.
7381                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7382                N = results.size();
7383                int j;
7384                for (j=specificsPos; j<N; j++) {
7385                    ResolveInfo sri = results.get(j);
7386                    if ((sri.activityInfo.name.equals(comp.getClassName())
7387                            && sri.activityInfo.applicationInfo.packageName.equals(
7388                                    comp.getPackageName()))
7389                        || (action != null && sri.filter.matchAction(action))) {
7390                        results.remove(j);
7391                        if (DEBUG_INTENT_MATCHING) Log.v(
7392                            TAG, "Removing duplicate item from " + j
7393                            + " due to specific " + specificsPos);
7394                        if (ri == null) {
7395                            ri = sri;
7396                        }
7397                        j--;
7398                        N--;
7399                    }
7400                }
7401
7402                // Add this specific item to its proper place.
7403                if (ri == null) {
7404                    ri = new ResolveInfo();
7405                    ri.activityInfo = ai;
7406                }
7407                results.add(specificsPos, ri);
7408                ri.specificIndex = i;
7409                specificsPos++;
7410            }
7411        }
7412
7413        // Now we go through the remaining generic results and remove any
7414        // duplicate actions that are found here.
7415        N = results.size();
7416        for (int i=specificsPos; i<N-1; i++) {
7417            final ResolveInfo rii = results.get(i);
7418            if (rii.filter == null) {
7419                continue;
7420            }
7421
7422            // Iterate over all of the actions of this result's intent
7423            // filter...  typically this should be just one.
7424            final Iterator<String> it = rii.filter.actionsIterator();
7425            if (it == null) {
7426                continue;
7427            }
7428            while (it.hasNext()) {
7429                final String action = it.next();
7430                if (resultsAction != null && resultsAction.equals(action)) {
7431                    // If this action was explicitly requested, then don't
7432                    // remove things that have it.
7433                    continue;
7434                }
7435                for (int j=i+1; j<N; j++) {
7436                    final ResolveInfo rij = results.get(j);
7437                    if (rij.filter != null && rij.filter.hasAction(action)) {
7438                        results.remove(j);
7439                        if (DEBUG_INTENT_MATCHING) Log.v(
7440                            TAG, "Removing duplicate item from " + j
7441                            + " due to action " + action + " at " + i);
7442                        j--;
7443                        N--;
7444                    }
7445                }
7446            }
7447
7448            // If the caller didn't request filter information, drop it now
7449            // so we don't have to marshall/unmarshall it.
7450            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7451                rii.filter = null;
7452            }
7453        }
7454
7455        // Filter out the caller activity if so requested.
7456        if (caller != null) {
7457            N = results.size();
7458            for (int i=0; i<N; i++) {
7459                ActivityInfo ainfo = results.get(i).activityInfo;
7460                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7461                        && caller.getClassName().equals(ainfo.name)) {
7462                    results.remove(i);
7463                    break;
7464                }
7465            }
7466        }
7467
7468        // If the caller didn't request filter information,
7469        // drop them now so we don't have to
7470        // marshall/unmarshall it.
7471        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7472            N = results.size();
7473            for (int i=0; i<N; i++) {
7474                results.get(i).filter = null;
7475            }
7476        }
7477
7478        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7479        return results;
7480    }
7481
7482    @Override
7483    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7484            String resolvedType, int flags, int userId) {
7485        return new ParceledListSlice<>(
7486                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7487                        false /*allowDynamicSplits*/));
7488    }
7489
7490    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7491            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7492        if (!sUserManager.exists(userId)) return Collections.emptyList();
7493        final int callingUid = Binder.getCallingUid();
7494        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7495                false /*requireFullPermission*/, false /*checkShell*/,
7496                "query intent receivers");
7497        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7498        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7499                false /*includeInstantApps*/);
7500        ComponentName comp = intent.getComponent();
7501        if (comp == null) {
7502            if (intent.getSelector() != null) {
7503                intent = intent.getSelector();
7504                comp = intent.getComponent();
7505            }
7506        }
7507        if (comp != null) {
7508            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7509            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7510            if (ai != null) {
7511                // When specifying an explicit component, we prevent the activity from being
7512                // used when either 1) the calling package is normal and the activity is within
7513                // an instant application or 2) the calling package is ephemeral and the
7514                // activity is not visible to instant applications.
7515                final boolean matchInstantApp =
7516                        (flags & PackageManager.MATCH_INSTANT) != 0;
7517                final boolean matchVisibleToInstantAppOnly =
7518                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7519                final boolean matchExplicitlyVisibleOnly =
7520                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7521                final boolean isCallerInstantApp =
7522                        instantAppPkgName != null;
7523                final boolean isTargetSameInstantApp =
7524                        comp.getPackageName().equals(instantAppPkgName);
7525                final boolean isTargetInstantApp =
7526                        (ai.applicationInfo.privateFlags
7527                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7528                final boolean isTargetVisibleToInstantApp =
7529                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7530                final boolean isTargetExplicitlyVisibleToInstantApp =
7531                        isTargetVisibleToInstantApp
7532                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7533                final boolean isTargetHiddenFromInstantApp =
7534                        !isTargetVisibleToInstantApp
7535                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7536                final boolean blockResolution =
7537                        !isTargetSameInstantApp
7538                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7539                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7540                                        && isTargetHiddenFromInstantApp));
7541                if (!blockResolution) {
7542                    ResolveInfo ri = new ResolveInfo();
7543                    ri.activityInfo = ai;
7544                    list.add(ri);
7545                }
7546            }
7547            return applyPostResolutionFilter(
7548                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7549        }
7550
7551        // reader
7552        synchronized (mPackages) {
7553            String pkgName = intent.getPackage();
7554            if (pkgName == null) {
7555                final List<ResolveInfo> result =
7556                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7557                return applyPostResolutionFilter(
7558                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7559            }
7560            final PackageParser.Package pkg = mPackages.get(pkgName);
7561            if (pkg != null) {
7562                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7563                        intent, resolvedType, flags, pkg.receivers, userId);
7564                return applyPostResolutionFilter(
7565                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7566            }
7567            return Collections.emptyList();
7568        }
7569    }
7570
7571    @Override
7572    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7573        final int callingUid = Binder.getCallingUid();
7574        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7575    }
7576
7577    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7578            int userId, int callingUid) {
7579        if (!sUserManager.exists(userId)) return null;
7580        flags = updateFlagsForResolve(
7581                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7582        List<ResolveInfo> query = queryIntentServicesInternal(
7583                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7584        if (query != null) {
7585            if (query.size() >= 1) {
7586                // If there is more than one service with the same priority,
7587                // just arbitrarily pick the first one.
7588                return query.get(0);
7589            }
7590        }
7591        return null;
7592    }
7593
7594    @Override
7595    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7596            String resolvedType, int flags, int userId) {
7597        final int callingUid = Binder.getCallingUid();
7598        return new ParceledListSlice<>(queryIntentServicesInternal(
7599                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7600    }
7601
7602    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7603            String resolvedType, int flags, int userId, int callingUid,
7604            boolean includeInstantApps) {
7605        if (!sUserManager.exists(userId)) return Collections.emptyList();
7606        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7607                false /*requireFullPermission*/, false /*checkShell*/,
7608                "query intent receivers");
7609        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7610        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7611        ComponentName comp = intent.getComponent();
7612        if (comp == null) {
7613            if (intent.getSelector() != null) {
7614                intent = intent.getSelector();
7615                comp = intent.getComponent();
7616            }
7617        }
7618        if (comp != null) {
7619            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7620            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7621            if (si != null) {
7622                // When specifying an explicit component, we prevent the service from being
7623                // used when either 1) the service is in an instant application and the
7624                // caller is not the same instant application or 2) the calling package is
7625                // ephemeral and the activity is not visible to ephemeral applications.
7626                final boolean matchInstantApp =
7627                        (flags & PackageManager.MATCH_INSTANT) != 0;
7628                final boolean matchVisibleToInstantAppOnly =
7629                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7630                final boolean isCallerInstantApp =
7631                        instantAppPkgName != null;
7632                final boolean isTargetSameInstantApp =
7633                        comp.getPackageName().equals(instantAppPkgName);
7634                final boolean isTargetInstantApp =
7635                        (si.applicationInfo.privateFlags
7636                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7637                final boolean isTargetHiddenFromInstantApp =
7638                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7639                final boolean blockResolution =
7640                        !isTargetSameInstantApp
7641                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7642                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7643                                        && isTargetHiddenFromInstantApp));
7644                if (!blockResolution) {
7645                    final ResolveInfo ri = new ResolveInfo();
7646                    ri.serviceInfo = si;
7647                    list.add(ri);
7648                }
7649            }
7650            return list;
7651        }
7652
7653        // reader
7654        synchronized (mPackages) {
7655            String pkgName = intent.getPackage();
7656            if (pkgName == null) {
7657                return applyPostServiceResolutionFilter(
7658                        mServices.queryIntent(intent, resolvedType, flags, userId),
7659                        instantAppPkgName);
7660            }
7661            final PackageParser.Package pkg = mPackages.get(pkgName);
7662            if (pkg != null) {
7663                return applyPostServiceResolutionFilter(
7664                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7665                                userId),
7666                        instantAppPkgName);
7667            }
7668            return Collections.emptyList();
7669        }
7670    }
7671
7672    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7673            String instantAppPkgName) {
7674        if (instantAppPkgName == null) {
7675            return resolveInfos;
7676        }
7677        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7678            final ResolveInfo info = resolveInfos.get(i);
7679            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7680            // allow services that are defined in the provided package
7681            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7682                if (info.serviceInfo.splitName != null
7683                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7684                                info.serviceInfo.splitName)) {
7685                    // requested service is defined in a split that hasn't been installed yet.
7686                    // add the installer to the resolve list
7687                    if (DEBUG_EPHEMERAL) {
7688                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7689                    }
7690                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7691                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7692                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7693                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7694                            null /*failureIntent*/);
7695                    // make sure this resolver is the default
7696                    installerInfo.isDefault = true;
7697                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7698                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7699                    // add a non-generic filter
7700                    installerInfo.filter = new IntentFilter();
7701                    // load resources from the correct package
7702                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7703                    resolveInfos.set(i, installerInfo);
7704                }
7705                continue;
7706            }
7707            // allow services that have been explicitly exposed to ephemeral apps
7708            if (!isEphemeralApp
7709                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7710                continue;
7711            }
7712            resolveInfos.remove(i);
7713        }
7714        return resolveInfos;
7715    }
7716
7717    @Override
7718    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7719            String resolvedType, int flags, int userId) {
7720        return new ParceledListSlice<>(
7721                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7722    }
7723
7724    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7725            Intent intent, String resolvedType, int flags, int userId) {
7726        if (!sUserManager.exists(userId)) return Collections.emptyList();
7727        final int callingUid = Binder.getCallingUid();
7728        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7729        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7730                false /*includeInstantApps*/);
7731        ComponentName comp = intent.getComponent();
7732        if (comp == null) {
7733            if (intent.getSelector() != null) {
7734                intent = intent.getSelector();
7735                comp = intent.getComponent();
7736            }
7737        }
7738        if (comp != null) {
7739            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7740            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7741            if (pi != null) {
7742                // When specifying an explicit component, we prevent the provider from being
7743                // used when either 1) the provider is in an instant application and the
7744                // caller is not the same instant application or 2) the calling package is an
7745                // instant application and the provider is not visible to instant applications.
7746                final boolean matchInstantApp =
7747                        (flags & PackageManager.MATCH_INSTANT) != 0;
7748                final boolean matchVisibleToInstantAppOnly =
7749                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7750                final boolean isCallerInstantApp =
7751                        instantAppPkgName != null;
7752                final boolean isTargetSameInstantApp =
7753                        comp.getPackageName().equals(instantAppPkgName);
7754                final boolean isTargetInstantApp =
7755                        (pi.applicationInfo.privateFlags
7756                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7757                final boolean isTargetHiddenFromInstantApp =
7758                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7759                final boolean blockResolution =
7760                        !isTargetSameInstantApp
7761                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7762                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7763                                        && isTargetHiddenFromInstantApp));
7764                if (!blockResolution) {
7765                    final ResolveInfo ri = new ResolveInfo();
7766                    ri.providerInfo = pi;
7767                    list.add(ri);
7768                }
7769            }
7770            return list;
7771        }
7772
7773        // reader
7774        synchronized (mPackages) {
7775            String pkgName = intent.getPackage();
7776            if (pkgName == null) {
7777                return applyPostContentProviderResolutionFilter(
7778                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7779                        instantAppPkgName);
7780            }
7781            final PackageParser.Package pkg = mPackages.get(pkgName);
7782            if (pkg != null) {
7783                return applyPostContentProviderResolutionFilter(
7784                        mProviders.queryIntentForPackage(
7785                        intent, resolvedType, flags, pkg.providers, userId),
7786                        instantAppPkgName);
7787            }
7788            return Collections.emptyList();
7789        }
7790    }
7791
7792    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7793            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7794        if (instantAppPkgName == null) {
7795            return resolveInfos;
7796        }
7797        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7798            final ResolveInfo info = resolveInfos.get(i);
7799            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7800            // allow providers that are defined in the provided package
7801            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7802                if (info.providerInfo.splitName != null
7803                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7804                                info.providerInfo.splitName)) {
7805                    // requested provider is defined in a split that hasn't been installed yet.
7806                    // add the installer to the resolve list
7807                    if (DEBUG_EPHEMERAL) {
7808                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7809                    }
7810                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7811                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7812                            info.providerInfo.packageName, info.providerInfo.splitName,
7813                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7814                            null /*failureIntent*/);
7815                    // make sure this resolver is the default
7816                    installerInfo.isDefault = true;
7817                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7818                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7819                    // add a non-generic filter
7820                    installerInfo.filter = new IntentFilter();
7821                    // load resources from the correct package
7822                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7823                    resolveInfos.set(i, installerInfo);
7824                }
7825                continue;
7826            }
7827            // allow providers that have been explicitly exposed to instant applications
7828            if (!isEphemeralApp
7829                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7830                continue;
7831            }
7832            resolveInfos.remove(i);
7833        }
7834        return resolveInfos;
7835    }
7836
7837    @Override
7838    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7839        final int callingUid = Binder.getCallingUid();
7840        if (getInstantAppPackageName(callingUid) != null) {
7841            return ParceledListSlice.emptyList();
7842        }
7843        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7844        flags = updateFlagsForPackage(flags, userId, null);
7845        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7846        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7847                true /* requireFullPermission */, false /* checkShell */,
7848                "get installed packages");
7849
7850        // writer
7851        synchronized (mPackages) {
7852            ArrayList<PackageInfo> list;
7853            if (listUninstalled) {
7854                list = new ArrayList<>(mSettings.mPackages.size());
7855                for (PackageSetting ps : mSettings.mPackages.values()) {
7856                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7857                        continue;
7858                    }
7859                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7860                        continue;
7861                    }
7862                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7863                    if (pi != null) {
7864                        list.add(pi);
7865                    }
7866                }
7867            } else {
7868                list = new ArrayList<>(mPackages.size());
7869                for (PackageParser.Package p : mPackages.values()) {
7870                    final PackageSetting ps = (PackageSetting) p.mExtras;
7871                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7872                        continue;
7873                    }
7874                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7875                        continue;
7876                    }
7877                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7878                            p.mExtras, flags, userId);
7879                    if (pi != null) {
7880                        list.add(pi);
7881                    }
7882                }
7883            }
7884
7885            return new ParceledListSlice<>(list);
7886        }
7887    }
7888
7889    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7890            String[] permissions, boolean[] tmp, int flags, int userId) {
7891        int numMatch = 0;
7892        final PermissionsState permissionsState = ps.getPermissionsState();
7893        for (int i=0; i<permissions.length; i++) {
7894            final String permission = permissions[i];
7895            if (permissionsState.hasPermission(permission, userId)) {
7896                tmp[i] = true;
7897                numMatch++;
7898            } else {
7899                tmp[i] = false;
7900            }
7901        }
7902        if (numMatch == 0) {
7903            return;
7904        }
7905        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7906
7907        // The above might return null in cases of uninstalled apps or install-state
7908        // skew across users/profiles.
7909        if (pi != null) {
7910            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7911                if (numMatch == permissions.length) {
7912                    pi.requestedPermissions = permissions;
7913                } else {
7914                    pi.requestedPermissions = new String[numMatch];
7915                    numMatch = 0;
7916                    for (int i=0; i<permissions.length; i++) {
7917                        if (tmp[i]) {
7918                            pi.requestedPermissions[numMatch] = permissions[i];
7919                            numMatch++;
7920                        }
7921                    }
7922                }
7923            }
7924            list.add(pi);
7925        }
7926    }
7927
7928    @Override
7929    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7930            String[] permissions, int flags, int userId) {
7931        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7932        flags = updateFlagsForPackage(flags, userId, permissions);
7933        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7934                true /* requireFullPermission */, false /* checkShell */,
7935                "get packages holding permissions");
7936        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7937
7938        // writer
7939        synchronized (mPackages) {
7940            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7941            boolean[] tmpBools = new boolean[permissions.length];
7942            if (listUninstalled) {
7943                for (PackageSetting ps : mSettings.mPackages.values()) {
7944                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7945                            userId);
7946                }
7947            } else {
7948                for (PackageParser.Package pkg : mPackages.values()) {
7949                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7950                    if (ps != null) {
7951                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7952                                userId);
7953                    }
7954                }
7955            }
7956
7957            return new ParceledListSlice<PackageInfo>(list);
7958        }
7959    }
7960
7961    @Override
7962    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7963        final int callingUid = Binder.getCallingUid();
7964        if (getInstantAppPackageName(callingUid) != null) {
7965            return ParceledListSlice.emptyList();
7966        }
7967        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7968        flags = updateFlagsForApplication(flags, userId, null);
7969        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7970
7971        // writer
7972        synchronized (mPackages) {
7973            ArrayList<ApplicationInfo> list;
7974            if (listUninstalled) {
7975                list = new ArrayList<>(mSettings.mPackages.size());
7976                for (PackageSetting ps : mSettings.mPackages.values()) {
7977                    ApplicationInfo ai;
7978                    int effectiveFlags = flags;
7979                    if (ps.isSystem()) {
7980                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7981                    }
7982                    if (ps.pkg != null) {
7983                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7984                            continue;
7985                        }
7986                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7987                            continue;
7988                        }
7989                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7990                                ps.readUserState(userId), userId);
7991                        if (ai != null) {
7992                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7993                        }
7994                    } else {
7995                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7996                        // and already converts to externally visible package name
7997                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7998                                callingUid, effectiveFlags, userId);
7999                    }
8000                    if (ai != null) {
8001                        list.add(ai);
8002                    }
8003                }
8004            } else {
8005                list = new ArrayList<>(mPackages.size());
8006                for (PackageParser.Package p : mPackages.values()) {
8007                    if (p.mExtras != null) {
8008                        PackageSetting ps = (PackageSetting) p.mExtras;
8009                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8010                            continue;
8011                        }
8012                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8013                            continue;
8014                        }
8015                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8016                                ps.readUserState(userId), userId);
8017                        if (ai != null) {
8018                            ai.packageName = resolveExternalPackageNameLPr(p);
8019                            list.add(ai);
8020                        }
8021                    }
8022                }
8023            }
8024
8025            return new ParceledListSlice<>(list);
8026        }
8027    }
8028
8029    @Override
8030    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8031        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8032            return null;
8033        }
8034        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8035            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8036                    "getEphemeralApplications");
8037        }
8038        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8039                true /* requireFullPermission */, false /* checkShell */,
8040                "getEphemeralApplications");
8041        synchronized (mPackages) {
8042            List<InstantAppInfo> instantApps = mInstantAppRegistry
8043                    .getInstantAppsLPr(userId);
8044            if (instantApps != null) {
8045                return new ParceledListSlice<>(instantApps);
8046            }
8047        }
8048        return null;
8049    }
8050
8051    @Override
8052    public boolean isInstantApp(String packageName, int userId) {
8053        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8054                true /* requireFullPermission */, false /* checkShell */,
8055                "isInstantApp");
8056        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8057            return false;
8058        }
8059
8060        synchronized (mPackages) {
8061            int callingUid = Binder.getCallingUid();
8062            if (Process.isIsolated(callingUid)) {
8063                callingUid = mIsolatedOwners.get(callingUid);
8064            }
8065            final PackageSetting ps = mSettings.mPackages.get(packageName);
8066            PackageParser.Package pkg = mPackages.get(packageName);
8067            final boolean returnAllowed =
8068                    ps != null
8069                    && (isCallerSameApp(packageName, callingUid)
8070                            || canViewInstantApps(callingUid, userId)
8071                            || mInstantAppRegistry.isInstantAccessGranted(
8072                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8073            if (returnAllowed) {
8074                return ps.getInstantApp(userId);
8075            }
8076        }
8077        return false;
8078    }
8079
8080    @Override
8081    public byte[] getInstantAppCookie(String packageName, int userId) {
8082        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8083            return null;
8084        }
8085
8086        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8087                true /* requireFullPermission */, false /* checkShell */,
8088                "getInstantAppCookie");
8089        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8090            return null;
8091        }
8092        synchronized (mPackages) {
8093            return mInstantAppRegistry.getInstantAppCookieLPw(
8094                    packageName, userId);
8095        }
8096    }
8097
8098    @Override
8099    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8100        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8101            return true;
8102        }
8103
8104        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8105                true /* requireFullPermission */, true /* checkShell */,
8106                "setInstantAppCookie");
8107        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8108            return false;
8109        }
8110        synchronized (mPackages) {
8111            return mInstantAppRegistry.setInstantAppCookieLPw(
8112                    packageName, cookie, userId);
8113        }
8114    }
8115
8116    @Override
8117    public Bitmap getInstantAppIcon(String packageName, int userId) {
8118        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8119            return null;
8120        }
8121
8122        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8123            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8124                    "getInstantAppIcon");
8125        }
8126        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8127                true /* requireFullPermission */, false /* checkShell */,
8128                "getInstantAppIcon");
8129
8130        synchronized (mPackages) {
8131            return mInstantAppRegistry.getInstantAppIconLPw(
8132                    packageName, userId);
8133        }
8134    }
8135
8136    private boolean isCallerSameApp(String packageName, int uid) {
8137        PackageParser.Package pkg = mPackages.get(packageName);
8138        return pkg != null
8139                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8140    }
8141
8142    @Override
8143    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8144        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8145            return ParceledListSlice.emptyList();
8146        }
8147        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8148    }
8149
8150    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8151        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8152
8153        // reader
8154        synchronized (mPackages) {
8155            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8156            final int userId = UserHandle.getCallingUserId();
8157            while (i.hasNext()) {
8158                final PackageParser.Package p = i.next();
8159                if (p.applicationInfo == null) continue;
8160
8161                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8162                        && !p.applicationInfo.isDirectBootAware();
8163                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8164                        && p.applicationInfo.isDirectBootAware();
8165
8166                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8167                        && (!mSafeMode || isSystemApp(p))
8168                        && (matchesUnaware || matchesAware)) {
8169                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8170                    if (ps != null) {
8171                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8172                                ps.readUserState(userId), userId);
8173                        if (ai != null) {
8174                            finalList.add(ai);
8175                        }
8176                    }
8177                }
8178            }
8179        }
8180
8181        return finalList;
8182    }
8183
8184    @Override
8185    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8186        return resolveContentProviderInternal(name, flags, userId);
8187    }
8188
8189    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8190        if (!sUserManager.exists(userId)) return null;
8191        flags = updateFlagsForComponent(flags, userId, name);
8192        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8193        // reader
8194        synchronized (mPackages) {
8195            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8196            PackageSetting ps = provider != null
8197                    ? mSettings.mPackages.get(provider.owner.packageName)
8198                    : null;
8199            if (ps != null) {
8200                final boolean isInstantApp = ps.getInstantApp(userId);
8201                // normal application; filter out instant application provider
8202                if (instantAppPkgName == null && isInstantApp) {
8203                    return null;
8204                }
8205                // instant application; filter out other instant applications
8206                if (instantAppPkgName != null
8207                        && isInstantApp
8208                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8209                    return null;
8210                }
8211                // instant application; filter out non-exposed provider
8212                if (instantAppPkgName != null
8213                        && !isInstantApp
8214                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8215                    return null;
8216                }
8217                // provider not enabled
8218                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8219                    return null;
8220                }
8221                return PackageParser.generateProviderInfo(
8222                        provider, flags, ps.readUserState(userId), userId);
8223            }
8224            return null;
8225        }
8226    }
8227
8228    /**
8229     * @deprecated
8230     */
8231    @Deprecated
8232    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8233        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8234            return;
8235        }
8236        // reader
8237        synchronized (mPackages) {
8238            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8239                    .entrySet().iterator();
8240            final int userId = UserHandle.getCallingUserId();
8241            while (i.hasNext()) {
8242                Map.Entry<String, PackageParser.Provider> entry = i.next();
8243                PackageParser.Provider p = entry.getValue();
8244                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8245
8246                if (ps != null && p.syncable
8247                        && (!mSafeMode || (p.info.applicationInfo.flags
8248                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8249                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8250                            ps.readUserState(userId), userId);
8251                    if (info != null) {
8252                        outNames.add(entry.getKey());
8253                        outInfo.add(info);
8254                    }
8255                }
8256            }
8257        }
8258    }
8259
8260    @Override
8261    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8262            int uid, int flags, String metaDataKey) {
8263        final int callingUid = Binder.getCallingUid();
8264        final int userId = processName != null ? UserHandle.getUserId(uid)
8265                : UserHandle.getCallingUserId();
8266        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8267        flags = updateFlagsForComponent(flags, userId, processName);
8268        ArrayList<ProviderInfo> finalList = null;
8269        // reader
8270        synchronized (mPackages) {
8271            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8272            while (i.hasNext()) {
8273                final PackageParser.Provider p = i.next();
8274                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8275                if (ps != null && p.info.authority != null
8276                        && (processName == null
8277                                || (p.info.processName.equals(processName)
8278                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8279                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8280
8281                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8282                    // parameter.
8283                    if (metaDataKey != null
8284                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8285                        continue;
8286                    }
8287                    final ComponentName component =
8288                            new ComponentName(p.info.packageName, p.info.name);
8289                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8290                        continue;
8291                    }
8292                    if (finalList == null) {
8293                        finalList = new ArrayList<ProviderInfo>(3);
8294                    }
8295                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8296                            ps.readUserState(userId), userId);
8297                    if (info != null) {
8298                        finalList.add(info);
8299                    }
8300                }
8301            }
8302        }
8303
8304        if (finalList != null) {
8305            Collections.sort(finalList, mProviderInitOrderSorter);
8306            return new ParceledListSlice<ProviderInfo>(finalList);
8307        }
8308
8309        return ParceledListSlice.emptyList();
8310    }
8311
8312    @Override
8313    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8314        // reader
8315        synchronized (mPackages) {
8316            final int callingUid = Binder.getCallingUid();
8317            final int callingUserId = UserHandle.getUserId(callingUid);
8318            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8319            if (ps == null) return null;
8320            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8321                return null;
8322            }
8323            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8324            return PackageParser.generateInstrumentationInfo(i, flags);
8325        }
8326    }
8327
8328    @Override
8329    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8330            String targetPackage, int flags) {
8331        final int callingUid = Binder.getCallingUid();
8332        final int callingUserId = UserHandle.getUserId(callingUid);
8333        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8334        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8335            return ParceledListSlice.emptyList();
8336        }
8337        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8338    }
8339
8340    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8341            int flags) {
8342        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8343
8344        // reader
8345        synchronized (mPackages) {
8346            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8347            while (i.hasNext()) {
8348                final PackageParser.Instrumentation p = i.next();
8349                if (targetPackage == null
8350                        || targetPackage.equals(p.info.targetPackage)) {
8351                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8352                            flags);
8353                    if (ii != null) {
8354                        finalList.add(ii);
8355                    }
8356                }
8357            }
8358        }
8359
8360        return finalList;
8361    }
8362
8363    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8365        try {
8366            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8367        } finally {
8368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8369        }
8370    }
8371
8372    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8373        final File[] files = dir.listFiles();
8374        if (ArrayUtils.isEmpty(files)) {
8375            Log.d(TAG, "No files in app dir " + dir);
8376            return;
8377        }
8378
8379        if (DEBUG_PACKAGE_SCANNING) {
8380            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8381                    + " flags=0x" + Integer.toHexString(parseFlags));
8382        }
8383        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8384                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8385                mParallelPackageParserCallback);
8386
8387        // Submit files for parsing in parallel
8388        int fileCount = 0;
8389        for (File file : files) {
8390            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8391                    && !PackageInstallerService.isStageName(file.getName());
8392            if (!isPackage) {
8393                // Ignore entries which are not packages
8394                continue;
8395            }
8396            parallelPackageParser.submit(file, parseFlags);
8397            fileCount++;
8398        }
8399
8400        // Process results one by one
8401        for (; fileCount > 0; fileCount--) {
8402            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8403            Throwable throwable = parseResult.throwable;
8404            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8405
8406            if (throwable == null) {
8407                // Static shared libraries have synthetic package names
8408                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8409                    renameStaticSharedLibraryPackage(parseResult.pkg);
8410                }
8411                try {
8412                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8413                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8414                                currentTime, null);
8415                    }
8416                } catch (PackageManagerException e) {
8417                    errorCode = e.error;
8418                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8419                }
8420            } else if (throwable instanceof PackageParser.PackageParserException) {
8421                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8422                        throwable;
8423                errorCode = e.error;
8424                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8425            } else {
8426                throw new IllegalStateException("Unexpected exception occurred while parsing "
8427                        + parseResult.scanFile, throwable);
8428            }
8429
8430            // Delete invalid userdata apps
8431            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8432                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8433                logCriticalInfo(Log.WARN,
8434                        "Deleting invalid package at " + parseResult.scanFile);
8435                removeCodePathLI(parseResult.scanFile);
8436            }
8437        }
8438        parallelPackageParser.close();
8439    }
8440
8441    private static File getSettingsProblemFile() {
8442        File dataDir = Environment.getDataDirectory();
8443        File systemDir = new File(dataDir, "system");
8444        File fname = new File(systemDir, "uiderrors.txt");
8445        return fname;
8446    }
8447
8448    public static void reportSettingsProblem(int priority, String msg) {
8449        logCriticalInfo(priority, msg);
8450    }
8451
8452    public static void logCriticalInfo(int priority, String msg) {
8453        Slog.println(priority, TAG, msg);
8454        EventLogTags.writePmCriticalInfo(msg);
8455        try {
8456            File fname = getSettingsProblemFile();
8457            FileOutputStream out = new FileOutputStream(fname, true);
8458            PrintWriter pw = new FastPrintWriter(out);
8459            SimpleDateFormat formatter = new SimpleDateFormat();
8460            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8461            pw.println(dateString + ": " + msg);
8462            pw.close();
8463            FileUtils.setPermissions(
8464                    fname.toString(),
8465                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8466                    -1, -1);
8467        } catch (java.io.IOException e) {
8468        }
8469    }
8470
8471    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8472        if (srcFile.isDirectory()) {
8473            final File baseFile = new File(pkg.baseCodePath);
8474            long maxModifiedTime = baseFile.lastModified();
8475            if (pkg.splitCodePaths != null) {
8476                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8477                    final File splitFile = new File(pkg.splitCodePaths[i]);
8478                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8479                }
8480            }
8481            return maxModifiedTime;
8482        }
8483        return srcFile.lastModified();
8484    }
8485
8486    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8487            final int policyFlags) throws PackageManagerException {
8488        // When upgrading from pre-N MR1, verify the package time stamp using the package
8489        // directory and not the APK file.
8490        final long lastModifiedTime = mIsPreNMR1Upgrade
8491                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8492        if (ps != null
8493                && ps.codePath.equals(srcFile)
8494                && ps.timeStamp == lastModifiedTime
8495                && !isCompatSignatureUpdateNeeded(pkg)
8496                && !isRecoverSignatureUpdateNeeded(pkg)) {
8497            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8498            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8499            ArraySet<PublicKey> signingKs;
8500            synchronized (mPackages) {
8501                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8502            }
8503            if (ps.signatures.mSignatures != null
8504                    && ps.signatures.mSignatures.length != 0
8505                    && signingKs != null) {
8506                // Optimization: reuse the existing cached certificates
8507                // if the package appears to be unchanged.
8508                pkg.mSignatures = ps.signatures.mSignatures;
8509                pkg.mSigningKeys = signingKs;
8510                return;
8511            }
8512
8513            Slog.w(TAG, "PackageSetting for " + ps.name
8514                    + " is missing signatures.  Collecting certs again to recover them.");
8515        } else {
8516            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8517        }
8518
8519        try {
8520            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8521            PackageParser.collectCertificates(pkg, policyFlags);
8522        } catch (PackageParserException e) {
8523            throw PackageManagerException.from(e);
8524        } finally {
8525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8526        }
8527    }
8528
8529    /**
8530     *  Traces a package scan.
8531     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8532     */
8533    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8534            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8535        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8536        try {
8537            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8538        } finally {
8539            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8540        }
8541    }
8542
8543    /**
8544     *  Scans a package and returns the newly parsed package.
8545     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8546     */
8547    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8548            long currentTime, UserHandle user) throws PackageManagerException {
8549        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8550        PackageParser pp = new PackageParser();
8551        pp.setSeparateProcesses(mSeparateProcesses);
8552        pp.setOnlyCoreApps(mOnlyCore);
8553        pp.setDisplayMetrics(mMetrics);
8554        pp.setCallback(mPackageParserCallback);
8555
8556        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8557            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8558        }
8559
8560        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8561        final PackageParser.Package pkg;
8562        try {
8563            pkg = pp.parsePackage(scanFile, parseFlags);
8564        } catch (PackageParserException e) {
8565            throw PackageManagerException.from(e);
8566        } finally {
8567            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8568        }
8569
8570        // Static shared libraries have synthetic package names
8571        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8572            renameStaticSharedLibraryPackage(pkg);
8573        }
8574
8575        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8576    }
8577
8578    /**
8579     *  Scans a package and returns the newly parsed package.
8580     *  @throws PackageManagerException on a parse error.
8581     */
8582    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8583            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8584            throws PackageManagerException {
8585        // If the package has children and this is the first dive in the function
8586        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8587        // packages (parent and children) would be successfully scanned before the
8588        // actual scan since scanning mutates internal state and we want to atomically
8589        // install the package and its children.
8590        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8591            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8592                scanFlags |= SCAN_CHECK_ONLY;
8593            }
8594        } else {
8595            scanFlags &= ~SCAN_CHECK_ONLY;
8596        }
8597
8598        // Scan the parent
8599        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8600                scanFlags, currentTime, user);
8601
8602        // Scan the children
8603        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8604        for (int i = 0; i < childCount; i++) {
8605            PackageParser.Package childPackage = pkg.childPackages.get(i);
8606            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8607                    currentTime, user);
8608        }
8609
8610
8611        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8612            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8613        }
8614
8615        return scannedPkg;
8616    }
8617
8618    /**
8619     *  Scans a package and returns the newly parsed package.
8620     *  @throws PackageManagerException on a parse error.
8621     */
8622    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8623            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8624            throws PackageManagerException {
8625        PackageSetting ps = null;
8626        PackageSetting updatedPkg;
8627        // reader
8628        synchronized (mPackages) {
8629            // Look to see if we already know about this package.
8630            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8631            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8632                // This package has been renamed to its original name.  Let's
8633                // use that.
8634                ps = mSettings.getPackageLPr(oldName);
8635            }
8636            // If there was no original package, see one for the real package name.
8637            if (ps == null) {
8638                ps = mSettings.getPackageLPr(pkg.packageName);
8639            }
8640            // Check to see if this package could be hiding/updating a system
8641            // package.  Must look for it either under the original or real
8642            // package name depending on our state.
8643            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8644            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8645
8646            // If this is a package we don't know about on the system partition, we
8647            // may need to remove disabled child packages on the system partition
8648            // or may need to not add child packages if the parent apk is updated
8649            // on the data partition and no longer defines this child package.
8650            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8651                // If this is a parent package for an updated system app and this system
8652                // app got an OTA update which no longer defines some of the child packages
8653                // we have to prune them from the disabled system packages.
8654                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8655                if (disabledPs != null) {
8656                    final int scannedChildCount = (pkg.childPackages != null)
8657                            ? pkg.childPackages.size() : 0;
8658                    final int disabledChildCount = disabledPs.childPackageNames != null
8659                            ? disabledPs.childPackageNames.size() : 0;
8660                    for (int i = 0; i < disabledChildCount; i++) {
8661                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8662                        boolean disabledPackageAvailable = false;
8663                        for (int j = 0; j < scannedChildCount; j++) {
8664                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8665                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8666                                disabledPackageAvailable = true;
8667                                break;
8668                            }
8669                         }
8670                         if (!disabledPackageAvailable) {
8671                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8672                         }
8673                    }
8674                }
8675            }
8676        }
8677
8678        final boolean isUpdatedPkg = updatedPkg != null;
8679        final boolean isUpdatedSystemPkg = isUpdatedPkg
8680                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8681        boolean isUpdatedPkgBetter = false;
8682        // First check if this is a system package that may involve an update
8683        if (isUpdatedSystemPkg) {
8684            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8685            // it needs to drop FLAG_PRIVILEGED.
8686            if (locationIsPrivileged(scanFile)) {
8687                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8688            } else {
8689                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8690            }
8691            // If new package is not located in "/oem" (e.g. due to an OTA),
8692            // it needs to drop FLAG_OEM.
8693            if (locationIsOem(scanFile)) {
8694                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8695            } else {
8696                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8697            }
8698
8699            if (ps != null && !ps.codePath.equals(scanFile)) {
8700                // The path has changed from what was last scanned...  check the
8701                // version of the new path against what we have stored to determine
8702                // what to do.
8703                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8704                if (pkg.mVersionCode <= ps.versionCode) {
8705                    // The system package has been updated and the code path does not match
8706                    // Ignore entry. Skip it.
8707                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8708                            + " ignored: updated version " + ps.versionCode
8709                            + " better than this " + pkg.mVersionCode);
8710                    if (!updatedPkg.codePath.equals(scanFile)) {
8711                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8712                                + ps.name + " changing from " + updatedPkg.codePathString
8713                                + " to " + scanFile);
8714                        updatedPkg.codePath = scanFile;
8715                        updatedPkg.codePathString = scanFile.toString();
8716                        updatedPkg.resourcePath = scanFile;
8717                        updatedPkg.resourcePathString = scanFile.toString();
8718                    }
8719                    updatedPkg.pkg = pkg;
8720                    updatedPkg.versionCode = pkg.mVersionCode;
8721
8722                    // Update the disabled system child packages to point to the package too.
8723                    final int childCount = updatedPkg.childPackageNames != null
8724                            ? updatedPkg.childPackageNames.size() : 0;
8725                    for (int i = 0; i < childCount; i++) {
8726                        String childPackageName = updatedPkg.childPackageNames.get(i);
8727                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8728                                childPackageName);
8729                        if (updatedChildPkg != null) {
8730                            updatedChildPkg.pkg = pkg;
8731                            updatedChildPkg.versionCode = pkg.mVersionCode;
8732                        }
8733                    }
8734                } else {
8735                    // The current app on the system partition is better than
8736                    // what we have updated to on the data partition; switch
8737                    // back to the system partition version.
8738                    // At this point, its safely assumed that package installation for
8739                    // apps in system partition will go through. If not there won't be a working
8740                    // version of the app
8741                    // writer
8742                    synchronized (mPackages) {
8743                        // Just remove the loaded entries from package lists.
8744                        mPackages.remove(ps.name);
8745                    }
8746
8747                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8748                            + " reverting from " + ps.codePathString
8749                            + ": new version " + pkg.mVersionCode
8750                            + " better than installed " + ps.versionCode);
8751
8752                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8753                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8754                    synchronized (mInstallLock) {
8755                        args.cleanUpResourcesLI();
8756                    }
8757                    synchronized (mPackages) {
8758                        mSettings.enableSystemPackageLPw(ps.name);
8759                    }
8760                    isUpdatedPkgBetter = true;
8761                }
8762            }
8763        }
8764
8765        String resourcePath = null;
8766        String baseResourcePath = null;
8767        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8768            if (ps != null && ps.resourcePathString != null) {
8769                resourcePath = ps.resourcePathString;
8770                baseResourcePath = ps.resourcePathString;
8771            } else {
8772                // Should not happen at all. Just log an error.
8773                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8774            }
8775        } else {
8776            resourcePath = pkg.codePath;
8777            baseResourcePath = pkg.baseCodePath;
8778        }
8779
8780        // Set application objects path explicitly.
8781        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8782        pkg.setApplicationInfoCodePath(pkg.codePath);
8783        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8784        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8785        pkg.setApplicationInfoResourcePath(resourcePath);
8786        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8787        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8788
8789        // throw an exception if we have an update to a system application, but, it's not more
8790        // recent than the package we've already scanned
8791        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8792            // Set CPU Abis to application info.
8793            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8794                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8795                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8796            } else {
8797                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8798                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8799            }
8800
8801            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8802                    + scanFile + " ignored: updated version " + ps.versionCode
8803                    + " better than this " + pkg.mVersionCode);
8804        }
8805
8806        if (isUpdatedPkg) {
8807            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8808            // initially
8809            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8810
8811            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8812            // flag set initially
8813            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8814                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8815            }
8816
8817            // An updated OEM app will not have the PARSE_IS_OEM
8818            // flag set initially
8819            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8820                policyFlags |= PackageParser.PARSE_IS_OEM;
8821            }
8822        }
8823
8824        // Verify certificates against what was last scanned
8825        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8826
8827        /*
8828         * A new system app appeared, but we already had a non-system one of the
8829         * same name installed earlier.
8830         */
8831        boolean shouldHideSystemApp = false;
8832        if (!isUpdatedPkg && ps != null
8833                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8834            /*
8835             * Check to make sure the signatures match first. If they don't,
8836             * wipe the installed application and its data.
8837             */
8838            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8839                    != PackageManager.SIGNATURE_MATCH) {
8840                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8841                        + " signatures don't match existing userdata copy; removing");
8842                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8843                        "scanPackageInternalLI")) {
8844                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8845                }
8846                ps = null;
8847            } else {
8848                /*
8849                 * If the newly-added system app is an older version than the
8850                 * already installed version, hide it. It will be scanned later
8851                 * and re-added like an update.
8852                 */
8853                if (pkg.mVersionCode <= ps.versionCode) {
8854                    shouldHideSystemApp = true;
8855                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8856                            + " but new version " + pkg.mVersionCode + " better than installed "
8857                            + ps.versionCode + "; hiding system");
8858                } else {
8859                    /*
8860                     * The newly found system app is a newer version that the
8861                     * one previously installed. Simply remove the
8862                     * already-installed application and replace it with our own
8863                     * while keeping the application data.
8864                     */
8865                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8866                            + " reverting from " + ps.codePathString + ": new version "
8867                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8868                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8869                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8870                    synchronized (mInstallLock) {
8871                        args.cleanUpResourcesLI();
8872                    }
8873                }
8874            }
8875        }
8876
8877        // The apk is forward locked (not public) if its code and resources
8878        // are kept in different files. (except for app in either system or
8879        // vendor path).
8880        // TODO grab this value from PackageSettings
8881        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8882            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8883                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8884            }
8885        }
8886
8887        final int userId = ((user == null) ? 0 : user.getIdentifier());
8888        if (ps != null && ps.getInstantApp(userId)) {
8889            scanFlags |= SCAN_AS_INSTANT_APP;
8890        }
8891        if (ps != null && ps.getVirtulalPreload(userId)) {
8892            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8893        }
8894
8895        // Note that we invoke the following method only if we are about to unpack an application
8896        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8897                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8898
8899        /*
8900         * If the system app should be overridden by a previously installed
8901         * data, hide the system app now and let the /data/app scan pick it up
8902         * again.
8903         */
8904        if (shouldHideSystemApp) {
8905            synchronized (mPackages) {
8906                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8907            }
8908        }
8909
8910        return scannedPkg;
8911    }
8912
8913    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8914        // Derive the new package synthetic package name
8915        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8916                + pkg.staticSharedLibVersion);
8917    }
8918
8919    private static String fixProcessName(String defProcessName,
8920            String processName) {
8921        if (processName == null) {
8922            return defProcessName;
8923        }
8924        return processName;
8925    }
8926
8927    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8928            throws PackageManagerException {
8929        if (pkgSetting.signatures.mSignatures != null) {
8930            // Already existing package. Make sure signatures match
8931            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8932                    == PackageManager.SIGNATURE_MATCH;
8933            if (!match) {
8934                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8935                        == PackageManager.SIGNATURE_MATCH;
8936            }
8937            if (!match) {
8938                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8939                        == PackageManager.SIGNATURE_MATCH;
8940            }
8941            if (!match) {
8942                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8943                        + pkg.packageName + " signatures do not match the "
8944                        + "previously installed version; ignoring!");
8945            }
8946        }
8947
8948        // Check for shared user signatures
8949        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8950            // Already existing package. Make sure signatures match
8951            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8952                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8953            if (!match) {
8954                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8955                        == PackageManager.SIGNATURE_MATCH;
8956            }
8957            if (!match) {
8958                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8959                        == PackageManager.SIGNATURE_MATCH;
8960            }
8961            if (!match) {
8962                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8963                        "Package " + pkg.packageName
8964                        + " has no signatures that match those in shared user "
8965                        + pkgSetting.sharedUser.name + "; ignoring!");
8966            }
8967        }
8968    }
8969
8970    /**
8971     * Enforces that only the system UID or root's UID can call a method exposed
8972     * via Binder.
8973     *
8974     * @param message used as message if SecurityException is thrown
8975     * @throws SecurityException if the caller is not system or root
8976     */
8977    private static final void enforceSystemOrRoot(String message) {
8978        final int uid = Binder.getCallingUid();
8979        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8980            throw new SecurityException(message);
8981        }
8982    }
8983
8984    @Override
8985    public void performFstrimIfNeeded() {
8986        enforceSystemOrRoot("Only the system can request fstrim");
8987
8988        // Before everything else, see whether we need to fstrim.
8989        try {
8990            IStorageManager sm = PackageHelper.getStorageManager();
8991            if (sm != null) {
8992                boolean doTrim = false;
8993                final long interval = android.provider.Settings.Global.getLong(
8994                        mContext.getContentResolver(),
8995                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8996                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8997                if (interval > 0) {
8998                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8999                    if (timeSinceLast > interval) {
9000                        doTrim = true;
9001                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9002                                + "; running immediately");
9003                    }
9004                }
9005                if (doTrim) {
9006                    final boolean dexOptDialogShown;
9007                    synchronized (mPackages) {
9008                        dexOptDialogShown = mDexOptDialogShown;
9009                    }
9010                    if (!isFirstBoot() && dexOptDialogShown) {
9011                        try {
9012                            ActivityManager.getService().showBootMessage(
9013                                    mContext.getResources().getString(
9014                                            R.string.android_upgrading_fstrim), true);
9015                        } catch (RemoteException e) {
9016                        }
9017                    }
9018                    sm.runMaintenance();
9019                }
9020            } else {
9021                Slog.e(TAG, "storageManager service unavailable!");
9022            }
9023        } catch (RemoteException e) {
9024            // Can't happen; StorageManagerService is local
9025        }
9026    }
9027
9028    @Override
9029    public void updatePackagesIfNeeded() {
9030        enforceSystemOrRoot("Only the system can request package update");
9031
9032        // We need to re-extract after an OTA.
9033        boolean causeUpgrade = isUpgrade();
9034
9035        // First boot or factory reset.
9036        // Note: we also handle devices that are upgrading to N right now as if it is their
9037        //       first boot, as they do not have profile data.
9038        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9039
9040        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9041        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9042
9043        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9044            return;
9045        }
9046
9047        List<PackageParser.Package> pkgs;
9048        synchronized (mPackages) {
9049            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9050        }
9051
9052        final long startTime = System.nanoTime();
9053        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9054                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9055                    false /* bootComplete */);
9056
9057        final int elapsedTimeSeconds =
9058                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9059
9060        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9061        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9062        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9063        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9064        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9065    }
9066
9067    /*
9068     * Return the prebuilt profile path given a package base code path.
9069     */
9070    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9071        return pkg.baseCodePath + ".prof";
9072    }
9073
9074    /**
9075     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9076     * containing statistics about the invocation. The array consists of three elements,
9077     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9078     * and {@code numberOfPackagesFailed}.
9079     */
9080    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9081            final String compilerFilter, boolean bootComplete) {
9082
9083        int numberOfPackagesVisited = 0;
9084        int numberOfPackagesOptimized = 0;
9085        int numberOfPackagesSkipped = 0;
9086        int numberOfPackagesFailed = 0;
9087        final int numberOfPackagesToDexopt = pkgs.size();
9088
9089        for (PackageParser.Package pkg : pkgs) {
9090            numberOfPackagesVisited++;
9091
9092            boolean useProfileForDexopt = false;
9093
9094            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9095                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9096                // that are already compiled.
9097                File profileFile = new File(getPrebuildProfilePath(pkg));
9098                // Copy profile if it exists.
9099                if (profileFile.exists()) {
9100                    try {
9101                        // We could also do this lazily before calling dexopt in
9102                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9103                        // is that we don't have a good way to say "do this only once".
9104                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9105                                pkg.applicationInfo.uid, pkg.packageName)) {
9106                            Log.e(TAG, "Installer failed to copy system profile!");
9107                        } else {
9108                            // Disabled as this causes speed-profile compilation during first boot
9109                            // even if things are already compiled.
9110                            // useProfileForDexopt = true;
9111                        }
9112                    } catch (Exception e) {
9113                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9114                                e);
9115                    }
9116                } else {
9117                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9118                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9119                    // minimize the number off apps being speed-profile compiled during first boot.
9120                    // The other paths will not change the filter.
9121                    if (disabledPs != null && disabledPs.pkg.isStub) {
9122                        // The package is the stub one, remove the stub suffix to get the normal
9123                        // package and APK names.
9124                        String systemProfilePath =
9125                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9126                        File systemProfile = new File(systemProfilePath);
9127                        // Use the profile for compilation if there exists one for the same package
9128                        // in the system partition.
9129                        useProfileForDexopt = systemProfile.exists();
9130                    }
9131                }
9132            }
9133
9134            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9135                if (DEBUG_DEXOPT) {
9136                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9137                }
9138                numberOfPackagesSkipped++;
9139                continue;
9140            }
9141
9142            if (DEBUG_DEXOPT) {
9143                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9144                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9145            }
9146
9147            if (showDialog) {
9148                try {
9149                    ActivityManager.getService().showBootMessage(
9150                            mContext.getResources().getString(R.string.android_upgrading_apk,
9151                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9152                } catch (RemoteException e) {
9153                }
9154                synchronized (mPackages) {
9155                    mDexOptDialogShown = true;
9156                }
9157            }
9158
9159            String pkgCompilerFilter = compilerFilter;
9160            if (useProfileForDexopt) {
9161                // Use background dexopt mode to try and use the profile. Note that this does not
9162                // guarantee usage of the profile.
9163                pkgCompilerFilter =
9164                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9165                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9166            }
9167
9168            // checkProfiles is false to avoid merging profiles during boot which
9169            // might interfere with background compilation (b/28612421).
9170            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9171            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9172            // trade-off worth doing to save boot time work.
9173            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9174            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9175                    pkg.packageName,
9176                    pkgCompilerFilter,
9177                    dexoptFlags));
9178
9179            switch (primaryDexOptStaus) {
9180                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9181                    numberOfPackagesOptimized++;
9182                    break;
9183                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9184                    numberOfPackagesSkipped++;
9185                    break;
9186                case PackageDexOptimizer.DEX_OPT_FAILED:
9187                    numberOfPackagesFailed++;
9188                    break;
9189                default:
9190                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9191                    break;
9192            }
9193        }
9194
9195        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9196                numberOfPackagesFailed };
9197    }
9198
9199    @Override
9200    public void notifyPackageUse(String packageName, int reason) {
9201        synchronized (mPackages) {
9202            final int callingUid = Binder.getCallingUid();
9203            final int callingUserId = UserHandle.getUserId(callingUid);
9204            if (getInstantAppPackageName(callingUid) != null) {
9205                if (!isCallerSameApp(packageName, callingUid)) {
9206                    return;
9207                }
9208            } else {
9209                if (isInstantApp(packageName, callingUserId)) {
9210                    return;
9211                }
9212            }
9213            notifyPackageUseLocked(packageName, reason);
9214        }
9215    }
9216
9217    private void notifyPackageUseLocked(String packageName, int reason) {
9218        final PackageParser.Package p = mPackages.get(packageName);
9219        if (p == null) {
9220            return;
9221        }
9222        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9223    }
9224
9225    @Override
9226    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9227            List<String> classPaths, String loaderIsa) {
9228        int userId = UserHandle.getCallingUserId();
9229        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9230        if (ai == null) {
9231            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9232                + loadingPackageName + ", user=" + userId);
9233            return;
9234        }
9235        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9236    }
9237
9238    @Override
9239    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9240            IDexModuleRegisterCallback callback) {
9241        int userId = UserHandle.getCallingUserId();
9242        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9243        DexManager.RegisterDexModuleResult result;
9244        if (ai == null) {
9245            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9246                     " calling user. package=" + packageName + ", user=" + userId);
9247            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9248        } else {
9249            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9250        }
9251
9252        if (callback != null) {
9253            mHandler.post(() -> {
9254                try {
9255                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9256                } catch (RemoteException e) {
9257                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9258                }
9259            });
9260        }
9261    }
9262
9263    /**
9264     * Ask the package manager to perform a dex-opt with the given compiler filter.
9265     *
9266     * Note: exposed only for the shell command to allow moving packages explicitly to a
9267     *       definite state.
9268     */
9269    @Override
9270    public boolean performDexOptMode(String packageName,
9271            boolean checkProfiles, String targetCompilerFilter, boolean force,
9272            boolean bootComplete, String splitName) {
9273        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9274                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9275                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9276        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9277                splitName, flags));
9278    }
9279
9280    /**
9281     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9282     * secondary dex files belonging to the given package.
9283     *
9284     * Note: exposed only for the shell command to allow moving packages explicitly to a
9285     *       definite state.
9286     */
9287    @Override
9288    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9289            boolean force) {
9290        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9291                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9292                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9293                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9294        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9295    }
9296
9297    /*package*/ boolean performDexOpt(DexoptOptions options) {
9298        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9299            return false;
9300        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9301            return false;
9302        }
9303
9304        if (options.isDexoptOnlySecondaryDex()) {
9305            return mDexManager.dexoptSecondaryDex(options);
9306        } else {
9307            int dexoptStatus = performDexOptWithStatus(options);
9308            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9309        }
9310    }
9311
9312    /**
9313     * Perform dexopt on the given package and return one of following result:
9314     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9315     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9316     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9317     */
9318    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9319        return performDexOptTraced(options);
9320    }
9321
9322    private int performDexOptTraced(DexoptOptions options) {
9323        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9324        try {
9325            return performDexOptInternal(options);
9326        } finally {
9327            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9328        }
9329    }
9330
9331    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9332    // if the package can now be considered up to date for the given filter.
9333    private int performDexOptInternal(DexoptOptions options) {
9334        PackageParser.Package p;
9335        synchronized (mPackages) {
9336            p = mPackages.get(options.getPackageName());
9337            if (p == null) {
9338                // Package could not be found. Report failure.
9339                return PackageDexOptimizer.DEX_OPT_FAILED;
9340            }
9341            mPackageUsage.maybeWriteAsync(mPackages);
9342            mCompilerStats.maybeWriteAsync();
9343        }
9344        long callingId = Binder.clearCallingIdentity();
9345        try {
9346            synchronized (mInstallLock) {
9347                return performDexOptInternalWithDependenciesLI(p, options);
9348            }
9349        } finally {
9350            Binder.restoreCallingIdentity(callingId);
9351        }
9352    }
9353
9354    public ArraySet<String> getOptimizablePackages() {
9355        ArraySet<String> pkgs = new ArraySet<String>();
9356        synchronized (mPackages) {
9357            for (PackageParser.Package p : mPackages.values()) {
9358                if (PackageDexOptimizer.canOptimizePackage(p)) {
9359                    pkgs.add(p.packageName);
9360                }
9361            }
9362        }
9363        return pkgs;
9364    }
9365
9366    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9367            DexoptOptions options) {
9368        // Select the dex optimizer based on the force parameter.
9369        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9370        //       allocate an object here.
9371        PackageDexOptimizer pdo = options.isForce()
9372                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9373                : mPackageDexOptimizer;
9374
9375        // Dexopt all dependencies first. Note: we ignore the return value and march on
9376        // on errors.
9377        // Note that we are going to call performDexOpt on those libraries as many times as
9378        // they are referenced in packages. When we do a batch of performDexOpt (for example
9379        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9380        // and the first package that uses the library will dexopt it. The
9381        // others will see that the compiled code for the library is up to date.
9382        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9383        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9384        if (!deps.isEmpty()) {
9385            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9386                    options.getCompilerFilter(), options.getSplitName(),
9387                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9388            for (PackageParser.Package depPackage : deps) {
9389                // TODO: Analyze and investigate if we (should) profile libraries.
9390                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9391                        getOrCreateCompilerPackageStats(depPackage),
9392                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9393            }
9394        }
9395        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9396                getOrCreateCompilerPackageStats(p),
9397                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9398    }
9399
9400    /**
9401     * Reconcile the information we have about the secondary dex files belonging to
9402     * {@code packagName} and the actual dex files. For all dex files that were
9403     * deleted, update the internal records and delete the generated oat files.
9404     */
9405    @Override
9406    public void reconcileSecondaryDexFiles(String packageName) {
9407        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9408            return;
9409        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9410            return;
9411        }
9412        mDexManager.reconcileSecondaryDexFiles(packageName);
9413    }
9414
9415    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9416    // a reference there.
9417    /*package*/ DexManager getDexManager() {
9418        return mDexManager;
9419    }
9420
9421    /**
9422     * Execute the background dexopt job immediately.
9423     */
9424    @Override
9425    public boolean runBackgroundDexoptJob() {
9426        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9427            return false;
9428        }
9429        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9430    }
9431
9432    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9433        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9434                || p.usesStaticLibraries != null) {
9435            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9436            Set<String> collectedNames = new HashSet<>();
9437            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9438
9439            retValue.remove(p);
9440
9441            return retValue;
9442        } else {
9443            return Collections.emptyList();
9444        }
9445    }
9446
9447    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9448            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9449        if (!collectedNames.contains(p.packageName)) {
9450            collectedNames.add(p.packageName);
9451            collected.add(p);
9452
9453            if (p.usesLibraries != null) {
9454                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9455                        null, collected, collectedNames);
9456            }
9457            if (p.usesOptionalLibraries != null) {
9458                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9459                        null, collected, collectedNames);
9460            }
9461            if (p.usesStaticLibraries != null) {
9462                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9463                        p.usesStaticLibrariesVersions, collected, collectedNames);
9464            }
9465        }
9466    }
9467
9468    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9469            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9470        final int libNameCount = libs.size();
9471        for (int i = 0; i < libNameCount; i++) {
9472            String libName = libs.get(i);
9473            int version = (versions != null && versions.length == libNameCount)
9474                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9475            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9476            if (libPkg != null) {
9477                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9478            }
9479        }
9480    }
9481
9482    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9483        synchronized (mPackages) {
9484            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9485            if (libEntry != null) {
9486                return mPackages.get(libEntry.apk);
9487            }
9488            return null;
9489        }
9490    }
9491
9492    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9493        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9494        if (versionedLib == null) {
9495            return null;
9496        }
9497        return versionedLib.get(version);
9498    }
9499
9500    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9501        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9502                pkg.staticSharedLibName);
9503        if (versionedLib == null) {
9504            return null;
9505        }
9506        int previousLibVersion = -1;
9507        final int versionCount = versionedLib.size();
9508        for (int i = 0; i < versionCount; i++) {
9509            final int libVersion = versionedLib.keyAt(i);
9510            if (libVersion < pkg.staticSharedLibVersion) {
9511                previousLibVersion = Math.max(previousLibVersion, libVersion);
9512            }
9513        }
9514        if (previousLibVersion >= 0) {
9515            return versionedLib.get(previousLibVersion);
9516        }
9517        return null;
9518    }
9519
9520    public void shutdown() {
9521        mPackageUsage.writeNow(mPackages);
9522        mCompilerStats.writeNow();
9523        mDexManager.writePackageDexUsageNow();
9524    }
9525
9526    @Override
9527    public void dumpProfiles(String packageName) {
9528        PackageParser.Package pkg;
9529        synchronized (mPackages) {
9530            pkg = mPackages.get(packageName);
9531            if (pkg == null) {
9532                throw new IllegalArgumentException("Unknown package: " + packageName);
9533            }
9534        }
9535        /* Only the shell, root, or the app user should be able to dump profiles. */
9536        int callingUid = Binder.getCallingUid();
9537        if (callingUid != Process.SHELL_UID &&
9538            callingUid != Process.ROOT_UID &&
9539            callingUid != pkg.applicationInfo.uid) {
9540            throw new SecurityException("dumpProfiles");
9541        }
9542
9543        synchronized (mInstallLock) {
9544            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9545            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9546            try {
9547                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9548                String codePaths = TextUtils.join(";", allCodePaths);
9549                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9550            } catch (InstallerException e) {
9551                Slog.w(TAG, "Failed to dump profiles", e);
9552            }
9553            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9554        }
9555    }
9556
9557    @Override
9558    public void forceDexOpt(String packageName) {
9559        enforceSystemOrRoot("forceDexOpt");
9560
9561        PackageParser.Package pkg;
9562        synchronized (mPackages) {
9563            pkg = mPackages.get(packageName);
9564            if (pkg == null) {
9565                throw new IllegalArgumentException("Unknown package: " + packageName);
9566            }
9567        }
9568
9569        synchronized (mInstallLock) {
9570            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9571
9572            // Whoever is calling forceDexOpt wants a compiled package.
9573            // Don't use profiles since that may cause compilation to be skipped.
9574            final int res = performDexOptInternalWithDependenciesLI(
9575                    pkg,
9576                    new DexoptOptions(packageName,
9577                            getDefaultCompilerFilter(),
9578                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9579
9580            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9581            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9582                throw new IllegalStateException("Failed to dexopt: " + res);
9583            }
9584        }
9585    }
9586
9587    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9588        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9589            Slog.w(TAG, "Unable to update from " + oldPkg.name
9590                    + " to " + newPkg.packageName
9591                    + ": old package not in system partition");
9592            return false;
9593        } else if (mPackages.get(oldPkg.name) != null) {
9594            Slog.w(TAG, "Unable to update from " + oldPkg.name
9595                    + " to " + newPkg.packageName
9596                    + ": old package still exists");
9597            return false;
9598        }
9599        return true;
9600    }
9601
9602    void removeCodePathLI(File codePath) {
9603        if (codePath.isDirectory()) {
9604            try {
9605                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9606            } catch (InstallerException e) {
9607                Slog.w(TAG, "Failed to remove code path", e);
9608            }
9609        } else {
9610            codePath.delete();
9611        }
9612    }
9613
9614    private int[] resolveUserIds(int userId) {
9615        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9616    }
9617
9618    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9619        if (pkg == null) {
9620            Slog.wtf(TAG, "Package was null!", new Throwable());
9621            return;
9622        }
9623        clearAppDataLeafLIF(pkg, userId, flags);
9624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9625        for (int i = 0; i < childCount; i++) {
9626            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9627        }
9628    }
9629
9630    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9631        final PackageSetting ps;
9632        synchronized (mPackages) {
9633            ps = mSettings.mPackages.get(pkg.packageName);
9634        }
9635        for (int realUserId : resolveUserIds(userId)) {
9636            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9637            try {
9638                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9639                        ceDataInode);
9640            } catch (InstallerException e) {
9641                Slog.w(TAG, String.valueOf(e));
9642            }
9643        }
9644    }
9645
9646    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9647        if (pkg == null) {
9648            Slog.wtf(TAG, "Package was null!", new Throwable());
9649            return;
9650        }
9651        destroyAppDataLeafLIF(pkg, userId, flags);
9652        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9653        for (int i = 0; i < childCount; i++) {
9654            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9655        }
9656    }
9657
9658    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9659        final PackageSetting ps;
9660        synchronized (mPackages) {
9661            ps = mSettings.mPackages.get(pkg.packageName);
9662        }
9663        for (int realUserId : resolveUserIds(userId)) {
9664            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9665            try {
9666                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9667                        ceDataInode);
9668            } catch (InstallerException e) {
9669                Slog.w(TAG, String.valueOf(e));
9670            }
9671            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9672        }
9673    }
9674
9675    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9676        if (pkg == null) {
9677            Slog.wtf(TAG, "Package was null!", new Throwable());
9678            return;
9679        }
9680        destroyAppProfilesLeafLIF(pkg);
9681        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9682        for (int i = 0; i < childCount; i++) {
9683            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9684        }
9685    }
9686
9687    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9688        try {
9689            mInstaller.destroyAppProfiles(pkg.packageName);
9690        } catch (InstallerException e) {
9691            Slog.w(TAG, String.valueOf(e));
9692        }
9693    }
9694
9695    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9696        if (pkg == null) {
9697            Slog.wtf(TAG, "Package was null!", new Throwable());
9698            return;
9699        }
9700        clearAppProfilesLeafLIF(pkg);
9701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9702        for (int i = 0; i < childCount; i++) {
9703            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9704        }
9705    }
9706
9707    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9708        try {
9709            mInstaller.clearAppProfiles(pkg.packageName);
9710        } catch (InstallerException e) {
9711            Slog.w(TAG, String.valueOf(e));
9712        }
9713    }
9714
9715    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9716            long lastUpdateTime) {
9717        // Set parent install/update time
9718        PackageSetting ps = (PackageSetting) pkg.mExtras;
9719        if (ps != null) {
9720            ps.firstInstallTime = firstInstallTime;
9721            ps.lastUpdateTime = lastUpdateTime;
9722        }
9723        // Set children install/update time
9724        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9725        for (int i = 0; i < childCount; i++) {
9726            PackageParser.Package childPkg = pkg.childPackages.get(i);
9727            ps = (PackageSetting) childPkg.mExtras;
9728            if (ps != null) {
9729                ps.firstInstallTime = firstInstallTime;
9730                ps.lastUpdateTime = lastUpdateTime;
9731            }
9732        }
9733    }
9734
9735    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9736            PackageParser.Package changingLib) {
9737        if (file.path != null) {
9738            usesLibraryFiles.add(file.path);
9739            return;
9740        }
9741        PackageParser.Package p = mPackages.get(file.apk);
9742        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9743            // If we are doing this while in the middle of updating a library apk,
9744            // then we need to make sure to use that new apk for determining the
9745            // dependencies here.  (We haven't yet finished committing the new apk
9746            // to the package manager state.)
9747            if (p == null || p.packageName.equals(changingLib.packageName)) {
9748                p = changingLib;
9749            }
9750        }
9751        if (p != null) {
9752            usesLibraryFiles.addAll(p.getAllCodePaths());
9753            if (p.usesLibraryFiles != null) {
9754                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9755            }
9756        }
9757    }
9758
9759    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9760            PackageParser.Package changingLib) throws PackageManagerException {
9761        if (pkg == null) {
9762            return;
9763        }
9764        ArraySet<String> usesLibraryFiles = null;
9765        if (pkg.usesLibraries != null) {
9766            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9767                    null, null, pkg.packageName, changingLib, true,
9768                    pkg.applicationInfo.targetSdkVersion, null);
9769        }
9770        if (pkg.usesStaticLibraries != null) {
9771            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9772                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9773                    pkg.packageName, changingLib, true,
9774                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9775        }
9776        if (pkg.usesOptionalLibraries != null) {
9777            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9778                    null, null, pkg.packageName, changingLib, false,
9779                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9780        }
9781        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9782            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9783        } else {
9784            pkg.usesLibraryFiles = null;
9785        }
9786    }
9787
9788    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9789            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9790            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9791            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
9792            throws PackageManagerException {
9793        final int libCount = requestedLibraries.size();
9794        for (int i = 0; i < libCount; i++) {
9795            final String libName = requestedLibraries.get(i);
9796            final int libVersion = requiredVersions != null ? requiredVersions[i]
9797                    : SharedLibraryInfo.VERSION_UNDEFINED;
9798            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9799            if (libEntry == null) {
9800                if (required) {
9801                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9802                            "Package " + packageName + " requires unavailable shared library "
9803                                    + libName + "; failing!");
9804                } else if (DEBUG_SHARED_LIBRARIES) {
9805                    Slog.i(TAG, "Package " + packageName
9806                            + " desires unavailable shared library "
9807                            + libName + "; ignoring!");
9808                }
9809            } else {
9810                if (requiredVersions != null && requiredCertDigests != null) {
9811                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9812                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9813                            "Package " + packageName + " requires unavailable static shared"
9814                                    + " library " + libName + " version "
9815                                    + libEntry.info.getVersion() + "; failing!");
9816                    }
9817
9818                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9819                    if (libPkg == null) {
9820                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9821                                "Package " + packageName + " requires unavailable static shared"
9822                                        + " library; failing!");
9823                    }
9824
9825                    final String[] expectedCertDigests = requiredCertDigests[i];
9826                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9827                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9828                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9829                            : PackageUtils.computeSignaturesSha256Digests(
9830                                    new Signature[]{libPkg.mSignatures[0]});
9831
9832                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9833                    // target O we don't parse the "additional-certificate" tags similarly
9834                    // how we only consider all certs only for apps targeting O (see above).
9835                    // Therefore, the size check is safe to make.
9836                    if (expectedCertDigests.length != libCertDigests.length) {
9837                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9838                                "Package " + packageName + " requires differently signed" +
9839                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9840                    }
9841
9842                    // Use a predictable order as signature order may vary
9843                    Arrays.sort(libCertDigests);
9844                    Arrays.sort(expectedCertDigests);
9845
9846                    final int certCount = libCertDigests.length;
9847                    for (int j = 0; j < certCount; j++) {
9848                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9849                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9850                                    "Package " + packageName + " requires differently signed" +
9851                                            " static shared library; failing!");
9852                        }
9853                    }
9854                }
9855
9856                if (outUsedLibraries == null) {
9857                    outUsedLibraries = new ArraySet<>();
9858                }
9859                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9860            }
9861        }
9862        return outUsedLibraries;
9863    }
9864
9865    private static boolean hasString(List<String> list, List<String> which) {
9866        if (list == null) {
9867            return false;
9868        }
9869        for (int i=list.size()-1; i>=0; i--) {
9870            for (int j=which.size()-1; j>=0; j--) {
9871                if (which.get(j).equals(list.get(i))) {
9872                    return true;
9873                }
9874            }
9875        }
9876        return false;
9877    }
9878
9879    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9880            PackageParser.Package changingPkg) {
9881        ArrayList<PackageParser.Package> res = null;
9882        for (PackageParser.Package pkg : mPackages.values()) {
9883            if (changingPkg != null
9884                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9885                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9886                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9887                            changingPkg.staticSharedLibName)) {
9888                return null;
9889            }
9890            if (res == null) {
9891                res = new ArrayList<>();
9892            }
9893            res.add(pkg);
9894            try {
9895                updateSharedLibrariesLPr(pkg, changingPkg);
9896            } catch (PackageManagerException e) {
9897                // If a system app update or an app and a required lib missing we
9898                // delete the package and for updated system apps keep the data as
9899                // it is better for the user to reinstall than to be in an limbo
9900                // state. Also libs disappearing under an app should never happen
9901                // - just in case.
9902                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9903                    final int flags = pkg.isUpdatedSystemApp()
9904                            ? PackageManager.DELETE_KEEP_DATA : 0;
9905                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9906                            flags , null, true, null);
9907                }
9908                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9909            }
9910        }
9911        return res;
9912    }
9913
9914    /**
9915     * Derive the value of the {@code cpuAbiOverride} based on the provided
9916     * value and an optional stored value from the package settings.
9917     */
9918    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9919        String cpuAbiOverride = null;
9920
9921        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9922            cpuAbiOverride = null;
9923        } else if (abiOverride != null) {
9924            cpuAbiOverride = abiOverride;
9925        } else if (settings != null) {
9926            cpuAbiOverride = settings.cpuAbiOverrideString;
9927        }
9928
9929        return cpuAbiOverride;
9930    }
9931
9932    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9933            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9934                    throws PackageManagerException {
9935        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9936        // If the package has children and this is the first dive in the function
9937        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9938        // whether all packages (parent and children) would be successfully scanned
9939        // before the actual scan since scanning mutates internal state and we want
9940        // to atomically install the package and its children.
9941        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9942            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9943                scanFlags |= SCAN_CHECK_ONLY;
9944            }
9945        } else {
9946            scanFlags &= ~SCAN_CHECK_ONLY;
9947        }
9948
9949        final PackageParser.Package scannedPkg;
9950        try {
9951            // Scan the parent
9952            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9953            // Scan the children
9954            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9955            for (int i = 0; i < childCount; i++) {
9956                PackageParser.Package childPkg = pkg.childPackages.get(i);
9957                scanPackageLI(childPkg, policyFlags,
9958                        scanFlags, currentTime, user);
9959            }
9960        } finally {
9961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9962        }
9963
9964        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9965            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9966        }
9967
9968        return scannedPkg;
9969    }
9970
9971    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9972            int scanFlags, long currentTime, @Nullable UserHandle user)
9973                    throws PackageManagerException {
9974        boolean success = false;
9975        try {
9976            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9977                    currentTime, user);
9978            success = true;
9979            return res;
9980        } finally {
9981            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9982                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9983                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9984                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9985                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9986            }
9987        }
9988    }
9989
9990    /**
9991     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9992     */
9993    private static boolean apkHasCode(String fileName) {
9994        StrictJarFile jarFile = null;
9995        try {
9996            jarFile = new StrictJarFile(fileName,
9997                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9998            return jarFile.findEntry("classes.dex") != null;
9999        } catch (IOException ignore) {
10000        } finally {
10001            try {
10002                if (jarFile != null) {
10003                    jarFile.close();
10004                }
10005            } catch (IOException ignore) {}
10006        }
10007        return false;
10008    }
10009
10010    /**
10011     * Enforces code policy for the package. This ensures that if an APK has
10012     * declared hasCode="true" in its manifest that the APK actually contains
10013     * code.
10014     *
10015     * @throws PackageManagerException If bytecode could not be found when it should exist
10016     */
10017    private static void assertCodePolicy(PackageParser.Package pkg)
10018            throws PackageManagerException {
10019        final boolean shouldHaveCode =
10020                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10021        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10022            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10023                    "Package " + pkg.baseCodePath + " code is missing");
10024        }
10025
10026        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10027            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10028                final boolean splitShouldHaveCode =
10029                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10030                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10031                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10032                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10033                }
10034            }
10035        }
10036    }
10037
10038    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10039            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10040                    throws PackageManagerException {
10041        if (DEBUG_PACKAGE_SCANNING) {
10042            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10043                Log.d(TAG, "Scanning package " + pkg.packageName);
10044        }
10045
10046        applyPolicy(pkg, policyFlags);
10047
10048        assertPackageIsValid(pkg, policyFlags, scanFlags);
10049
10050        if (Build.IS_DEBUGGABLE &&
10051                pkg.isPrivilegedApp() &&
10052                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10053            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10054        }
10055
10056        // Initialize package source and resource directories
10057        final File scanFile = new File(pkg.codePath);
10058        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10059        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10060
10061        SharedUserSetting suid = null;
10062        PackageSetting pkgSetting = null;
10063
10064        // Getting the package setting may have a side-effect, so if we
10065        // are only checking if scan would succeed, stash a copy of the
10066        // old setting to restore at the end.
10067        PackageSetting nonMutatedPs = null;
10068
10069        // We keep references to the derived CPU Abis from settings in oder to reuse
10070        // them in the case where we're not upgrading or booting for the first time.
10071        String primaryCpuAbiFromSettings = null;
10072        String secondaryCpuAbiFromSettings = null;
10073
10074        // writer
10075        synchronized (mPackages) {
10076            if (pkg.mSharedUserId != null) {
10077                // SIDE EFFECTS; may potentially allocate a new shared user
10078                suid = mSettings.getSharedUserLPw(
10079                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10080                if (DEBUG_PACKAGE_SCANNING) {
10081                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10082                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10083                                + "): packages=" + suid.packages);
10084                }
10085            }
10086
10087            // Check if we are renaming from an original package name.
10088            PackageSetting origPackage = null;
10089            String realName = null;
10090            if (pkg.mOriginalPackages != null) {
10091                // This package may need to be renamed to a previously
10092                // installed name.  Let's check on that...
10093                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10094                if (pkg.mOriginalPackages.contains(renamed)) {
10095                    // This package had originally been installed as the
10096                    // original name, and we have already taken care of
10097                    // transitioning to the new one.  Just update the new
10098                    // one to continue using the old name.
10099                    realName = pkg.mRealPackage;
10100                    if (!pkg.packageName.equals(renamed)) {
10101                        // Callers into this function may have already taken
10102                        // care of renaming the package; only do it here if
10103                        // it is not already done.
10104                        pkg.setPackageName(renamed);
10105                    }
10106                } else {
10107                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10108                        if ((origPackage = mSettings.getPackageLPr(
10109                                pkg.mOriginalPackages.get(i))) != null) {
10110                            // We do have the package already installed under its
10111                            // original name...  should we use it?
10112                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10113                                // New package is not compatible with original.
10114                                origPackage = null;
10115                                continue;
10116                            } else if (origPackage.sharedUser != null) {
10117                                // Make sure uid is compatible between packages.
10118                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10119                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10120                                            + " to " + pkg.packageName + ": old uid "
10121                                            + origPackage.sharedUser.name
10122                                            + " differs from " + pkg.mSharedUserId);
10123                                    origPackage = null;
10124                                    continue;
10125                                }
10126                                // TODO: Add case when shared user id is added [b/28144775]
10127                            } else {
10128                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10129                                        + pkg.packageName + " to old name " + origPackage.name);
10130                            }
10131                            break;
10132                        }
10133                    }
10134                }
10135            }
10136
10137            if (mTransferedPackages.contains(pkg.packageName)) {
10138                Slog.w(TAG, "Package " + pkg.packageName
10139                        + " was transferred to another, but its .apk remains");
10140            }
10141
10142            // See comments in nonMutatedPs declaration
10143            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10144                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10145                if (foundPs != null) {
10146                    nonMutatedPs = new PackageSetting(foundPs);
10147                }
10148            }
10149
10150            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10151                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10152                if (foundPs != null) {
10153                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10154                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10155                }
10156            }
10157
10158            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10159            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10160                PackageManagerService.reportSettingsProblem(Log.WARN,
10161                        "Package " + pkg.packageName + " shared user changed from "
10162                                + (pkgSetting.sharedUser != null
10163                                        ? pkgSetting.sharedUser.name : "<nothing>")
10164                                + " to "
10165                                + (suid != null ? suid.name : "<nothing>")
10166                                + "; replacing with new");
10167                pkgSetting = null;
10168            }
10169            final PackageSetting oldPkgSetting =
10170                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10171            final PackageSetting disabledPkgSetting =
10172                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10173
10174            String[] usesStaticLibraries = null;
10175            if (pkg.usesStaticLibraries != null) {
10176                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10177                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10178            }
10179
10180            if (pkgSetting == null) {
10181                final String parentPackageName = (pkg.parentPackage != null)
10182                        ? pkg.parentPackage.packageName : null;
10183                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10184                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10185                // REMOVE SharedUserSetting from method; update in a separate call
10186                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10187                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10188                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10189                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10190                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10191                        true /*allowInstall*/, instantApp, virtualPreload,
10192                        parentPackageName, pkg.getChildPackageNames(),
10193                        UserManagerService.getInstance(), usesStaticLibraries,
10194                        pkg.usesStaticLibrariesVersions);
10195                // SIDE EFFECTS; updates system state; move elsewhere
10196                if (origPackage != null) {
10197                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10198                }
10199                mSettings.addUserToSettingLPw(pkgSetting);
10200            } else {
10201                // REMOVE SharedUserSetting from method; update in a separate call.
10202                //
10203                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10204                // secondaryCpuAbi are not known at this point so we always update them
10205                // to null here, only to reset them at a later point.
10206                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10207                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10208                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10209                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10210                        UserManagerService.getInstance(), usesStaticLibraries,
10211                        pkg.usesStaticLibrariesVersions);
10212            }
10213            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10214            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10215
10216            // SIDE EFFECTS; modifies system state; move elsewhere
10217            if (pkgSetting.origPackage != null) {
10218                // If we are first transitioning from an original package,
10219                // fix up the new package's name now.  We need to do this after
10220                // looking up the package under its new name, so getPackageLP
10221                // can take care of fiddling things correctly.
10222                pkg.setPackageName(origPackage.name);
10223
10224                // File a report about this.
10225                String msg = "New package " + pkgSetting.realName
10226                        + " renamed to replace old package " + pkgSetting.name;
10227                reportSettingsProblem(Log.WARN, msg);
10228
10229                // Make a note of it.
10230                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10231                    mTransferedPackages.add(origPackage.name);
10232                }
10233
10234                // No longer need to retain this.
10235                pkgSetting.origPackage = null;
10236            }
10237
10238            // SIDE EFFECTS; modifies system state; move elsewhere
10239            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10240                // Make a note of it.
10241                mTransferedPackages.add(pkg.packageName);
10242            }
10243
10244            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10245                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10246            }
10247
10248            if ((scanFlags & SCAN_BOOTING) == 0
10249                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10250                // Check all shared libraries and map to their actual file path.
10251                // We only do this here for apps not on a system dir, because those
10252                // are the only ones that can fail an install due to this.  We
10253                // will take care of the system apps by updating all of their
10254                // library paths after the scan is done. Also during the initial
10255                // scan don't update any libs as we do this wholesale after all
10256                // apps are scanned to avoid dependency based scanning.
10257                updateSharedLibrariesLPr(pkg, null);
10258            }
10259
10260            if (mFoundPolicyFile) {
10261                SELinuxMMAC.assignSeInfoValue(pkg);
10262            }
10263            pkg.applicationInfo.uid = pkgSetting.appId;
10264            pkg.mExtras = pkgSetting;
10265
10266
10267            // Static shared libs have same package with different versions where
10268            // we internally use a synthetic package name to allow multiple versions
10269            // of the same package, therefore we need to compare signatures against
10270            // the package setting for the latest library version.
10271            PackageSetting signatureCheckPs = pkgSetting;
10272            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10273                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10274                if (libraryEntry != null) {
10275                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10276                }
10277            }
10278
10279            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10280                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10281                    // We just determined the app is signed correctly, so bring
10282                    // over the latest parsed certs.
10283                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10284                } else {
10285                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10286                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10287                                "Package " + pkg.packageName + " upgrade keys do not match the "
10288                                + "previously installed version");
10289                    } else {
10290                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10291                        String msg = "System package " + pkg.packageName
10292                                + " signature changed; retaining data.";
10293                        reportSettingsProblem(Log.WARN, msg);
10294                    }
10295                }
10296            } else {
10297                try {
10298                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10299                    verifySignaturesLP(signatureCheckPs, pkg);
10300                    // We just determined the app is signed correctly, so bring
10301                    // over the latest parsed certs.
10302                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10303                } catch (PackageManagerException e) {
10304                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10305                        throw e;
10306                    }
10307                    // The signature has changed, but this package is in the system
10308                    // image...  let's recover!
10309                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10310                    // However...  if this package is part of a shared user, but it
10311                    // doesn't match the signature of the shared user, let's fail.
10312                    // What this means is that you can't change the signatures
10313                    // associated with an overall shared user, which doesn't seem all
10314                    // that unreasonable.
10315                    if (signatureCheckPs.sharedUser != null) {
10316                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10317                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10318                            throw new PackageManagerException(
10319                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10320                                    "Signature mismatch for shared user: "
10321                                            + pkgSetting.sharedUser);
10322                        }
10323                    }
10324                    // File a report about this.
10325                    String msg = "System package " + pkg.packageName
10326                            + " signature changed; retaining data.";
10327                    reportSettingsProblem(Log.WARN, msg);
10328                }
10329            }
10330
10331            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10332                // This package wants to adopt ownership of permissions from
10333                // another package.
10334                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10335                    final String origName = pkg.mAdoptPermissions.get(i);
10336                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10337                    if (orig != null) {
10338                        if (verifyPackageUpdateLPr(orig, pkg)) {
10339                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10340                                    + pkg.packageName);
10341                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10342                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10343                        }
10344                    }
10345                }
10346            }
10347        }
10348
10349        pkg.applicationInfo.processName = fixProcessName(
10350                pkg.applicationInfo.packageName,
10351                pkg.applicationInfo.processName);
10352
10353        if (pkg != mPlatformPackage) {
10354            // Get all of our default paths setup
10355            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10356        }
10357
10358        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10359
10360        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10361            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10362                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10363                final boolean extractNativeLibs = !pkg.isLibrary();
10364                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10365                        mAppLib32InstallDir);
10366                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10367
10368                // Some system apps still use directory structure for native libraries
10369                // in which case we might end up not detecting abi solely based on apk
10370                // structure. Try to detect abi based on directory structure.
10371                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10372                        pkg.applicationInfo.primaryCpuAbi == null) {
10373                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10374                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10375                }
10376            } else {
10377                // This is not a first boot or an upgrade, don't bother deriving the
10378                // ABI during the scan. Instead, trust the value that was stored in the
10379                // package setting.
10380                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10381                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10382
10383                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10384
10385                if (DEBUG_ABI_SELECTION) {
10386                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10387                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10388                        pkg.applicationInfo.secondaryCpuAbi);
10389                }
10390            }
10391        } else {
10392            if ((scanFlags & SCAN_MOVE) != 0) {
10393                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10394                // but we already have this packages package info in the PackageSetting. We just
10395                // use that and derive the native library path based on the new codepath.
10396                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10397                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10398            }
10399
10400            // Set native library paths again. For moves, the path will be updated based on the
10401            // ABIs we've determined above. For non-moves, the path will be updated based on the
10402            // ABIs we determined during compilation, but the path will depend on the final
10403            // package path (after the rename away from the stage path).
10404            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10405        }
10406
10407        // This is a special case for the "system" package, where the ABI is
10408        // dictated by the zygote configuration (and init.rc). We should keep track
10409        // of this ABI so that we can deal with "normal" applications that run under
10410        // the same UID correctly.
10411        if (mPlatformPackage == pkg) {
10412            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10413                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10414        }
10415
10416        // If there's a mismatch between the abi-override in the package setting
10417        // and the abiOverride specified for the install. Warn about this because we
10418        // would've already compiled the app without taking the package setting into
10419        // account.
10420        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10421            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10422                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10423                        " for package " + pkg.packageName);
10424            }
10425        }
10426
10427        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10428        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10429        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10430
10431        // Copy the derived override back to the parsed package, so that we can
10432        // update the package settings accordingly.
10433        pkg.cpuAbiOverride = cpuAbiOverride;
10434
10435        if (DEBUG_ABI_SELECTION) {
10436            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10437                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10438                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10439        }
10440
10441        // Push the derived path down into PackageSettings so we know what to
10442        // clean up at uninstall time.
10443        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10444
10445        if (DEBUG_ABI_SELECTION) {
10446            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10447                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10448                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10449        }
10450
10451        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10452        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10453            // We don't do this here during boot because we can do it all
10454            // at once after scanning all existing packages.
10455            //
10456            // We also do this *before* we perform dexopt on this package, so that
10457            // we can avoid redundant dexopts, and also to make sure we've got the
10458            // code and package path correct.
10459            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10460        }
10461
10462        if (mFactoryTest && pkg.requestedPermissions.contains(
10463                android.Manifest.permission.FACTORY_TEST)) {
10464            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10465        }
10466
10467        if (isSystemApp(pkg)) {
10468            pkgSetting.isOrphaned = true;
10469        }
10470
10471        // Take care of first install / last update times.
10472        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10473        if (currentTime != 0) {
10474            if (pkgSetting.firstInstallTime == 0) {
10475                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10476            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10477                pkgSetting.lastUpdateTime = currentTime;
10478            }
10479        } else if (pkgSetting.firstInstallTime == 0) {
10480            // We need *something*.  Take time time stamp of the file.
10481            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10482        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10483            if (scanFileTime != pkgSetting.timeStamp) {
10484                // A package on the system image has changed; consider this
10485                // to be an update.
10486                pkgSetting.lastUpdateTime = scanFileTime;
10487            }
10488        }
10489        pkgSetting.setTimeStamp(scanFileTime);
10490
10491        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10492            if (nonMutatedPs != null) {
10493                synchronized (mPackages) {
10494                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10495                }
10496            }
10497        } else {
10498            final int userId = user == null ? 0 : user.getIdentifier();
10499            // Modify state for the given package setting
10500            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10501                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10502            if (pkgSetting.getInstantApp(userId)) {
10503                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10504            }
10505        }
10506        return pkg;
10507    }
10508
10509    /**
10510     * Applies policy to the parsed package based upon the given policy flags.
10511     * Ensures the package is in a good state.
10512     * <p>
10513     * Implementation detail: This method must NOT have any side effect. It would
10514     * ideally be static, but, it requires locks to read system state.
10515     */
10516    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10517        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10518            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10519            if (pkg.applicationInfo.isDirectBootAware()) {
10520                // we're direct boot aware; set for all components
10521                for (PackageParser.Service s : pkg.services) {
10522                    s.info.encryptionAware = s.info.directBootAware = true;
10523                }
10524                for (PackageParser.Provider p : pkg.providers) {
10525                    p.info.encryptionAware = p.info.directBootAware = true;
10526                }
10527                for (PackageParser.Activity a : pkg.activities) {
10528                    a.info.encryptionAware = a.info.directBootAware = true;
10529                }
10530                for (PackageParser.Activity r : pkg.receivers) {
10531                    r.info.encryptionAware = r.info.directBootAware = true;
10532                }
10533            }
10534            if (compressedFileExists(pkg.codePath)) {
10535                pkg.isStub = true;
10536            }
10537        } else {
10538            // Only allow system apps to be flagged as core apps.
10539            pkg.coreApp = false;
10540            // clear flags not applicable to regular apps
10541            pkg.applicationInfo.privateFlags &=
10542                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10543            pkg.applicationInfo.privateFlags &=
10544                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10545        }
10546        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10547
10548        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10549            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10550        }
10551
10552        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10553            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10554        }
10555
10556        if (!isSystemApp(pkg)) {
10557            // Only system apps can use these features.
10558            pkg.mOriginalPackages = null;
10559            pkg.mRealPackage = null;
10560            pkg.mAdoptPermissions = null;
10561        }
10562    }
10563
10564    /**
10565     * Asserts the parsed package is valid according to the given policy. If the
10566     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10567     * <p>
10568     * Implementation detail: This method must NOT have any side effects. It would
10569     * ideally be static, but, it requires locks to read system state.
10570     *
10571     * @throws PackageManagerException If the package fails any of the validation checks
10572     */
10573    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10574            throws PackageManagerException {
10575        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10576            assertCodePolicy(pkg);
10577        }
10578
10579        if (pkg.applicationInfo.getCodePath() == null ||
10580                pkg.applicationInfo.getResourcePath() == null) {
10581            // Bail out. The resource and code paths haven't been set.
10582            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10583                    "Code and resource paths haven't been set correctly");
10584        }
10585
10586        // Make sure we're not adding any bogus keyset info
10587        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10588        ksms.assertScannedPackageValid(pkg);
10589
10590        synchronized (mPackages) {
10591            // The special "android" package can only be defined once
10592            if (pkg.packageName.equals("android")) {
10593                if (mAndroidApplication != null) {
10594                    Slog.w(TAG, "*************************************************");
10595                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10596                    Slog.w(TAG, " codePath=" + pkg.codePath);
10597                    Slog.w(TAG, "*************************************************");
10598                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10599                            "Core android package being redefined.  Skipping.");
10600                }
10601            }
10602
10603            // A package name must be unique; don't allow duplicates
10604            if (mPackages.containsKey(pkg.packageName)) {
10605                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10606                        "Application package " + pkg.packageName
10607                        + " already installed.  Skipping duplicate.");
10608            }
10609
10610            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10611                // Static libs have a synthetic package name containing the version
10612                // but we still want the base name to be unique.
10613                if (mPackages.containsKey(pkg.manifestPackageName)) {
10614                    throw new PackageManagerException(
10615                            "Duplicate static shared lib provider package");
10616                }
10617
10618                // Static shared libraries should have at least O target SDK
10619                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10620                    throw new PackageManagerException(
10621                            "Packages declaring static-shared libs must target O SDK or higher");
10622                }
10623
10624                // Package declaring static a shared lib cannot be instant apps
10625                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10626                    throw new PackageManagerException(
10627                            "Packages declaring static-shared libs cannot be instant apps");
10628                }
10629
10630                // Package declaring static a shared lib cannot be renamed since the package
10631                // name is synthetic and apps can't code around package manager internals.
10632                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10633                    throw new PackageManagerException(
10634                            "Packages declaring static-shared libs cannot be renamed");
10635                }
10636
10637                // Package declaring static a shared lib cannot declare child packages
10638                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10639                    throw new PackageManagerException(
10640                            "Packages declaring static-shared libs cannot have child packages");
10641                }
10642
10643                // Package declaring static a shared lib cannot declare dynamic libs
10644                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10645                    throw new PackageManagerException(
10646                            "Packages declaring static-shared libs cannot declare dynamic libs");
10647                }
10648
10649                // Package declaring static a shared lib cannot declare shared users
10650                if (pkg.mSharedUserId != null) {
10651                    throw new PackageManagerException(
10652                            "Packages declaring static-shared libs cannot declare shared users");
10653                }
10654
10655                // Static shared libs cannot declare activities
10656                if (!pkg.activities.isEmpty()) {
10657                    throw new PackageManagerException(
10658                            "Static shared libs cannot declare activities");
10659                }
10660
10661                // Static shared libs cannot declare services
10662                if (!pkg.services.isEmpty()) {
10663                    throw new PackageManagerException(
10664                            "Static shared libs cannot declare services");
10665                }
10666
10667                // Static shared libs cannot declare providers
10668                if (!pkg.providers.isEmpty()) {
10669                    throw new PackageManagerException(
10670                            "Static shared libs cannot declare content providers");
10671                }
10672
10673                // Static shared libs cannot declare receivers
10674                if (!pkg.receivers.isEmpty()) {
10675                    throw new PackageManagerException(
10676                            "Static shared libs cannot declare broadcast receivers");
10677                }
10678
10679                // Static shared libs cannot declare permission groups
10680                if (!pkg.permissionGroups.isEmpty()) {
10681                    throw new PackageManagerException(
10682                            "Static shared libs cannot declare permission groups");
10683                }
10684
10685                // Static shared libs cannot declare permissions
10686                if (!pkg.permissions.isEmpty()) {
10687                    throw new PackageManagerException(
10688                            "Static shared libs cannot declare permissions");
10689                }
10690
10691                // Static shared libs cannot declare protected broadcasts
10692                if (pkg.protectedBroadcasts != null) {
10693                    throw new PackageManagerException(
10694                            "Static shared libs cannot declare protected broadcasts");
10695                }
10696
10697                // Static shared libs cannot be overlay targets
10698                if (pkg.mOverlayTarget != null) {
10699                    throw new PackageManagerException(
10700                            "Static shared libs cannot be overlay targets");
10701                }
10702
10703                // The version codes must be ordered as lib versions
10704                int minVersionCode = Integer.MIN_VALUE;
10705                int maxVersionCode = Integer.MAX_VALUE;
10706
10707                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10708                        pkg.staticSharedLibName);
10709                if (versionedLib != null) {
10710                    final int versionCount = versionedLib.size();
10711                    for (int i = 0; i < versionCount; i++) {
10712                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10713                        final int libVersionCode = libInfo.getDeclaringPackage()
10714                                .getVersionCode();
10715                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10716                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10717                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10718                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10719                        } else {
10720                            minVersionCode = maxVersionCode = libVersionCode;
10721                            break;
10722                        }
10723                    }
10724                }
10725                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10726                    throw new PackageManagerException("Static shared"
10727                            + " lib version codes must be ordered as lib versions");
10728                }
10729            }
10730
10731            // Only privileged apps and updated privileged apps can add child packages.
10732            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10733                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10734                    throw new PackageManagerException("Only privileged apps can add child "
10735                            + "packages. Ignoring package " + pkg.packageName);
10736                }
10737                final int childCount = pkg.childPackages.size();
10738                for (int i = 0; i < childCount; i++) {
10739                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10740                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10741                            childPkg.packageName)) {
10742                        throw new PackageManagerException("Can't override child of "
10743                                + "another disabled app. Ignoring package " + pkg.packageName);
10744                    }
10745                }
10746            }
10747
10748            // If we're only installing presumed-existing packages, require that the
10749            // scanned APK is both already known and at the path previously established
10750            // for it.  Previously unknown packages we pick up normally, but if we have an
10751            // a priori expectation about this package's install presence, enforce it.
10752            // With a singular exception for new system packages. When an OTA contains
10753            // a new system package, we allow the codepath to change from a system location
10754            // to the user-installed location. If we don't allow this change, any newer,
10755            // user-installed version of the application will be ignored.
10756            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10757                if (mExpectingBetter.containsKey(pkg.packageName)) {
10758                    logCriticalInfo(Log.WARN,
10759                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10760                } else {
10761                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10762                    if (known != null) {
10763                        if (DEBUG_PACKAGE_SCANNING) {
10764                            Log.d(TAG, "Examining " + pkg.codePath
10765                                    + " and requiring known paths " + known.codePathString
10766                                    + " & " + known.resourcePathString);
10767                        }
10768                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10769                                || !pkg.applicationInfo.getResourcePath().equals(
10770                                        known.resourcePathString)) {
10771                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10772                                    "Application package " + pkg.packageName
10773                                    + " found at " + pkg.applicationInfo.getCodePath()
10774                                    + " but expected at " + known.codePathString
10775                                    + "; ignoring.");
10776                        }
10777                    } else {
10778                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10779                                "Application package " + pkg.packageName
10780                                + " not found; ignoring.");
10781                    }
10782                }
10783            }
10784
10785            // Verify that this new package doesn't have any content providers
10786            // that conflict with existing packages.  Only do this if the
10787            // package isn't already installed, since we don't want to break
10788            // things that are installed.
10789            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10790                final int N = pkg.providers.size();
10791                int i;
10792                for (i=0; i<N; i++) {
10793                    PackageParser.Provider p = pkg.providers.get(i);
10794                    if (p.info.authority != null) {
10795                        String names[] = p.info.authority.split(";");
10796                        for (int j = 0; j < names.length; j++) {
10797                            if (mProvidersByAuthority.containsKey(names[j])) {
10798                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10799                                final String otherPackageName =
10800                                        ((other != null && other.getComponentName() != null) ?
10801                                                other.getComponentName().getPackageName() : "?");
10802                                throw new PackageManagerException(
10803                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10804                                        "Can't install because provider name " + names[j]
10805                                                + " (in package " + pkg.applicationInfo.packageName
10806                                                + ") is already used by " + otherPackageName);
10807                            }
10808                        }
10809                    }
10810                }
10811            }
10812        }
10813    }
10814
10815    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10816            int type, String declaringPackageName, int declaringVersionCode) {
10817        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10818        if (versionedLib == null) {
10819            versionedLib = new SparseArray<>();
10820            mSharedLibraries.put(name, versionedLib);
10821            if (type == SharedLibraryInfo.TYPE_STATIC) {
10822                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10823            }
10824        } else if (versionedLib.indexOfKey(version) >= 0) {
10825            return false;
10826        }
10827        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10828                version, type, declaringPackageName, declaringVersionCode);
10829        versionedLib.put(version, libEntry);
10830        return true;
10831    }
10832
10833    private boolean removeSharedLibraryLPw(String name, int version) {
10834        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10835        if (versionedLib == null) {
10836            return false;
10837        }
10838        final int libIdx = versionedLib.indexOfKey(version);
10839        if (libIdx < 0) {
10840            return false;
10841        }
10842        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10843        versionedLib.remove(version);
10844        if (versionedLib.size() <= 0) {
10845            mSharedLibraries.remove(name);
10846            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10847                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10848                        .getPackageName());
10849            }
10850        }
10851        return true;
10852    }
10853
10854    /**
10855     * Adds a scanned package to the system. When this method is finished, the package will
10856     * be available for query, resolution, etc...
10857     */
10858    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10859            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10860        final String pkgName = pkg.packageName;
10861        if (mCustomResolverComponentName != null &&
10862                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10863            setUpCustomResolverActivity(pkg);
10864        }
10865
10866        if (pkg.packageName.equals("android")) {
10867            synchronized (mPackages) {
10868                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10869                    // Set up information for our fall-back user intent resolution activity.
10870                    mPlatformPackage = pkg;
10871                    pkg.mVersionCode = mSdkVersion;
10872                    mAndroidApplication = pkg.applicationInfo;
10873                    if (!mResolverReplaced) {
10874                        mResolveActivity.applicationInfo = mAndroidApplication;
10875                        mResolveActivity.name = ResolverActivity.class.getName();
10876                        mResolveActivity.packageName = mAndroidApplication.packageName;
10877                        mResolveActivity.processName = "system:ui";
10878                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10879                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10880                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10881                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10882                        mResolveActivity.exported = true;
10883                        mResolveActivity.enabled = true;
10884                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10885                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10886                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10887                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10888                                | ActivityInfo.CONFIG_ORIENTATION
10889                                | ActivityInfo.CONFIG_KEYBOARD
10890                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10891                        mResolveInfo.activityInfo = mResolveActivity;
10892                        mResolveInfo.priority = 0;
10893                        mResolveInfo.preferredOrder = 0;
10894                        mResolveInfo.match = 0;
10895                        mResolveComponentName = new ComponentName(
10896                                mAndroidApplication.packageName, mResolveActivity.name);
10897                    }
10898                }
10899            }
10900        }
10901
10902        ArrayList<PackageParser.Package> clientLibPkgs = null;
10903        // writer
10904        synchronized (mPackages) {
10905            boolean hasStaticSharedLibs = false;
10906
10907            // Any app can add new static shared libraries
10908            if (pkg.staticSharedLibName != null) {
10909                // Static shared libs don't allow renaming as they have synthetic package
10910                // names to allow install of multiple versions, so use name from manifest.
10911                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10912                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10913                        pkg.manifestPackageName, pkg.mVersionCode)) {
10914                    hasStaticSharedLibs = true;
10915                } else {
10916                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10917                                + pkg.staticSharedLibName + " already exists; skipping");
10918                }
10919                // Static shared libs cannot be updated once installed since they
10920                // use synthetic package name which includes the version code, so
10921                // not need to update other packages's shared lib dependencies.
10922            }
10923
10924            if (!hasStaticSharedLibs
10925                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10926                // Only system apps can add new dynamic shared libraries.
10927                if (pkg.libraryNames != null) {
10928                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10929                        String name = pkg.libraryNames.get(i);
10930                        boolean allowed = false;
10931                        if (pkg.isUpdatedSystemApp()) {
10932                            // New library entries can only be added through the
10933                            // system image.  This is important to get rid of a lot
10934                            // of nasty edge cases: for example if we allowed a non-
10935                            // system update of the app to add a library, then uninstalling
10936                            // the update would make the library go away, and assumptions
10937                            // we made such as through app install filtering would now
10938                            // have allowed apps on the device which aren't compatible
10939                            // with it.  Better to just have the restriction here, be
10940                            // conservative, and create many fewer cases that can negatively
10941                            // impact the user experience.
10942                            final PackageSetting sysPs = mSettings
10943                                    .getDisabledSystemPkgLPr(pkg.packageName);
10944                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10945                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10946                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10947                                        allowed = true;
10948                                        break;
10949                                    }
10950                                }
10951                            }
10952                        } else {
10953                            allowed = true;
10954                        }
10955                        if (allowed) {
10956                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10957                                    SharedLibraryInfo.VERSION_UNDEFINED,
10958                                    SharedLibraryInfo.TYPE_DYNAMIC,
10959                                    pkg.packageName, pkg.mVersionCode)) {
10960                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10961                                        + name + " already exists; skipping");
10962                            }
10963                        } else {
10964                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10965                                    + name + " that is not declared on system image; skipping");
10966                        }
10967                    }
10968
10969                    if ((scanFlags & SCAN_BOOTING) == 0) {
10970                        // If we are not booting, we need to update any applications
10971                        // that are clients of our shared library.  If we are booting,
10972                        // this will all be done once the scan is complete.
10973                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10974                    }
10975                }
10976            }
10977        }
10978
10979        if ((scanFlags & SCAN_BOOTING) != 0) {
10980            // No apps can run during boot scan, so they don't need to be frozen
10981        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10982            // Caller asked to not kill app, so it's probably not frozen
10983        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10984            // Caller asked us to ignore frozen check for some reason; they
10985            // probably didn't know the package name
10986        } else {
10987            // We're doing major surgery on this package, so it better be frozen
10988            // right now to keep it from launching
10989            checkPackageFrozen(pkgName);
10990        }
10991
10992        // Also need to kill any apps that are dependent on the library.
10993        if (clientLibPkgs != null) {
10994            for (int i=0; i<clientLibPkgs.size(); i++) {
10995                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10996                killApplication(clientPkg.applicationInfo.packageName,
10997                        clientPkg.applicationInfo.uid, "update lib");
10998            }
10999        }
11000
11001        // writer
11002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11003
11004        synchronized (mPackages) {
11005            // We don't expect installation to fail beyond this point
11006
11007            // Add the new setting to mSettings
11008            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11009            // Add the new setting to mPackages
11010            mPackages.put(pkg.applicationInfo.packageName, pkg);
11011            // Make sure we don't accidentally delete its data.
11012            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11013            while (iter.hasNext()) {
11014                PackageCleanItem item = iter.next();
11015                if (pkgName.equals(item.packageName)) {
11016                    iter.remove();
11017                }
11018            }
11019
11020            // Add the package's KeySets to the global KeySetManagerService
11021            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11022            ksms.addScannedPackageLPw(pkg);
11023
11024            int N = pkg.providers.size();
11025            StringBuilder r = null;
11026            int i;
11027            for (i=0; i<N; i++) {
11028                PackageParser.Provider p = pkg.providers.get(i);
11029                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11030                        p.info.processName);
11031                mProviders.addProvider(p);
11032                p.syncable = p.info.isSyncable;
11033                if (p.info.authority != null) {
11034                    String names[] = p.info.authority.split(";");
11035                    p.info.authority = null;
11036                    for (int j = 0; j < names.length; j++) {
11037                        if (j == 1 && p.syncable) {
11038                            // We only want the first authority for a provider to possibly be
11039                            // syncable, so if we already added this provider using a different
11040                            // authority clear the syncable flag. We copy the provider before
11041                            // changing it because the mProviders object contains a reference
11042                            // to a provider that we don't want to change.
11043                            // Only do this for the second authority since the resulting provider
11044                            // object can be the same for all future authorities for this provider.
11045                            p = new PackageParser.Provider(p);
11046                            p.syncable = false;
11047                        }
11048                        if (!mProvidersByAuthority.containsKey(names[j])) {
11049                            mProvidersByAuthority.put(names[j], p);
11050                            if (p.info.authority == null) {
11051                                p.info.authority = names[j];
11052                            } else {
11053                                p.info.authority = p.info.authority + ";" + names[j];
11054                            }
11055                            if (DEBUG_PACKAGE_SCANNING) {
11056                                if (chatty)
11057                                    Log.d(TAG, "Registered content provider: " + names[j]
11058                                            + ", className = " + p.info.name + ", isSyncable = "
11059                                            + p.info.isSyncable);
11060                            }
11061                        } else {
11062                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11063                            Slog.w(TAG, "Skipping provider name " + names[j] +
11064                                    " (in package " + pkg.applicationInfo.packageName +
11065                                    "): name already used by "
11066                                    + ((other != null && other.getComponentName() != null)
11067                                            ? other.getComponentName().getPackageName() : "?"));
11068                        }
11069                    }
11070                }
11071                if (chatty) {
11072                    if (r == null) {
11073                        r = new StringBuilder(256);
11074                    } else {
11075                        r.append(' ');
11076                    }
11077                    r.append(p.info.name);
11078                }
11079            }
11080            if (r != null) {
11081                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11082            }
11083
11084            N = pkg.services.size();
11085            r = null;
11086            for (i=0; i<N; i++) {
11087                PackageParser.Service s = pkg.services.get(i);
11088                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11089                        s.info.processName);
11090                mServices.addService(s);
11091                if (chatty) {
11092                    if (r == null) {
11093                        r = new StringBuilder(256);
11094                    } else {
11095                        r.append(' ');
11096                    }
11097                    r.append(s.info.name);
11098                }
11099            }
11100            if (r != null) {
11101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11102            }
11103
11104            N = pkg.receivers.size();
11105            r = null;
11106            for (i=0; i<N; i++) {
11107                PackageParser.Activity a = pkg.receivers.get(i);
11108                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11109                        a.info.processName);
11110                mReceivers.addActivity(a, "receiver");
11111                if (chatty) {
11112                    if (r == null) {
11113                        r = new StringBuilder(256);
11114                    } else {
11115                        r.append(' ');
11116                    }
11117                    r.append(a.info.name);
11118                }
11119            }
11120            if (r != null) {
11121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11122            }
11123
11124            N = pkg.activities.size();
11125            r = null;
11126            for (i=0; i<N; i++) {
11127                PackageParser.Activity a = pkg.activities.get(i);
11128                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11129                        a.info.processName);
11130                mActivities.addActivity(a, "activity");
11131                if (chatty) {
11132                    if (r == null) {
11133                        r = new StringBuilder(256);
11134                    } else {
11135                        r.append(' ');
11136                    }
11137                    r.append(a.info.name);
11138                }
11139            }
11140            if (r != null) {
11141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11142            }
11143
11144            N = pkg.permissionGroups.size();
11145            r = null;
11146            for (i=0; i<N; i++) {
11147                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11148                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11149                final String curPackageName = cur == null ? null : cur.info.packageName;
11150                // Dont allow ephemeral apps to define new permission groups.
11151                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11152                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11153                            + pg.info.packageName
11154                            + " ignored: instant apps cannot define new permission groups.");
11155                    continue;
11156                }
11157                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11158                if (cur == null || isPackageUpdate) {
11159                    mPermissionGroups.put(pg.info.name, pg);
11160                    if (chatty) {
11161                        if (r == null) {
11162                            r = new StringBuilder(256);
11163                        } else {
11164                            r.append(' ');
11165                        }
11166                        if (isPackageUpdate) {
11167                            r.append("UPD:");
11168                        }
11169                        r.append(pg.info.name);
11170                    }
11171                } else {
11172                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11173                            + pg.info.packageName + " ignored: original from "
11174                            + cur.info.packageName);
11175                    if (chatty) {
11176                        if (r == null) {
11177                            r = new StringBuilder(256);
11178                        } else {
11179                            r.append(' ');
11180                        }
11181                        r.append("DUP:");
11182                        r.append(pg.info.name);
11183                    }
11184                }
11185            }
11186            if (r != null) {
11187                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11188            }
11189
11190            N = pkg.permissions.size();
11191            r = null;
11192            for (i=0; i<N; i++) {
11193                PackageParser.Permission p = pkg.permissions.get(i);
11194
11195                // Dont allow ephemeral apps to define new permissions.
11196                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11197                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11198                            + p.info.packageName
11199                            + " ignored: instant apps cannot define new permissions.");
11200                    continue;
11201                }
11202
11203                // Assume by default that we did not install this permission into the system.
11204                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11205
11206                // Now that permission groups have a special meaning, we ignore permission
11207                // groups for legacy apps to prevent unexpected behavior. In particular,
11208                // permissions for one app being granted to someone just because they happen
11209                // to be in a group defined by another app (before this had no implications).
11210                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11211                    p.group = mPermissionGroups.get(p.info.group);
11212                    // Warn for a permission in an unknown group.
11213                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11214                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11215                                + p.info.packageName + " in an unknown group " + p.info.group);
11216                    }
11217                }
11218
11219                // TODO Move to PermissionManager once mPermissionTrees moves there.
11220//                        p.tree ? mSettings.mPermissionTrees
11221//                                : mSettings.mPermissions;
11222//                final BasePermission bp = BasePermission.createOrUpdate(
11223//                        permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees, chatty);
11224//                permissionMap.put(p.info.name, bp);
11225                if (p.tree) {
11226                    final ArrayMap<String, BasePermission> permissionMap =
11227                            mSettings.mPermissionTrees;
11228                    final BasePermission bp = BasePermission.createOrUpdate(
11229                            permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees,
11230                            chatty);
11231                    permissionMap.put(p.info.name, bp);
11232                } else {
11233                    final BasePermission bp = BasePermission.createOrUpdate(
11234                            (BasePermission) mPermissionManager.getPermissionTEMP(p.info.name),
11235                            p, pkg, mSettings.mPermissionTrees, chatty);
11236                    mPermissionManager.putPermissionTEMP(p.info.name, bp);
11237                }
11238            }
11239
11240            N = pkg.instrumentation.size();
11241            r = null;
11242            for (i=0; i<N; i++) {
11243                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11244                a.info.packageName = pkg.applicationInfo.packageName;
11245                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11246                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11247                a.info.splitNames = pkg.splitNames;
11248                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11249                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11250                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11251                a.info.dataDir = pkg.applicationInfo.dataDir;
11252                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11253                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11254                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11255                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11256                mInstrumentation.put(a.getComponentName(), a);
11257                if (chatty) {
11258                    if (r == null) {
11259                        r = new StringBuilder(256);
11260                    } else {
11261                        r.append(' ');
11262                    }
11263                    r.append(a.info.name);
11264                }
11265            }
11266            if (r != null) {
11267                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11268            }
11269
11270            if (pkg.protectedBroadcasts != null) {
11271                N = pkg.protectedBroadcasts.size();
11272                synchronized (mProtectedBroadcasts) {
11273                    for (i = 0; i < N; i++) {
11274                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11275                    }
11276                }
11277            }
11278        }
11279
11280        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11281    }
11282
11283    /**
11284     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11285     * is derived purely on the basis of the contents of {@code scanFile} and
11286     * {@code cpuAbiOverride}.
11287     *
11288     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11289     */
11290    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11291                                 String cpuAbiOverride, boolean extractLibs,
11292                                 File appLib32InstallDir)
11293            throws PackageManagerException {
11294        // Give ourselves some initial paths; we'll come back for another
11295        // pass once we've determined ABI below.
11296        setNativeLibraryPaths(pkg, appLib32InstallDir);
11297
11298        // We would never need to extract libs for forward-locked and external packages,
11299        // since the container service will do it for us. We shouldn't attempt to
11300        // extract libs from system app when it was not updated.
11301        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11302                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11303            extractLibs = false;
11304        }
11305
11306        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11307        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11308
11309        NativeLibraryHelper.Handle handle = null;
11310        try {
11311            handle = NativeLibraryHelper.Handle.create(pkg);
11312            // TODO(multiArch): This can be null for apps that didn't go through the
11313            // usual installation process. We can calculate it again, like we
11314            // do during install time.
11315            //
11316            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11317            // unnecessary.
11318            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11319
11320            // Null out the abis so that they can be recalculated.
11321            pkg.applicationInfo.primaryCpuAbi = null;
11322            pkg.applicationInfo.secondaryCpuAbi = null;
11323            if (isMultiArch(pkg.applicationInfo)) {
11324                // Warn if we've set an abiOverride for multi-lib packages..
11325                // By definition, we need to copy both 32 and 64 bit libraries for
11326                // such packages.
11327                if (pkg.cpuAbiOverride != null
11328                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11329                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11330                }
11331
11332                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11333                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11334                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11335                    if (extractLibs) {
11336                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11337                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11338                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11339                                useIsaSpecificSubdirs);
11340                    } else {
11341                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11342                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11343                    }
11344                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11345                }
11346
11347                // Shared library native code should be in the APK zip aligned
11348                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11349                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11350                            "Shared library native lib extraction not supported");
11351                }
11352
11353                maybeThrowExceptionForMultiArchCopy(
11354                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11355
11356                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11357                    if (extractLibs) {
11358                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11359                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11360                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11361                                useIsaSpecificSubdirs);
11362                    } else {
11363                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11364                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11365                    }
11366                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11367                }
11368
11369                maybeThrowExceptionForMultiArchCopy(
11370                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11371
11372                if (abi64 >= 0) {
11373                    // Shared library native libs should be in the APK zip aligned
11374                    if (extractLibs && pkg.isLibrary()) {
11375                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11376                                "Shared library native lib extraction not supported");
11377                    }
11378                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11379                }
11380
11381                if (abi32 >= 0) {
11382                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11383                    if (abi64 >= 0) {
11384                        if (pkg.use32bitAbi) {
11385                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11386                            pkg.applicationInfo.primaryCpuAbi = abi;
11387                        } else {
11388                            pkg.applicationInfo.secondaryCpuAbi = abi;
11389                        }
11390                    } else {
11391                        pkg.applicationInfo.primaryCpuAbi = abi;
11392                    }
11393                }
11394            } else {
11395                String[] abiList = (cpuAbiOverride != null) ?
11396                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11397
11398                // Enable gross and lame hacks for apps that are built with old
11399                // SDK tools. We must scan their APKs for renderscript bitcode and
11400                // not launch them if it's present. Don't bother checking on devices
11401                // that don't have 64 bit support.
11402                boolean needsRenderScriptOverride = false;
11403                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11404                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11405                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11406                    needsRenderScriptOverride = true;
11407                }
11408
11409                final int copyRet;
11410                if (extractLibs) {
11411                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11412                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11413                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11414                } else {
11415                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11416                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11417                }
11418                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11419
11420                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11421                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11422                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11423                }
11424
11425                if (copyRet >= 0) {
11426                    // Shared libraries that have native libs must be multi-architecture
11427                    if (pkg.isLibrary()) {
11428                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11429                                "Shared library with native libs must be multiarch");
11430                    }
11431                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11432                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11433                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11434                } else if (needsRenderScriptOverride) {
11435                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11436                }
11437            }
11438        } catch (IOException ioe) {
11439            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11440        } finally {
11441            IoUtils.closeQuietly(handle);
11442        }
11443
11444        // Now that we've calculated the ABIs and determined if it's an internal app,
11445        // we will go ahead and populate the nativeLibraryPath.
11446        setNativeLibraryPaths(pkg, appLib32InstallDir);
11447    }
11448
11449    /**
11450     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11451     * i.e, so that all packages can be run inside a single process if required.
11452     *
11453     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11454     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11455     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11456     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11457     * updating a package that belongs to a shared user.
11458     *
11459     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11460     * adds unnecessary complexity.
11461     */
11462    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11463            PackageParser.Package scannedPackage) {
11464        String requiredInstructionSet = null;
11465        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11466            requiredInstructionSet = VMRuntime.getInstructionSet(
11467                     scannedPackage.applicationInfo.primaryCpuAbi);
11468        }
11469
11470        PackageSetting requirer = null;
11471        for (PackageSetting ps : packagesForUser) {
11472            // If packagesForUser contains scannedPackage, we skip it. This will happen
11473            // when scannedPackage is an update of an existing package. Without this check,
11474            // we will never be able to change the ABI of any package belonging to a shared
11475            // user, even if it's compatible with other packages.
11476            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11477                if (ps.primaryCpuAbiString == null) {
11478                    continue;
11479                }
11480
11481                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11482                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11483                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11484                    // this but there's not much we can do.
11485                    String errorMessage = "Instruction set mismatch, "
11486                            + ((requirer == null) ? "[caller]" : requirer)
11487                            + " requires " + requiredInstructionSet + " whereas " + ps
11488                            + " requires " + instructionSet;
11489                    Slog.w(TAG, errorMessage);
11490                }
11491
11492                if (requiredInstructionSet == null) {
11493                    requiredInstructionSet = instructionSet;
11494                    requirer = ps;
11495                }
11496            }
11497        }
11498
11499        if (requiredInstructionSet != null) {
11500            String adjustedAbi;
11501            if (requirer != null) {
11502                // requirer != null implies that either scannedPackage was null or that scannedPackage
11503                // did not require an ABI, in which case we have to adjust scannedPackage to match
11504                // the ABI of the set (which is the same as requirer's ABI)
11505                adjustedAbi = requirer.primaryCpuAbiString;
11506                if (scannedPackage != null) {
11507                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11508                }
11509            } else {
11510                // requirer == null implies that we're updating all ABIs in the set to
11511                // match scannedPackage.
11512                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11513            }
11514
11515            for (PackageSetting ps : packagesForUser) {
11516                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11517                    if (ps.primaryCpuAbiString != null) {
11518                        continue;
11519                    }
11520
11521                    ps.primaryCpuAbiString = adjustedAbi;
11522                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11523                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11524                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11525                        if (DEBUG_ABI_SELECTION) {
11526                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11527                                    + " (requirer="
11528                                    + (requirer != null ? requirer.pkg : "null")
11529                                    + ", scannedPackage="
11530                                    + (scannedPackage != null ? scannedPackage : "null")
11531                                    + ")");
11532                        }
11533                        try {
11534                            mInstaller.rmdex(ps.codePathString,
11535                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11536                        } catch (InstallerException ignored) {
11537                        }
11538                    }
11539                }
11540            }
11541        }
11542    }
11543
11544    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11545        synchronized (mPackages) {
11546            mResolverReplaced = true;
11547            // Set up information for custom user intent resolution activity.
11548            mResolveActivity.applicationInfo = pkg.applicationInfo;
11549            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11550            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11551            mResolveActivity.processName = pkg.applicationInfo.packageName;
11552            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11553            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11554                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11555            mResolveActivity.theme = 0;
11556            mResolveActivity.exported = true;
11557            mResolveActivity.enabled = true;
11558            mResolveInfo.activityInfo = mResolveActivity;
11559            mResolveInfo.priority = 0;
11560            mResolveInfo.preferredOrder = 0;
11561            mResolveInfo.match = 0;
11562            mResolveComponentName = mCustomResolverComponentName;
11563            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11564                    mResolveComponentName);
11565        }
11566    }
11567
11568    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11569        if (installerActivity == null) {
11570            if (DEBUG_EPHEMERAL) {
11571                Slog.d(TAG, "Clear ephemeral installer activity");
11572            }
11573            mInstantAppInstallerActivity = null;
11574            return;
11575        }
11576
11577        if (DEBUG_EPHEMERAL) {
11578            Slog.d(TAG, "Set ephemeral installer activity: "
11579                    + installerActivity.getComponentName());
11580        }
11581        // Set up information for ephemeral installer activity
11582        mInstantAppInstallerActivity = installerActivity;
11583        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11584                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11585        mInstantAppInstallerActivity.exported = true;
11586        mInstantAppInstallerActivity.enabled = true;
11587        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11588        mInstantAppInstallerInfo.priority = 0;
11589        mInstantAppInstallerInfo.preferredOrder = 1;
11590        mInstantAppInstallerInfo.isDefault = true;
11591        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11592                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11593    }
11594
11595    private static String calculateBundledApkRoot(final String codePathString) {
11596        final File codePath = new File(codePathString);
11597        final File codeRoot;
11598        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11599            codeRoot = Environment.getRootDirectory();
11600        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11601            codeRoot = Environment.getOemDirectory();
11602        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11603            codeRoot = Environment.getVendorDirectory();
11604        } else {
11605            // Unrecognized code path; take its top real segment as the apk root:
11606            // e.g. /something/app/blah.apk => /something
11607            try {
11608                File f = codePath.getCanonicalFile();
11609                File parent = f.getParentFile();    // non-null because codePath is a file
11610                File tmp;
11611                while ((tmp = parent.getParentFile()) != null) {
11612                    f = parent;
11613                    parent = tmp;
11614                }
11615                codeRoot = f;
11616                Slog.w(TAG, "Unrecognized code path "
11617                        + codePath + " - using " + codeRoot);
11618            } catch (IOException e) {
11619                // Can't canonicalize the code path -- shenanigans?
11620                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11621                return Environment.getRootDirectory().getPath();
11622            }
11623        }
11624        return codeRoot.getPath();
11625    }
11626
11627    /**
11628     * Derive and set the location of native libraries for the given package,
11629     * which varies depending on where and how the package was installed.
11630     */
11631    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11632        final ApplicationInfo info = pkg.applicationInfo;
11633        final String codePath = pkg.codePath;
11634        final File codeFile = new File(codePath);
11635        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11636        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11637
11638        info.nativeLibraryRootDir = null;
11639        info.nativeLibraryRootRequiresIsa = false;
11640        info.nativeLibraryDir = null;
11641        info.secondaryNativeLibraryDir = null;
11642
11643        if (isApkFile(codeFile)) {
11644            // Monolithic install
11645            if (bundledApp) {
11646                // If "/system/lib64/apkname" exists, assume that is the per-package
11647                // native library directory to use; otherwise use "/system/lib/apkname".
11648                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11649                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11650                        getPrimaryInstructionSet(info));
11651
11652                // This is a bundled system app so choose the path based on the ABI.
11653                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11654                // is just the default path.
11655                final String apkName = deriveCodePathName(codePath);
11656                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11657                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11658                        apkName).getAbsolutePath();
11659
11660                if (info.secondaryCpuAbi != null) {
11661                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11662                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11663                            secondaryLibDir, apkName).getAbsolutePath();
11664                }
11665            } else if (asecApp) {
11666                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11667                        .getAbsolutePath();
11668            } else {
11669                final String apkName = deriveCodePathName(codePath);
11670                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11671                        .getAbsolutePath();
11672            }
11673
11674            info.nativeLibraryRootRequiresIsa = false;
11675            info.nativeLibraryDir = info.nativeLibraryRootDir;
11676        } else {
11677            // Cluster install
11678            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11679            info.nativeLibraryRootRequiresIsa = true;
11680
11681            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11682                    getPrimaryInstructionSet(info)).getAbsolutePath();
11683
11684            if (info.secondaryCpuAbi != null) {
11685                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11686                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11687            }
11688        }
11689    }
11690
11691    /**
11692     * Calculate the abis and roots for a bundled app. These can uniquely
11693     * be determined from the contents of the system partition, i.e whether
11694     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11695     * of this information, and instead assume that the system was built
11696     * sensibly.
11697     */
11698    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11699                                           PackageSetting pkgSetting) {
11700        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11701
11702        // If "/system/lib64/apkname" exists, assume that is the per-package
11703        // native library directory to use; otherwise use "/system/lib/apkname".
11704        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11705        setBundledAppAbi(pkg, apkRoot, apkName);
11706        // pkgSetting might be null during rescan following uninstall of updates
11707        // to a bundled app, so accommodate that possibility.  The settings in
11708        // that case will be established later from the parsed package.
11709        //
11710        // If the settings aren't null, sync them up with what we've just derived.
11711        // note that apkRoot isn't stored in the package settings.
11712        if (pkgSetting != null) {
11713            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11714            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11715        }
11716    }
11717
11718    /**
11719     * Deduces the ABI of a bundled app and sets the relevant fields on the
11720     * parsed pkg object.
11721     *
11722     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11723     *        under which system libraries are installed.
11724     * @param apkName the name of the installed package.
11725     */
11726    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11727        final File codeFile = new File(pkg.codePath);
11728
11729        final boolean has64BitLibs;
11730        final boolean has32BitLibs;
11731        if (isApkFile(codeFile)) {
11732            // Monolithic install
11733            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11734            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11735        } else {
11736            // Cluster install
11737            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11738            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11739                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11740                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11741                has64BitLibs = (new File(rootDir, isa)).exists();
11742            } else {
11743                has64BitLibs = false;
11744            }
11745            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11746                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11747                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11748                has32BitLibs = (new File(rootDir, isa)).exists();
11749            } else {
11750                has32BitLibs = false;
11751            }
11752        }
11753
11754        if (has64BitLibs && !has32BitLibs) {
11755            // The package has 64 bit libs, but not 32 bit libs. Its primary
11756            // ABI should be 64 bit. We can safely assume here that the bundled
11757            // native libraries correspond to the most preferred ABI in the list.
11758
11759            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11760            pkg.applicationInfo.secondaryCpuAbi = null;
11761        } else if (has32BitLibs && !has64BitLibs) {
11762            // The package has 32 bit libs but not 64 bit libs. Its primary
11763            // ABI should be 32 bit.
11764
11765            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11766            pkg.applicationInfo.secondaryCpuAbi = null;
11767        } else if (has32BitLibs && has64BitLibs) {
11768            // The application has both 64 and 32 bit bundled libraries. We check
11769            // here that the app declares multiArch support, and warn if it doesn't.
11770            //
11771            // We will be lenient here and record both ABIs. The primary will be the
11772            // ABI that's higher on the list, i.e, a device that's configured to prefer
11773            // 64 bit apps will see a 64 bit primary ABI,
11774
11775            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11776                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11777            }
11778
11779            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11780                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11781                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11782            } else {
11783                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11784                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11785            }
11786        } else {
11787            pkg.applicationInfo.primaryCpuAbi = null;
11788            pkg.applicationInfo.secondaryCpuAbi = null;
11789        }
11790    }
11791
11792    private void killApplication(String pkgName, int appId, String reason) {
11793        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11794    }
11795
11796    private void killApplication(String pkgName, int appId, int userId, String reason) {
11797        // Request the ActivityManager to kill the process(only for existing packages)
11798        // so that we do not end up in a confused state while the user is still using the older
11799        // version of the application while the new one gets installed.
11800        final long token = Binder.clearCallingIdentity();
11801        try {
11802            IActivityManager am = ActivityManager.getService();
11803            if (am != null) {
11804                try {
11805                    am.killApplication(pkgName, appId, userId, reason);
11806                } catch (RemoteException e) {
11807                }
11808            }
11809        } finally {
11810            Binder.restoreCallingIdentity(token);
11811        }
11812    }
11813
11814    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11815        // Remove the parent package setting
11816        PackageSetting ps = (PackageSetting) pkg.mExtras;
11817        if (ps != null) {
11818            removePackageLI(ps, chatty);
11819        }
11820        // Remove the child package setting
11821        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11822        for (int i = 0; i < childCount; i++) {
11823            PackageParser.Package childPkg = pkg.childPackages.get(i);
11824            ps = (PackageSetting) childPkg.mExtras;
11825            if (ps != null) {
11826                removePackageLI(ps, chatty);
11827            }
11828        }
11829    }
11830
11831    void removePackageLI(PackageSetting ps, boolean chatty) {
11832        if (DEBUG_INSTALL) {
11833            if (chatty)
11834                Log.d(TAG, "Removing package " + ps.name);
11835        }
11836
11837        // writer
11838        synchronized (mPackages) {
11839            mPackages.remove(ps.name);
11840            final PackageParser.Package pkg = ps.pkg;
11841            if (pkg != null) {
11842                cleanPackageDataStructuresLILPw(pkg, chatty);
11843            }
11844        }
11845    }
11846
11847    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11848        if (DEBUG_INSTALL) {
11849            if (chatty)
11850                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11851        }
11852
11853        // writer
11854        synchronized (mPackages) {
11855            // Remove the parent package
11856            mPackages.remove(pkg.applicationInfo.packageName);
11857            cleanPackageDataStructuresLILPw(pkg, chatty);
11858
11859            // Remove the child packages
11860            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11861            for (int i = 0; i < childCount; i++) {
11862                PackageParser.Package childPkg = pkg.childPackages.get(i);
11863                mPackages.remove(childPkg.applicationInfo.packageName);
11864                cleanPackageDataStructuresLILPw(childPkg, chatty);
11865            }
11866        }
11867    }
11868
11869    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11870        int N = pkg.providers.size();
11871        StringBuilder r = null;
11872        int i;
11873        for (i=0; i<N; i++) {
11874            PackageParser.Provider p = pkg.providers.get(i);
11875            mProviders.removeProvider(p);
11876            if (p.info.authority == null) {
11877
11878                /* There was another ContentProvider with this authority when
11879                 * this app was installed so this authority is null,
11880                 * Ignore it as we don't have to unregister the provider.
11881                 */
11882                continue;
11883            }
11884            String names[] = p.info.authority.split(";");
11885            for (int j = 0; j < names.length; j++) {
11886                if (mProvidersByAuthority.get(names[j]) == p) {
11887                    mProvidersByAuthority.remove(names[j]);
11888                    if (DEBUG_REMOVE) {
11889                        if (chatty)
11890                            Log.d(TAG, "Unregistered content provider: " + names[j]
11891                                    + ", className = " + p.info.name + ", isSyncable = "
11892                                    + p.info.isSyncable);
11893                    }
11894                }
11895            }
11896            if (DEBUG_REMOVE && chatty) {
11897                if (r == null) {
11898                    r = new StringBuilder(256);
11899                } else {
11900                    r.append(' ');
11901                }
11902                r.append(p.info.name);
11903            }
11904        }
11905        if (r != null) {
11906            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11907        }
11908
11909        N = pkg.services.size();
11910        r = null;
11911        for (i=0; i<N; i++) {
11912            PackageParser.Service s = pkg.services.get(i);
11913            mServices.removeService(s);
11914            if (chatty) {
11915                if (r == null) {
11916                    r = new StringBuilder(256);
11917                } else {
11918                    r.append(' ');
11919                }
11920                r.append(s.info.name);
11921            }
11922        }
11923        if (r != null) {
11924            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11925        }
11926
11927        N = pkg.receivers.size();
11928        r = null;
11929        for (i=0; i<N; i++) {
11930            PackageParser.Activity a = pkg.receivers.get(i);
11931            mReceivers.removeActivity(a, "receiver");
11932            if (DEBUG_REMOVE && chatty) {
11933                if (r == null) {
11934                    r = new StringBuilder(256);
11935                } else {
11936                    r.append(' ');
11937                }
11938                r.append(a.info.name);
11939            }
11940        }
11941        if (r != null) {
11942            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11943        }
11944
11945        N = pkg.activities.size();
11946        r = null;
11947        for (i=0; i<N; i++) {
11948            PackageParser.Activity a = pkg.activities.get(i);
11949            mActivities.removeActivity(a, "activity");
11950            if (DEBUG_REMOVE && chatty) {
11951                if (r == null) {
11952                    r = new StringBuilder(256);
11953                } else {
11954                    r.append(' ');
11955                }
11956                r.append(a.info.name);
11957            }
11958        }
11959        if (r != null) {
11960            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11961        }
11962
11963        N = pkg.permissions.size();
11964        r = null;
11965        for (i=0; i<N; i++) {
11966            PackageParser.Permission p = pkg.permissions.get(i);
11967            BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(p.info.name);
11968            if (bp == null) {
11969                bp = mSettings.mPermissionTrees.get(p.info.name);
11970            }
11971            if (bp != null && bp.isPermission(p)) {
11972                bp.setPermission(null);
11973                if (DEBUG_REMOVE && chatty) {
11974                    if (r == null) {
11975                        r = new StringBuilder(256);
11976                    } else {
11977                        r.append(' ');
11978                    }
11979                    r.append(p.info.name);
11980                }
11981            }
11982            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11983                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11984                if (appOpPkgs != null) {
11985                    appOpPkgs.remove(pkg.packageName);
11986                }
11987            }
11988        }
11989        if (r != null) {
11990            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11991        }
11992
11993        N = pkg.requestedPermissions.size();
11994        r = null;
11995        for (i=0; i<N; i++) {
11996            String perm = pkg.requestedPermissions.get(i);
11997            if (mPermissionManager.isPermissionAppOp(perm)) {
11998                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11999                if (appOpPkgs != null) {
12000                    appOpPkgs.remove(pkg.packageName);
12001                    if (appOpPkgs.isEmpty()) {
12002                        mAppOpPermissionPackages.remove(perm);
12003                    }
12004                }
12005            }
12006        }
12007        if (r != null) {
12008            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12009        }
12010
12011        N = pkg.instrumentation.size();
12012        r = null;
12013        for (i=0; i<N; i++) {
12014            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12015            mInstrumentation.remove(a.getComponentName());
12016            if (DEBUG_REMOVE && chatty) {
12017                if (r == null) {
12018                    r = new StringBuilder(256);
12019                } else {
12020                    r.append(' ');
12021                }
12022                r.append(a.info.name);
12023            }
12024        }
12025        if (r != null) {
12026            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12027        }
12028
12029        r = null;
12030        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12031            // Only system apps can hold shared libraries.
12032            if (pkg.libraryNames != null) {
12033                for (i = 0; i < pkg.libraryNames.size(); i++) {
12034                    String name = pkg.libraryNames.get(i);
12035                    if (removeSharedLibraryLPw(name, 0)) {
12036                        if (DEBUG_REMOVE && chatty) {
12037                            if (r == null) {
12038                                r = new StringBuilder(256);
12039                            } else {
12040                                r.append(' ');
12041                            }
12042                            r.append(name);
12043                        }
12044                    }
12045                }
12046            }
12047        }
12048
12049        r = null;
12050
12051        // Any package can hold static shared libraries.
12052        if (pkg.staticSharedLibName != null) {
12053            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12054                if (DEBUG_REMOVE && chatty) {
12055                    if (r == null) {
12056                        r = new StringBuilder(256);
12057                    } else {
12058                        r.append(' ');
12059                    }
12060                    r.append(pkg.staticSharedLibName);
12061                }
12062            }
12063        }
12064
12065        if (r != null) {
12066            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12067        }
12068    }
12069
12070    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12071        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12072            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12073                return true;
12074            }
12075        }
12076        return false;
12077    }
12078
12079    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12080    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12081    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12082
12083    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12084        // Update the parent permissions
12085        updatePermissionsLPw(pkg.packageName, pkg, flags);
12086        // Update the child permissions
12087        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12088        for (int i = 0; i < childCount; i++) {
12089            PackageParser.Package childPkg = pkg.childPackages.get(i);
12090            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12091        }
12092    }
12093
12094    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12095            int flags) {
12096        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12097        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12098    }
12099
12100    private void updatePermissionsLPw(String changingPkg,
12101            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12102        // TODO: Most of the methods exposing BasePermission internals [source package name,
12103        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12104        // have package settings, we should make note of it elsewhere [map between
12105        // source package name and BasePermission] and cycle through that here. Then we
12106        // define a single method on BasePermission that takes a PackageSetting, changing
12107        // package name and a package.
12108        // NOTE: With this approach, we also don't need to tree trees differently than
12109        // normal permissions. Today, we need two separate loops because these BasePermission
12110        // objects are stored separately.
12111        // Make sure there are no dangling permission trees.
12112        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12113        while (it.hasNext()) {
12114            final BasePermission bp = it.next();
12115            if (bp.getSourcePackageSetting() == null) {
12116                // We may not yet have parsed the package, so just see if
12117                // we still know about its settings.
12118                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12119            }
12120            if (bp.getSourcePackageSetting() == null) {
12121                Slog.w(TAG, "Removing dangling permission tree: " + bp.getName()
12122                        + " from package " + bp.getSourcePackageName());
12123                it.remove();
12124            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12125                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12126                    Slog.i(TAG, "Removing old permission tree: " + bp.getName()
12127                            + " from package " + bp.getSourcePackageName());
12128                    flags |= UPDATE_PERMISSIONS_ALL;
12129                    it.remove();
12130                }
12131            }
12132        }
12133
12134        // Make sure all dynamic permissions have been assigned to a package,
12135        // and make sure there are no dangling permissions.
12136        final Iterator<BasePermission> permissionIter =
12137                mPermissionManager.getPermissionIteratorTEMP();
12138        while (permissionIter.hasNext()) {
12139            final BasePermission bp = permissionIter.next();
12140            if (bp.isDynamic()) {
12141                bp.updateDynamicPermission(mSettings.mPermissionTrees);
12142            }
12143            if (bp.getSourcePackageSetting() == null) {
12144                // We may not yet have parsed the package, so just see if
12145                // we still know about its settings.
12146                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12147            }
12148            if (bp.getSourcePackageSetting() == null) {
12149                Slog.w(TAG, "Removing dangling permission: " + bp.getName()
12150                        + " from package " + bp.getSourcePackageName());
12151                permissionIter.remove();
12152            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12153                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12154                    Slog.i(TAG, "Removing old permission: " + bp.getName()
12155                            + " from package " + bp.getSourcePackageName());
12156                    flags |= UPDATE_PERMISSIONS_ALL;
12157                    permissionIter.remove();
12158                }
12159            }
12160        }
12161
12162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12163        // Now update the permissions for all packages, in particular
12164        // replace the granted permissions of the system packages.
12165        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12166            for (PackageParser.Package pkg : mPackages.values()) {
12167                if (pkg != pkgInfo) {
12168                    // Only replace for packages on requested volume
12169                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12170                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12171                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12172                    grantPermissionsLPw(pkg, replace, changingPkg);
12173                }
12174            }
12175        }
12176
12177        if (pkgInfo != null) {
12178            // Only replace for packages on requested volume
12179            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12180            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12181                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12182            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12183        }
12184        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12185    }
12186
12187    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12188            String packageOfInterest) {
12189        // IMPORTANT: There are two types of permissions: install and runtime.
12190        // Install time permissions are granted when the app is installed to
12191        // all device users and users added in the future. Runtime permissions
12192        // are granted at runtime explicitly to specific users. Normal and signature
12193        // protected permissions are install time permissions. Dangerous permissions
12194        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12195        // otherwise they are runtime permissions. This function does not manage
12196        // runtime permissions except for the case an app targeting Lollipop MR1
12197        // being upgraded to target a newer SDK, in which case dangerous permissions
12198        // are transformed from install time to runtime ones.
12199
12200        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12201        if (ps == null) {
12202            return;
12203        }
12204
12205        PermissionsState permissionsState = ps.getPermissionsState();
12206        PermissionsState origPermissions = permissionsState;
12207
12208        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12209
12210        boolean runtimePermissionsRevoked = false;
12211        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12212
12213        boolean changedInstallPermission = false;
12214
12215        if (replace) {
12216            ps.installPermissionsFixed = false;
12217            if (!ps.isSharedUser()) {
12218                origPermissions = new PermissionsState(permissionsState);
12219                permissionsState.reset();
12220            } else {
12221                // We need to know only about runtime permission changes since the
12222                // calling code always writes the install permissions state but
12223                // the runtime ones are written only if changed. The only cases of
12224                // changed runtime permissions here are promotion of an install to
12225                // runtime and revocation of a runtime from a shared user.
12226                changedRuntimePermissionUserIds =
12227                        mPermissionManager.revokeUnusedSharedUserPermissions(
12228                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12229                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12230                    runtimePermissionsRevoked = true;
12231                }
12232            }
12233        }
12234
12235        permissionsState.setGlobalGids(mGlobalGids);
12236
12237        final int N = pkg.requestedPermissions.size();
12238        for (int i=0; i<N; i++) {
12239            final String name = pkg.requestedPermissions.get(i);
12240            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12241            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12242                    >= Build.VERSION_CODES.M;
12243
12244            if (DEBUG_INSTALL) {
12245                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12246            }
12247
12248            if (bp == null || bp.getSourcePackageSetting() == null) {
12249                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12250                    if (DEBUG_PERMISSIONS) {
12251                        Slog.i(TAG, "Unknown permission " + name
12252                                + " in package " + pkg.packageName);
12253                    }
12254                }
12255                continue;
12256            }
12257
12258
12259            // Limit ephemeral apps to ephemeral allowed permissions.
12260            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12261                if (DEBUG_PERMISSIONS) {
12262                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12263                            + pkg.packageName);
12264                }
12265                continue;
12266            }
12267
12268            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12269                if (DEBUG_PERMISSIONS) {
12270                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12271                            + pkg.packageName);
12272                }
12273                continue;
12274            }
12275
12276            final String perm = bp.getName();
12277            boolean allowedSig = false;
12278            int grant = GRANT_DENIED;
12279
12280            // Keep track of app op permissions.
12281            if (bp.isAppOp()) {
12282                ArraySet<String> pkgs = mAppOpPermissionPackages.get(perm);
12283                if (pkgs == null) {
12284                    pkgs = new ArraySet<>();
12285                    mAppOpPermissionPackages.put(perm, pkgs);
12286                }
12287                pkgs.add(pkg.packageName);
12288            }
12289
12290            if (bp.isNormal()) {
12291                // For all apps normal permissions are install time ones.
12292                grant = GRANT_INSTALL;
12293            } else if (bp.isRuntime()) {
12294                // If a permission review is required for legacy apps we represent
12295                // their permissions as always granted runtime ones since we need
12296                // to keep the review required permission flag per user while an
12297                // install permission's state is shared across all users.
12298                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12299                    // For legacy apps dangerous permissions are install time ones.
12300                    grant = GRANT_INSTALL;
12301                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12302                    // For legacy apps that became modern, install becomes runtime.
12303                    grant = GRANT_UPGRADE;
12304                } else if (mPromoteSystemApps
12305                        && isSystemApp(ps)
12306                        && mExistingSystemPackages.contains(ps.name)) {
12307                    // For legacy system apps, install becomes runtime.
12308                    // We cannot check hasInstallPermission() for system apps since those
12309                    // permissions were granted implicitly and not persisted pre-M.
12310                    grant = GRANT_UPGRADE;
12311                } else {
12312                    // For modern apps keep runtime permissions unchanged.
12313                    grant = GRANT_RUNTIME;
12314                }
12315            } else if (bp.isSignature()) {
12316                // For all apps signature permissions are install time ones.
12317                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12318                if (allowedSig) {
12319                    grant = GRANT_INSTALL;
12320                }
12321            }
12322
12323            if (DEBUG_PERMISSIONS) {
12324                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12325            }
12326
12327            if (grant != GRANT_DENIED) {
12328                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12329                    // If this is an existing, non-system package, then
12330                    // we can't add any new permissions to it.
12331                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12332                        // Except...  if this is a permission that was added
12333                        // to the platform (note: need to only do this when
12334                        // updating the platform).
12335                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12336                            grant = GRANT_DENIED;
12337                        }
12338                    }
12339                }
12340
12341                switch (grant) {
12342                    case GRANT_INSTALL: {
12343                        // Revoke this as runtime permission to handle the case of
12344                        // a runtime permission being downgraded to an install one.
12345                        // Also in permission review mode we keep dangerous permissions
12346                        // for legacy apps
12347                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12348                            if (origPermissions.getRuntimePermissionState(
12349                                    perm, userId) != null) {
12350                                // Revoke the runtime permission and clear the flags.
12351                                origPermissions.revokeRuntimePermission(bp, userId);
12352                                origPermissions.updatePermissionFlags(bp, userId,
12353                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12354                                // If we revoked a permission permission, we have to write.
12355                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12356                                        changedRuntimePermissionUserIds, userId);
12357                            }
12358                        }
12359                        // Grant an install permission.
12360                        if (permissionsState.grantInstallPermission(bp) !=
12361                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12362                            changedInstallPermission = true;
12363                        }
12364                    } break;
12365
12366                    case GRANT_RUNTIME: {
12367                        // Grant previously granted runtime permissions.
12368                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12369                            PermissionState permissionState = origPermissions
12370                                    .getRuntimePermissionState(perm, userId);
12371                            int flags = permissionState != null
12372                                    ? permissionState.getFlags() : 0;
12373                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12374                                // Don't propagate the permission in a permission review mode if
12375                                // the former was revoked, i.e. marked to not propagate on upgrade.
12376                                // Note that in a permission review mode install permissions are
12377                                // represented as constantly granted runtime ones since we need to
12378                                // keep a per user state associated with the permission. Also the
12379                                // revoke on upgrade flag is no longer applicable and is reset.
12380                                final boolean revokeOnUpgrade = (flags & PackageManager
12381                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12382                                if (revokeOnUpgrade) {
12383                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12384                                    // Since we changed the flags, we have to write.
12385                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12386                                            changedRuntimePermissionUserIds, userId);
12387                                }
12388                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12389                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12390                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12391                                        // If we cannot put the permission as it was,
12392                                        // we have to write.
12393                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12394                                                changedRuntimePermissionUserIds, userId);
12395                                    }
12396                                }
12397
12398                                // If the app supports runtime permissions no need for a review.
12399                                if (mPermissionReviewRequired
12400                                        && appSupportsRuntimePermissions
12401                                        && (flags & PackageManager
12402                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12403                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12404                                    // Since we changed the flags, we have to write.
12405                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12406                                            changedRuntimePermissionUserIds, userId);
12407                                }
12408                            } else if (mPermissionReviewRequired
12409                                    && !appSupportsRuntimePermissions) {
12410                                // For legacy apps that need a permission review, every new
12411                                // runtime permission is granted but it is pending a review.
12412                                // We also need to review only platform defined runtime
12413                                // permissions as these are the only ones the platform knows
12414                                // how to disable the API to simulate revocation as legacy
12415                                // apps don't expect to run with revoked permissions.
12416                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12417                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12418                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12419                                        // We changed the flags, hence have to write.
12420                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12421                                                changedRuntimePermissionUserIds, userId);
12422                                    }
12423                                }
12424                                if (permissionsState.grantRuntimePermission(bp, userId)
12425                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12426                                    // We changed the permission, hence have to write.
12427                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12428                                            changedRuntimePermissionUserIds, userId);
12429                                }
12430                            }
12431                            // Propagate the permission flags.
12432                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12433                        }
12434                    } break;
12435
12436                    case GRANT_UPGRADE: {
12437                        // Grant runtime permissions for a previously held install permission.
12438                        PermissionState permissionState = origPermissions
12439                                .getInstallPermissionState(perm);
12440                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12441
12442                        if (origPermissions.revokeInstallPermission(bp)
12443                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12444                            // We will be transferring the permission flags, so clear them.
12445                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12446                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12447                            changedInstallPermission = true;
12448                        }
12449
12450                        // If the permission is not to be promoted to runtime we ignore it and
12451                        // also its other flags as they are not applicable to install permissions.
12452                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12453                            for (int userId : currentUserIds) {
12454                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12455                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12456                                    // Transfer the permission flags.
12457                                    permissionsState.updatePermissionFlags(bp, userId,
12458                                            flags, flags);
12459                                    // If we granted the permission, we have to write.
12460                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12461                                            changedRuntimePermissionUserIds, userId);
12462                                }
12463                            }
12464                        }
12465                    } break;
12466
12467                    default: {
12468                        if (packageOfInterest == null
12469                                || packageOfInterest.equals(pkg.packageName)) {
12470                            if (DEBUG_PERMISSIONS) {
12471                                Slog.i(TAG, "Not granting permission " + perm
12472                                        + " to package " + pkg.packageName
12473                                        + " because it was previously installed without");
12474                            }
12475                        }
12476                    } break;
12477                }
12478            } else {
12479                if (permissionsState.revokeInstallPermission(bp) !=
12480                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12481                    // Also drop the permission flags.
12482                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12483                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12484                    changedInstallPermission = true;
12485                    Slog.i(TAG, "Un-granting permission " + perm
12486                            + " from package " + pkg.packageName
12487                            + " (protectionLevel=" + bp.getProtectionLevel()
12488                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12489                            + ")");
12490                } else if (bp.isAppOp()) {
12491                    // Don't print warning for app op permissions, since it is fine for them
12492                    // not to be granted, there is a UI for the user to decide.
12493                    if (DEBUG_PERMISSIONS
12494                            && (packageOfInterest == null
12495                                    || packageOfInterest.equals(pkg.packageName))) {
12496                        Slog.i(TAG, "Not granting permission " + perm
12497                                + " to package " + pkg.packageName
12498                                + " (protectionLevel=" + bp.getProtectionLevel()
12499                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12500                                + ")");
12501                    }
12502                }
12503            }
12504        }
12505
12506        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12507                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12508            // This is the first that we have heard about this package, so the
12509            // permissions we have now selected are fixed until explicitly
12510            // changed.
12511            ps.installPermissionsFixed = true;
12512        }
12513
12514        // Persist the runtime permissions state for users with changes. If permissions
12515        // were revoked because no app in the shared user declares them we have to
12516        // write synchronously to avoid losing runtime permissions state.
12517        for (int userId : changedRuntimePermissionUserIds) {
12518            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12519        }
12520    }
12521
12522    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12523        boolean allowed = false;
12524        final int NP = PackageParser.NEW_PERMISSIONS.length;
12525        for (int ip=0; ip<NP; ip++) {
12526            final PackageParser.NewPermissionInfo npi
12527                    = PackageParser.NEW_PERMISSIONS[ip];
12528            if (npi.name.equals(perm)
12529                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12530                allowed = true;
12531                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12532                        + pkg.packageName);
12533                break;
12534            }
12535        }
12536        return allowed;
12537    }
12538
12539    /**
12540     * Determines whether a package is whitelisted for a particular privapp permission.
12541     *
12542     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12543     *
12544     * <p>This handles parent/child apps.
12545     */
12546    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12547        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12548                .getPrivAppPermissions(pkg.packageName);
12549        // Let's check if this package is whitelisted...
12550        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12551        // If it's not, we'll also tail-recurse to the parent.
12552        return whitelisted ||
12553                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12554    }
12555
12556    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12557            BasePermission bp, PermissionsState origPermissions) {
12558        boolean oemPermission = bp.isOEM();
12559        boolean privilegedPermission = bp.isPrivileged();
12560        boolean privappPermissionsDisable =
12561                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12562        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12563        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12564        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12565                && !platformPackage && platformPermission) {
12566            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12567                Slog.w(TAG, "Privileged permission " + perm + " for package "
12568                        + pkg.packageName + " - not in privapp-permissions whitelist");
12569                // Only report violations for apps on system image
12570                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12571                    // it's only a reportable violation if the permission isn't explicitly denied
12572                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12573                            .getPrivAppDenyPermissions(pkg.packageName);
12574                    final boolean permissionViolation =
12575                            deniedPermissions == null || !deniedPermissions.contains(perm);
12576                    if (permissionViolation) {
12577                        if (mPrivappPermissionsViolations == null) {
12578                            mPrivappPermissionsViolations = new ArraySet<>();
12579                        }
12580                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12581                    } else {
12582                        return false;
12583                    }
12584                }
12585                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12586                    return false;
12587                }
12588            }
12589        }
12590        boolean allowed = (compareSignatures(
12591                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12592                        == PackageManager.SIGNATURE_MATCH)
12593                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12594                        == PackageManager.SIGNATURE_MATCH);
12595        if (!allowed && (privilegedPermission || oemPermission)) {
12596            if (isSystemApp(pkg)) {
12597                // For updated system applications, a privileged/oem permission
12598                // is granted only if it had been defined by the original application.
12599                if (pkg.isUpdatedSystemApp()) {
12600                    final PackageSetting sysPs = mSettings
12601                            .getDisabledSystemPkgLPr(pkg.packageName);
12602                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12603                        // If the original was granted this permission, we take
12604                        // that grant decision as read and propagate it to the
12605                        // update.
12606                        if ((privilegedPermission && sysPs.isPrivileged())
12607                                || (oemPermission && sysPs.isOem()
12608                                        && canGrantOemPermission(sysPs, perm))) {
12609                            allowed = true;
12610                        }
12611                    } else {
12612                        // The system apk may have been updated with an older
12613                        // version of the one on the data partition, but which
12614                        // granted a new system permission that it didn't have
12615                        // before.  In this case we do want to allow the app to
12616                        // now get the new permission if the ancestral apk is
12617                        // privileged to get it.
12618                        if (sysPs != null && sysPs.pkg != null
12619                                && isPackageRequestingPermission(sysPs.pkg, perm)
12620                                && ((privilegedPermission && sysPs.isPrivileged())
12621                                        || (oemPermission && sysPs.isOem()
12622                                                && canGrantOemPermission(sysPs, perm)))) {
12623                            allowed = true;
12624                        }
12625                        // Also if a privileged parent package on the system image or any of
12626                        // its children requested a privileged/oem permission, the updated child
12627                        // packages can also get the permission.
12628                        if (pkg.parentPackage != null) {
12629                            final PackageSetting disabledSysParentPs = mSettings
12630                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12631                            final PackageParser.Package disabledSysParentPkg =
12632                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12633                                    ? null : disabledSysParentPs.pkg;
12634                            if (disabledSysParentPkg != null
12635                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12636                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12637                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12638                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12639                                    allowed = true;
12640                                } else if (disabledSysParentPkg.childPackages != null) {
12641                                    final int count = disabledSysParentPkg.childPackages.size();
12642                                    for (int i = 0; i < count; i++) {
12643                                        final PackageParser.Package disabledSysChildPkg =
12644                                                disabledSysParentPkg.childPackages.get(i);
12645                                        final PackageSetting disabledSysChildPs =
12646                                                mSettings.getDisabledSystemPkgLPr(
12647                                                        disabledSysChildPkg.packageName);
12648                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12649                                                && canGrantOemPermission(
12650                                                        disabledSysChildPs, perm)) {
12651                                            allowed = true;
12652                                            break;
12653                                        }
12654                                    }
12655                                }
12656                            }
12657                        }
12658                    }
12659                } else {
12660                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12661                            || (oemPermission && isOemApp(pkg)
12662                                    && canGrantOemPermission(
12663                                            mSettings.getPackageLPr(pkg.packageName), perm));
12664                }
12665            }
12666        }
12667        if (!allowed) {
12668            if (!allowed
12669                    && bp.isPre23()
12670                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12671                // If this was a previously normal/dangerous permission that got moved
12672                // to a system permission as part of the runtime permission redesign, then
12673                // we still want to blindly grant it to old apps.
12674                allowed = true;
12675            }
12676            if (!allowed && bp.isInstaller()
12677                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12678                // If this permission is to be granted to the system installer and
12679                // this app is an installer, then it gets the permission.
12680                allowed = true;
12681            }
12682            if (!allowed && bp.isVerifier()
12683                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12684                // If this permission is to be granted to the system verifier and
12685                // this app is a verifier, then it gets the permission.
12686                allowed = true;
12687            }
12688            if (!allowed && bp.isPreInstalled()
12689                    && isSystemApp(pkg)) {
12690                // Any pre-installed system app is allowed to get this permission.
12691                allowed = true;
12692            }
12693            if (!allowed && bp.isDevelopment()) {
12694                // For development permissions, a development permission
12695                // is granted only if it was already granted.
12696                allowed = origPermissions.hasInstallPermission(perm);
12697            }
12698            if (!allowed && bp.isSetup()
12699                    && pkg.packageName.equals(mSetupWizardPackage)) {
12700                // If this permission is to be granted to the system setup wizard and
12701                // this app is a setup wizard, then it gets the permission.
12702                allowed = true;
12703            }
12704        }
12705        return allowed;
12706    }
12707
12708    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12709        if (!ps.isOem()) {
12710            return false;
12711        }
12712        // all oem permissions must explicitly be granted or denied
12713        final Boolean granted =
12714                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12715        if (granted == null) {
12716            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12717                    + ps.name + " must be explicitly declared granted or not");
12718        }
12719        return Boolean.TRUE == granted;
12720    }
12721
12722    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12723        final int permCount = pkg.requestedPermissions.size();
12724        for (int j = 0; j < permCount; j++) {
12725            String requestedPermission = pkg.requestedPermissions.get(j);
12726            if (permission.equals(requestedPermission)) {
12727                return true;
12728            }
12729        }
12730        return false;
12731    }
12732
12733    final class ActivityIntentResolver
12734            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12735        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12736                boolean defaultOnly, int userId) {
12737            if (!sUserManager.exists(userId)) return null;
12738            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12739            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12740        }
12741
12742        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12743                int userId) {
12744            if (!sUserManager.exists(userId)) return null;
12745            mFlags = flags;
12746            return super.queryIntent(intent, resolvedType,
12747                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12748                    userId);
12749        }
12750
12751        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12752                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12753            if (!sUserManager.exists(userId)) return null;
12754            if (packageActivities == null) {
12755                return null;
12756            }
12757            mFlags = flags;
12758            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12759            final int N = packageActivities.size();
12760            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12761                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12762
12763            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12764            for (int i = 0; i < N; ++i) {
12765                intentFilters = packageActivities.get(i).intents;
12766                if (intentFilters != null && intentFilters.size() > 0) {
12767                    PackageParser.ActivityIntentInfo[] array =
12768                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12769                    intentFilters.toArray(array);
12770                    listCut.add(array);
12771                }
12772            }
12773            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12774        }
12775
12776        /**
12777         * Finds a privileged activity that matches the specified activity names.
12778         */
12779        private PackageParser.Activity findMatchingActivity(
12780                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12781            for (PackageParser.Activity sysActivity : activityList) {
12782                if (sysActivity.info.name.equals(activityInfo.name)) {
12783                    return sysActivity;
12784                }
12785                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12786                    return sysActivity;
12787                }
12788                if (sysActivity.info.targetActivity != null) {
12789                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12790                        return sysActivity;
12791                    }
12792                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12793                        return sysActivity;
12794                    }
12795                }
12796            }
12797            return null;
12798        }
12799
12800        public class IterGenerator<E> {
12801            public Iterator<E> generate(ActivityIntentInfo info) {
12802                return null;
12803            }
12804        }
12805
12806        public class ActionIterGenerator extends IterGenerator<String> {
12807            @Override
12808            public Iterator<String> generate(ActivityIntentInfo info) {
12809                return info.actionsIterator();
12810            }
12811        }
12812
12813        public class CategoriesIterGenerator extends IterGenerator<String> {
12814            @Override
12815            public Iterator<String> generate(ActivityIntentInfo info) {
12816                return info.categoriesIterator();
12817            }
12818        }
12819
12820        public class SchemesIterGenerator extends IterGenerator<String> {
12821            @Override
12822            public Iterator<String> generate(ActivityIntentInfo info) {
12823                return info.schemesIterator();
12824            }
12825        }
12826
12827        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12828            @Override
12829            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12830                return info.authoritiesIterator();
12831            }
12832        }
12833
12834        /**
12835         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12836         * MODIFIED. Do not pass in a list that should not be changed.
12837         */
12838        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12839                IterGenerator<T> generator, Iterator<T> searchIterator) {
12840            // loop through the set of actions; every one must be found in the intent filter
12841            while (searchIterator.hasNext()) {
12842                // we must have at least one filter in the list to consider a match
12843                if (intentList.size() == 0) {
12844                    break;
12845                }
12846
12847                final T searchAction = searchIterator.next();
12848
12849                // loop through the set of intent filters
12850                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12851                while (intentIter.hasNext()) {
12852                    final ActivityIntentInfo intentInfo = intentIter.next();
12853                    boolean selectionFound = false;
12854
12855                    // loop through the intent filter's selection criteria; at least one
12856                    // of them must match the searched criteria
12857                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12858                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12859                        final T intentSelection = intentSelectionIter.next();
12860                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12861                            selectionFound = true;
12862                            break;
12863                        }
12864                    }
12865
12866                    // the selection criteria wasn't found in this filter's set; this filter
12867                    // is not a potential match
12868                    if (!selectionFound) {
12869                        intentIter.remove();
12870                    }
12871                }
12872            }
12873        }
12874
12875        private boolean isProtectedAction(ActivityIntentInfo filter) {
12876            final Iterator<String> actionsIter = filter.actionsIterator();
12877            while (actionsIter != null && actionsIter.hasNext()) {
12878                final String filterAction = actionsIter.next();
12879                if (PROTECTED_ACTIONS.contains(filterAction)) {
12880                    return true;
12881                }
12882            }
12883            return false;
12884        }
12885
12886        /**
12887         * Adjusts the priority of the given intent filter according to policy.
12888         * <p>
12889         * <ul>
12890         * <li>The priority for non privileged applications is capped to '0'</li>
12891         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12892         * <li>The priority for unbundled updates to privileged applications is capped to the
12893         *      priority defined on the system partition</li>
12894         * </ul>
12895         * <p>
12896         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12897         * allowed to obtain any priority on any action.
12898         */
12899        private void adjustPriority(
12900                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12901            // nothing to do; priority is fine as-is
12902            if (intent.getPriority() <= 0) {
12903                return;
12904            }
12905
12906            final ActivityInfo activityInfo = intent.activity.info;
12907            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12908
12909            final boolean privilegedApp =
12910                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12911            if (!privilegedApp) {
12912                // non-privileged applications can never define a priority >0
12913                if (DEBUG_FILTERS) {
12914                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12915                            + " package: " + applicationInfo.packageName
12916                            + " activity: " + intent.activity.className
12917                            + " origPrio: " + intent.getPriority());
12918                }
12919                intent.setPriority(0);
12920                return;
12921            }
12922
12923            if (systemActivities == null) {
12924                // the system package is not disabled; we're parsing the system partition
12925                if (isProtectedAction(intent)) {
12926                    if (mDeferProtectedFilters) {
12927                        // We can't deal with these just yet. No component should ever obtain a
12928                        // >0 priority for a protected actions, with ONE exception -- the setup
12929                        // wizard. The setup wizard, however, cannot be known until we're able to
12930                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12931                        // until all intent filters have been processed. Chicken, meet egg.
12932                        // Let the filter temporarily have a high priority and rectify the
12933                        // priorities after all system packages have been scanned.
12934                        mProtectedFilters.add(intent);
12935                        if (DEBUG_FILTERS) {
12936                            Slog.i(TAG, "Protected action; save for later;"
12937                                    + " package: " + applicationInfo.packageName
12938                                    + " activity: " + intent.activity.className
12939                                    + " origPrio: " + intent.getPriority());
12940                        }
12941                        return;
12942                    } else {
12943                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12944                            Slog.i(TAG, "No setup wizard;"
12945                                + " All protected intents capped to priority 0");
12946                        }
12947                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12948                            if (DEBUG_FILTERS) {
12949                                Slog.i(TAG, "Found setup wizard;"
12950                                    + " allow priority " + intent.getPriority() + ";"
12951                                    + " package: " + intent.activity.info.packageName
12952                                    + " activity: " + intent.activity.className
12953                                    + " priority: " + intent.getPriority());
12954                            }
12955                            // setup wizard gets whatever it wants
12956                            return;
12957                        }
12958                        if (DEBUG_FILTERS) {
12959                            Slog.i(TAG, "Protected action; cap priority to 0;"
12960                                    + " package: " + intent.activity.info.packageName
12961                                    + " activity: " + intent.activity.className
12962                                    + " origPrio: " + intent.getPriority());
12963                        }
12964                        intent.setPriority(0);
12965                        return;
12966                    }
12967                }
12968                // privileged apps on the system image get whatever priority they request
12969                return;
12970            }
12971
12972            // privileged app unbundled update ... try to find the same activity
12973            final PackageParser.Activity foundActivity =
12974                    findMatchingActivity(systemActivities, activityInfo);
12975            if (foundActivity == null) {
12976                // this is a new activity; it cannot obtain >0 priority
12977                if (DEBUG_FILTERS) {
12978                    Slog.i(TAG, "New activity; cap priority to 0;"
12979                            + " package: " + applicationInfo.packageName
12980                            + " activity: " + intent.activity.className
12981                            + " origPrio: " + intent.getPriority());
12982                }
12983                intent.setPriority(0);
12984                return;
12985            }
12986
12987            // found activity, now check for filter equivalence
12988
12989            // a shallow copy is enough; we modify the list, not its contents
12990            final List<ActivityIntentInfo> intentListCopy =
12991                    new ArrayList<>(foundActivity.intents);
12992            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12993
12994            // find matching action subsets
12995            final Iterator<String> actionsIterator = intent.actionsIterator();
12996            if (actionsIterator != null) {
12997                getIntentListSubset(
12998                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12999                if (intentListCopy.size() == 0) {
13000                    // no more intents to match; we're not equivalent
13001                    if (DEBUG_FILTERS) {
13002                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13003                                + " package: " + applicationInfo.packageName
13004                                + " activity: " + intent.activity.className
13005                                + " origPrio: " + intent.getPriority());
13006                    }
13007                    intent.setPriority(0);
13008                    return;
13009                }
13010            }
13011
13012            // find matching category subsets
13013            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13014            if (categoriesIterator != null) {
13015                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13016                        categoriesIterator);
13017                if (intentListCopy.size() == 0) {
13018                    // no more intents to match; we're not equivalent
13019                    if (DEBUG_FILTERS) {
13020                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13021                                + " package: " + applicationInfo.packageName
13022                                + " activity: " + intent.activity.className
13023                                + " origPrio: " + intent.getPriority());
13024                    }
13025                    intent.setPriority(0);
13026                    return;
13027                }
13028            }
13029
13030            // find matching schemes subsets
13031            final Iterator<String> schemesIterator = intent.schemesIterator();
13032            if (schemesIterator != null) {
13033                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13034                        schemesIterator);
13035                if (intentListCopy.size() == 0) {
13036                    // no more intents to match; we're not equivalent
13037                    if (DEBUG_FILTERS) {
13038                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13039                                + " package: " + applicationInfo.packageName
13040                                + " activity: " + intent.activity.className
13041                                + " origPrio: " + intent.getPriority());
13042                    }
13043                    intent.setPriority(0);
13044                    return;
13045                }
13046            }
13047
13048            // find matching authorities subsets
13049            final Iterator<IntentFilter.AuthorityEntry>
13050                    authoritiesIterator = intent.authoritiesIterator();
13051            if (authoritiesIterator != null) {
13052                getIntentListSubset(intentListCopy,
13053                        new AuthoritiesIterGenerator(),
13054                        authoritiesIterator);
13055                if (intentListCopy.size() == 0) {
13056                    // no more intents to match; we're not equivalent
13057                    if (DEBUG_FILTERS) {
13058                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13059                                + " package: " + applicationInfo.packageName
13060                                + " activity: " + intent.activity.className
13061                                + " origPrio: " + intent.getPriority());
13062                    }
13063                    intent.setPriority(0);
13064                    return;
13065                }
13066            }
13067
13068            // we found matching filter(s); app gets the max priority of all intents
13069            int cappedPriority = 0;
13070            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13071                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13072            }
13073            if (intent.getPriority() > cappedPriority) {
13074                if (DEBUG_FILTERS) {
13075                    Slog.i(TAG, "Found matching filter(s);"
13076                            + " cap priority to " + cappedPriority + ";"
13077                            + " package: " + applicationInfo.packageName
13078                            + " activity: " + intent.activity.className
13079                            + " origPrio: " + intent.getPriority());
13080                }
13081                intent.setPriority(cappedPriority);
13082                return;
13083            }
13084            // all this for nothing; the requested priority was <= what was on the system
13085        }
13086
13087        public final void addActivity(PackageParser.Activity a, String type) {
13088            mActivities.put(a.getComponentName(), a);
13089            if (DEBUG_SHOW_INFO)
13090                Log.v(
13091                TAG, "  " + type + " " +
13092                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13093            if (DEBUG_SHOW_INFO)
13094                Log.v(TAG, "    Class=" + a.info.name);
13095            final int NI = a.intents.size();
13096            for (int j=0; j<NI; j++) {
13097                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13098                if ("activity".equals(type)) {
13099                    final PackageSetting ps =
13100                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13101                    final List<PackageParser.Activity> systemActivities =
13102                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13103                    adjustPriority(systemActivities, intent);
13104                }
13105                if (DEBUG_SHOW_INFO) {
13106                    Log.v(TAG, "    IntentFilter:");
13107                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13108                }
13109                if (!intent.debugCheck()) {
13110                    Log.w(TAG, "==> For Activity " + a.info.name);
13111                }
13112                addFilter(intent);
13113            }
13114        }
13115
13116        public final void removeActivity(PackageParser.Activity a, String type) {
13117            mActivities.remove(a.getComponentName());
13118            if (DEBUG_SHOW_INFO) {
13119                Log.v(TAG, "  " + type + " "
13120                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13121                                : a.info.name) + ":");
13122                Log.v(TAG, "    Class=" + a.info.name);
13123            }
13124            final int NI = a.intents.size();
13125            for (int j=0; j<NI; j++) {
13126                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13127                if (DEBUG_SHOW_INFO) {
13128                    Log.v(TAG, "    IntentFilter:");
13129                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13130                }
13131                removeFilter(intent);
13132            }
13133        }
13134
13135        @Override
13136        protected boolean allowFilterResult(
13137                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13138            ActivityInfo filterAi = filter.activity.info;
13139            for (int i=dest.size()-1; i>=0; i--) {
13140                ActivityInfo destAi = dest.get(i).activityInfo;
13141                if (destAi.name == filterAi.name
13142                        && destAi.packageName == filterAi.packageName) {
13143                    return false;
13144                }
13145            }
13146            return true;
13147        }
13148
13149        @Override
13150        protected ActivityIntentInfo[] newArray(int size) {
13151            return new ActivityIntentInfo[size];
13152        }
13153
13154        @Override
13155        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13156            if (!sUserManager.exists(userId)) return true;
13157            PackageParser.Package p = filter.activity.owner;
13158            if (p != null) {
13159                PackageSetting ps = (PackageSetting)p.mExtras;
13160                if (ps != null) {
13161                    // System apps are never considered stopped for purposes of
13162                    // filtering, because there may be no way for the user to
13163                    // actually re-launch them.
13164                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13165                            && ps.getStopped(userId);
13166                }
13167            }
13168            return false;
13169        }
13170
13171        @Override
13172        protected boolean isPackageForFilter(String packageName,
13173                PackageParser.ActivityIntentInfo info) {
13174            return packageName.equals(info.activity.owner.packageName);
13175        }
13176
13177        @Override
13178        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13179                int match, int userId) {
13180            if (!sUserManager.exists(userId)) return null;
13181            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13182                return null;
13183            }
13184            final PackageParser.Activity activity = info.activity;
13185            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13186            if (ps == null) {
13187                return null;
13188            }
13189            final PackageUserState userState = ps.readUserState(userId);
13190            ActivityInfo ai =
13191                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13192            if (ai == null) {
13193                return null;
13194            }
13195            final boolean matchExplicitlyVisibleOnly =
13196                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13197            final boolean matchVisibleToInstantApp =
13198                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13199            final boolean componentVisible =
13200                    matchVisibleToInstantApp
13201                    && info.isVisibleToInstantApp()
13202                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13203            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13204            // throw out filters that aren't visible to ephemeral apps
13205            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13206                return null;
13207            }
13208            // throw out instant app filters if we're not explicitly requesting them
13209            if (!matchInstantApp && userState.instantApp) {
13210                return null;
13211            }
13212            // throw out instant app filters if updates are available; will trigger
13213            // instant app resolution
13214            if (userState.instantApp && ps.isUpdateAvailable()) {
13215                return null;
13216            }
13217            final ResolveInfo res = new ResolveInfo();
13218            res.activityInfo = ai;
13219            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13220                res.filter = info;
13221            }
13222            if (info != null) {
13223                res.handleAllWebDataURI = info.handleAllWebDataURI();
13224            }
13225            res.priority = info.getPriority();
13226            res.preferredOrder = activity.owner.mPreferredOrder;
13227            //System.out.println("Result: " + res.activityInfo.className +
13228            //                   " = " + res.priority);
13229            res.match = match;
13230            res.isDefault = info.hasDefault;
13231            res.labelRes = info.labelRes;
13232            res.nonLocalizedLabel = info.nonLocalizedLabel;
13233            if (userNeedsBadging(userId)) {
13234                res.noResourceId = true;
13235            } else {
13236                res.icon = info.icon;
13237            }
13238            res.iconResourceId = info.icon;
13239            res.system = res.activityInfo.applicationInfo.isSystemApp();
13240            res.isInstantAppAvailable = userState.instantApp;
13241            return res;
13242        }
13243
13244        @Override
13245        protected void sortResults(List<ResolveInfo> results) {
13246            Collections.sort(results, mResolvePrioritySorter);
13247        }
13248
13249        @Override
13250        protected void dumpFilter(PrintWriter out, String prefix,
13251                PackageParser.ActivityIntentInfo filter) {
13252            out.print(prefix); out.print(
13253                    Integer.toHexString(System.identityHashCode(filter.activity)));
13254                    out.print(' ');
13255                    filter.activity.printComponentShortName(out);
13256                    out.print(" filter ");
13257                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13258        }
13259
13260        @Override
13261        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13262            return filter.activity;
13263        }
13264
13265        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13266            PackageParser.Activity activity = (PackageParser.Activity)label;
13267            out.print(prefix); out.print(
13268                    Integer.toHexString(System.identityHashCode(activity)));
13269                    out.print(' ');
13270                    activity.printComponentShortName(out);
13271            if (count > 1) {
13272                out.print(" ("); out.print(count); out.print(" filters)");
13273            }
13274            out.println();
13275        }
13276
13277        // Keys are String (activity class name), values are Activity.
13278        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13279                = new ArrayMap<ComponentName, PackageParser.Activity>();
13280        private int mFlags;
13281    }
13282
13283    private final class ServiceIntentResolver
13284            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13285        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13286                boolean defaultOnly, int userId) {
13287            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13288            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13289        }
13290
13291        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13292                int userId) {
13293            if (!sUserManager.exists(userId)) return null;
13294            mFlags = flags;
13295            return super.queryIntent(intent, resolvedType,
13296                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13297                    userId);
13298        }
13299
13300        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13301                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13302            if (!sUserManager.exists(userId)) return null;
13303            if (packageServices == null) {
13304                return null;
13305            }
13306            mFlags = flags;
13307            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13308            final int N = packageServices.size();
13309            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13310                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13311
13312            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13313            for (int i = 0; i < N; ++i) {
13314                intentFilters = packageServices.get(i).intents;
13315                if (intentFilters != null && intentFilters.size() > 0) {
13316                    PackageParser.ServiceIntentInfo[] array =
13317                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13318                    intentFilters.toArray(array);
13319                    listCut.add(array);
13320                }
13321            }
13322            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13323        }
13324
13325        public final void addService(PackageParser.Service s) {
13326            mServices.put(s.getComponentName(), s);
13327            if (DEBUG_SHOW_INFO) {
13328                Log.v(TAG, "  "
13329                        + (s.info.nonLocalizedLabel != null
13330                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13331                Log.v(TAG, "    Class=" + s.info.name);
13332            }
13333            final int NI = s.intents.size();
13334            int j;
13335            for (j=0; j<NI; j++) {
13336                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13337                if (DEBUG_SHOW_INFO) {
13338                    Log.v(TAG, "    IntentFilter:");
13339                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13340                }
13341                if (!intent.debugCheck()) {
13342                    Log.w(TAG, "==> For Service " + s.info.name);
13343                }
13344                addFilter(intent);
13345            }
13346        }
13347
13348        public final void removeService(PackageParser.Service s) {
13349            mServices.remove(s.getComponentName());
13350            if (DEBUG_SHOW_INFO) {
13351                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13352                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13353                Log.v(TAG, "    Class=" + s.info.name);
13354            }
13355            final int NI = s.intents.size();
13356            int j;
13357            for (j=0; j<NI; j++) {
13358                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13359                if (DEBUG_SHOW_INFO) {
13360                    Log.v(TAG, "    IntentFilter:");
13361                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13362                }
13363                removeFilter(intent);
13364            }
13365        }
13366
13367        @Override
13368        protected boolean allowFilterResult(
13369                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13370            ServiceInfo filterSi = filter.service.info;
13371            for (int i=dest.size()-1; i>=0; i--) {
13372                ServiceInfo destAi = dest.get(i).serviceInfo;
13373                if (destAi.name == filterSi.name
13374                        && destAi.packageName == filterSi.packageName) {
13375                    return false;
13376                }
13377            }
13378            return true;
13379        }
13380
13381        @Override
13382        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13383            return new PackageParser.ServiceIntentInfo[size];
13384        }
13385
13386        @Override
13387        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13388            if (!sUserManager.exists(userId)) return true;
13389            PackageParser.Package p = filter.service.owner;
13390            if (p != null) {
13391                PackageSetting ps = (PackageSetting)p.mExtras;
13392                if (ps != null) {
13393                    // System apps are never considered stopped for purposes of
13394                    // filtering, because there may be no way for the user to
13395                    // actually re-launch them.
13396                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13397                            && ps.getStopped(userId);
13398                }
13399            }
13400            return false;
13401        }
13402
13403        @Override
13404        protected boolean isPackageForFilter(String packageName,
13405                PackageParser.ServiceIntentInfo info) {
13406            return packageName.equals(info.service.owner.packageName);
13407        }
13408
13409        @Override
13410        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13411                int match, int userId) {
13412            if (!sUserManager.exists(userId)) return null;
13413            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13414            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13415                return null;
13416            }
13417            final PackageParser.Service service = info.service;
13418            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13419            if (ps == null) {
13420                return null;
13421            }
13422            final PackageUserState userState = ps.readUserState(userId);
13423            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13424                    userState, userId);
13425            if (si == null) {
13426                return null;
13427            }
13428            final boolean matchVisibleToInstantApp =
13429                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13430            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13431            // throw out filters that aren't visible to ephemeral apps
13432            if (matchVisibleToInstantApp
13433                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13434                return null;
13435            }
13436            // throw out ephemeral filters if we're not explicitly requesting them
13437            if (!isInstantApp && userState.instantApp) {
13438                return null;
13439            }
13440            // throw out instant app filters if updates are available; will trigger
13441            // instant app resolution
13442            if (userState.instantApp && ps.isUpdateAvailable()) {
13443                return null;
13444            }
13445            final ResolveInfo res = new ResolveInfo();
13446            res.serviceInfo = si;
13447            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13448                res.filter = filter;
13449            }
13450            res.priority = info.getPriority();
13451            res.preferredOrder = service.owner.mPreferredOrder;
13452            res.match = match;
13453            res.isDefault = info.hasDefault;
13454            res.labelRes = info.labelRes;
13455            res.nonLocalizedLabel = info.nonLocalizedLabel;
13456            res.icon = info.icon;
13457            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13458            return res;
13459        }
13460
13461        @Override
13462        protected void sortResults(List<ResolveInfo> results) {
13463            Collections.sort(results, mResolvePrioritySorter);
13464        }
13465
13466        @Override
13467        protected void dumpFilter(PrintWriter out, String prefix,
13468                PackageParser.ServiceIntentInfo filter) {
13469            out.print(prefix); out.print(
13470                    Integer.toHexString(System.identityHashCode(filter.service)));
13471                    out.print(' ');
13472                    filter.service.printComponentShortName(out);
13473                    out.print(" filter ");
13474                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13475        }
13476
13477        @Override
13478        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13479            return filter.service;
13480        }
13481
13482        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13483            PackageParser.Service service = (PackageParser.Service)label;
13484            out.print(prefix); out.print(
13485                    Integer.toHexString(System.identityHashCode(service)));
13486                    out.print(' ');
13487                    service.printComponentShortName(out);
13488            if (count > 1) {
13489                out.print(" ("); out.print(count); out.print(" filters)");
13490            }
13491            out.println();
13492        }
13493
13494//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13495//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13496//            final List<ResolveInfo> retList = Lists.newArrayList();
13497//            while (i.hasNext()) {
13498//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13499//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13500//                    retList.add(resolveInfo);
13501//                }
13502//            }
13503//            return retList;
13504//        }
13505
13506        // Keys are String (activity class name), values are Activity.
13507        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13508                = new ArrayMap<ComponentName, PackageParser.Service>();
13509        private int mFlags;
13510    }
13511
13512    private final class ProviderIntentResolver
13513            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13515                boolean defaultOnly, int userId) {
13516            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13517            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13518        }
13519
13520        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13521                int userId) {
13522            if (!sUserManager.exists(userId))
13523                return null;
13524            mFlags = flags;
13525            return super.queryIntent(intent, resolvedType,
13526                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13527                    userId);
13528        }
13529
13530        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13531                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13532            if (!sUserManager.exists(userId))
13533                return null;
13534            if (packageProviders == null) {
13535                return null;
13536            }
13537            mFlags = flags;
13538            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13539            final int N = packageProviders.size();
13540            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13541                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13542
13543            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13544            for (int i = 0; i < N; ++i) {
13545                intentFilters = packageProviders.get(i).intents;
13546                if (intentFilters != null && intentFilters.size() > 0) {
13547                    PackageParser.ProviderIntentInfo[] array =
13548                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13549                    intentFilters.toArray(array);
13550                    listCut.add(array);
13551                }
13552            }
13553            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13554        }
13555
13556        public final void addProvider(PackageParser.Provider p) {
13557            if (mProviders.containsKey(p.getComponentName())) {
13558                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13559                return;
13560            }
13561
13562            mProviders.put(p.getComponentName(), p);
13563            if (DEBUG_SHOW_INFO) {
13564                Log.v(TAG, "  "
13565                        + (p.info.nonLocalizedLabel != null
13566                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13567                Log.v(TAG, "    Class=" + p.info.name);
13568            }
13569            final int NI = p.intents.size();
13570            int j;
13571            for (j = 0; j < NI; j++) {
13572                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13573                if (DEBUG_SHOW_INFO) {
13574                    Log.v(TAG, "    IntentFilter:");
13575                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13576                }
13577                if (!intent.debugCheck()) {
13578                    Log.w(TAG, "==> For Provider " + p.info.name);
13579                }
13580                addFilter(intent);
13581            }
13582        }
13583
13584        public final void removeProvider(PackageParser.Provider p) {
13585            mProviders.remove(p.getComponentName());
13586            if (DEBUG_SHOW_INFO) {
13587                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13588                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13589                Log.v(TAG, "    Class=" + p.info.name);
13590            }
13591            final int NI = p.intents.size();
13592            int j;
13593            for (j = 0; j < NI; j++) {
13594                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13595                if (DEBUG_SHOW_INFO) {
13596                    Log.v(TAG, "    IntentFilter:");
13597                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13598                }
13599                removeFilter(intent);
13600            }
13601        }
13602
13603        @Override
13604        protected boolean allowFilterResult(
13605                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13606            ProviderInfo filterPi = filter.provider.info;
13607            for (int i = dest.size() - 1; i >= 0; i--) {
13608                ProviderInfo destPi = dest.get(i).providerInfo;
13609                if (destPi.name == filterPi.name
13610                        && destPi.packageName == filterPi.packageName) {
13611                    return false;
13612                }
13613            }
13614            return true;
13615        }
13616
13617        @Override
13618        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13619            return new PackageParser.ProviderIntentInfo[size];
13620        }
13621
13622        @Override
13623        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13624            if (!sUserManager.exists(userId))
13625                return true;
13626            PackageParser.Package p = filter.provider.owner;
13627            if (p != null) {
13628                PackageSetting ps = (PackageSetting) p.mExtras;
13629                if (ps != null) {
13630                    // System apps are never considered stopped for purposes of
13631                    // filtering, because there may be no way for the user to
13632                    // actually re-launch them.
13633                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13634                            && ps.getStopped(userId);
13635                }
13636            }
13637            return false;
13638        }
13639
13640        @Override
13641        protected boolean isPackageForFilter(String packageName,
13642                PackageParser.ProviderIntentInfo info) {
13643            return packageName.equals(info.provider.owner.packageName);
13644        }
13645
13646        @Override
13647        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13648                int match, int userId) {
13649            if (!sUserManager.exists(userId))
13650                return null;
13651            final PackageParser.ProviderIntentInfo info = filter;
13652            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13653                return null;
13654            }
13655            final PackageParser.Provider provider = info.provider;
13656            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13657            if (ps == null) {
13658                return null;
13659            }
13660            final PackageUserState userState = ps.readUserState(userId);
13661            final boolean matchVisibleToInstantApp =
13662                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13663            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13664            // throw out filters that aren't visible to instant applications
13665            if (matchVisibleToInstantApp
13666                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13667                return null;
13668            }
13669            // throw out instant application filters if we're not explicitly requesting them
13670            if (!isInstantApp && userState.instantApp) {
13671                return null;
13672            }
13673            // throw out instant application filters if updates are available; will trigger
13674            // instant application resolution
13675            if (userState.instantApp && ps.isUpdateAvailable()) {
13676                return null;
13677            }
13678            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13679                    userState, userId);
13680            if (pi == null) {
13681                return null;
13682            }
13683            final ResolveInfo res = new ResolveInfo();
13684            res.providerInfo = pi;
13685            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13686                res.filter = filter;
13687            }
13688            res.priority = info.getPriority();
13689            res.preferredOrder = provider.owner.mPreferredOrder;
13690            res.match = match;
13691            res.isDefault = info.hasDefault;
13692            res.labelRes = info.labelRes;
13693            res.nonLocalizedLabel = info.nonLocalizedLabel;
13694            res.icon = info.icon;
13695            res.system = res.providerInfo.applicationInfo.isSystemApp();
13696            return res;
13697        }
13698
13699        @Override
13700        protected void sortResults(List<ResolveInfo> results) {
13701            Collections.sort(results, mResolvePrioritySorter);
13702        }
13703
13704        @Override
13705        protected void dumpFilter(PrintWriter out, String prefix,
13706                PackageParser.ProviderIntentInfo filter) {
13707            out.print(prefix);
13708            out.print(
13709                    Integer.toHexString(System.identityHashCode(filter.provider)));
13710            out.print(' ');
13711            filter.provider.printComponentShortName(out);
13712            out.print(" filter ");
13713            out.println(Integer.toHexString(System.identityHashCode(filter)));
13714        }
13715
13716        @Override
13717        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13718            return filter.provider;
13719        }
13720
13721        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13722            PackageParser.Provider provider = (PackageParser.Provider)label;
13723            out.print(prefix); out.print(
13724                    Integer.toHexString(System.identityHashCode(provider)));
13725                    out.print(' ');
13726                    provider.printComponentShortName(out);
13727            if (count > 1) {
13728                out.print(" ("); out.print(count); out.print(" filters)");
13729            }
13730            out.println();
13731        }
13732
13733        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13734                = new ArrayMap<ComponentName, PackageParser.Provider>();
13735        private int mFlags;
13736    }
13737
13738    static final class EphemeralIntentResolver
13739            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13740        /**
13741         * The result that has the highest defined order. Ordering applies on a
13742         * per-package basis. Mapping is from package name to Pair of order and
13743         * EphemeralResolveInfo.
13744         * <p>
13745         * NOTE: This is implemented as a field variable for convenience and efficiency.
13746         * By having a field variable, we're able to track filter ordering as soon as
13747         * a non-zero order is defined. Otherwise, multiple loops across the result set
13748         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13749         * this needs to be contained entirely within {@link #filterResults}.
13750         */
13751        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13752
13753        @Override
13754        protected AuxiliaryResolveInfo[] newArray(int size) {
13755            return new AuxiliaryResolveInfo[size];
13756        }
13757
13758        @Override
13759        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13760            return true;
13761        }
13762
13763        @Override
13764        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13765                int userId) {
13766            if (!sUserManager.exists(userId)) {
13767                return null;
13768            }
13769            final String packageName = responseObj.resolveInfo.getPackageName();
13770            final Integer order = responseObj.getOrder();
13771            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13772                    mOrderResult.get(packageName);
13773            // ordering is enabled and this item's order isn't high enough
13774            if (lastOrderResult != null && lastOrderResult.first >= order) {
13775                return null;
13776            }
13777            final InstantAppResolveInfo res = responseObj.resolveInfo;
13778            if (order > 0) {
13779                // non-zero order, enable ordering
13780                mOrderResult.put(packageName, new Pair<>(order, res));
13781            }
13782            return responseObj;
13783        }
13784
13785        @Override
13786        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13787            // only do work if ordering is enabled [most of the time it won't be]
13788            if (mOrderResult.size() == 0) {
13789                return;
13790            }
13791            int resultSize = results.size();
13792            for (int i = 0; i < resultSize; i++) {
13793                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13794                final String packageName = info.getPackageName();
13795                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13796                if (savedInfo == null) {
13797                    // package doesn't having ordering
13798                    continue;
13799                }
13800                if (savedInfo.second == info) {
13801                    // circled back to the highest ordered item; remove from order list
13802                    mOrderResult.remove(packageName);
13803                    if (mOrderResult.size() == 0) {
13804                        // no more ordered items
13805                        break;
13806                    }
13807                    continue;
13808                }
13809                // item has a worse order, remove it from the result list
13810                results.remove(i);
13811                resultSize--;
13812                i--;
13813            }
13814        }
13815    }
13816
13817    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13818            new Comparator<ResolveInfo>() {
13819        public int compare(ResolveInfo r1, ResolveInfo r2) {
13820            int v1 = r1.priority;
13821            int v2 = r2.priority;
13822            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13823            if (v1 != v2) {
13824                return (v1 > v2) ? -1 : 1;
13825            }
13826            v1 = r1.preferredOrder;
13827            v2 = r2.preferredOrder;
13828            if (v1 != v2) {
13829                return (v1 > v2) ? -1 : 1;
13830            }
13831            if (r1.isDefault != r2.isDefault) {
13832                return r1.isDefault ? -1 : 1;
13833            }
13834            v1 = r1.match;
13835            v2 = r2.match;
13836            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13837            if (v1 != v2) {
13838                return (v1 > v2) ? -1 : 1;
13839            }
13840            if (r1.system != r2.system) {
13841                return r1.system ? -1 : 1;
13842            }
13843            if (r1.activityInfo != null) {
13844                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13845            }
13846            if (r1.serviceInfo != null) {
13847                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13848            }
13849            if (r1.providerInfo != null) {
13850                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13851            }
13852            return 0;
13853        }
13854    };
13855
13856    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13857            new Comparator<ProviderInfo>() {
13858        public int compare(ProviderInfo p1, ProviderInfo p2) {
13859            final int v1 = p1.initOrder;
13860            final int v2 = p2.initOrder;
13861            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13862        }
13863    };
13864
13865    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13866            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13867            final int[] userIds) {
13868        mHandler.post(new Runnable() {
13869            @Override
13870            public void run() {
13871                try {
13872                    final IActivityManager am = ActivityManager.getService();
13873                    if (am == null) return;
13874                    final int[] resolvedUserIds;
13875                    if (userIds == null) {
13876                        resolvedUserIds = am.getRunningUserIds();
13877                    } else {
13878                        resolvedUserIds = userIds;
13879                    }
13880                    for (int id : resolvedUserIds) {
13881                        final Intent intent = new Intent(action,
13882                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13883                        if (extras != null) {
13884                            intent.putExtras(extras);
13885                        }
13886                        if (targetPkg != null) {
13887                            intent.setPackage(targetPkg);
13888                        }
13889                        // Modify the UID when posting to other users
13890                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13891                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13892                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13893                            intent.putExtra(Intent.EXTRA_UID, uid);
13894                        }
13895                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13896                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13897                        if (DEBUG_BROADCASTS) {
13898                            RuntimeException here = new RuntimeException("here");
13899                            here.fillInStackTrace();
13900                            Slog.d(TAG, "Sending to user " + id + ": "
13901                                    + intent.toShortString(false, true, false, false)
13902                                    + " " + intent.getExtras(), here);
13903                        }
13904                        am.broadcastIntent(null, intent, null, finishedReceiver,
13905                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13906                                null, finishedReceiver != null, false, id);
13907                    }
13908                } catch (RemoteException ex) {
13909                }
13910            }
13911        });
13912    }
13913
13914    /**
13915     * Check if the external storage media is available. This is true if there
13916     * is a mounted external storage medium or if the external storage is
13917     * emulated.
13918     */
13919    private boolean isExternalMediaAvailable() {
13920        return mMediaMounted || Environment.isExternalStorageEmulated();
13921    }
13922
13923    @Override
13924    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13925        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13926            return null;
13927        }
13928        // writer
13929        synchronized (mPackages) {
13930            if (!isExternalMediaAvailable()) {
13931                // If the external storage is no longer mounted at this point,
13932                // the caller may not have been able to delete all of this
13933                // packages files and can not delete any more.  Bail.
13934                return null;
13935            }
13936            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13937            if (lastPackage != null) {
13938                pkgs.remove(lastPackage);
13939            }
13940            if (pkgs.size() > 0) {
13941                return pkgs.get(0);
13942            }
13943        }
13944        return null;
13945    }
13946
13947    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13948        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13949                userId, andCode ? 1 : 0, packageName);
13950        if (mSystemReady) {
13951            msg.sendToTarget();
13952        } else {
13953            if (mPostSystemReadyMessages == null) {
13954                mPostSystemReadyMessages = new ArrayList<>();
13955            }
13956            mPostSystemReadyMessages.add(msg);
13957        }
13958    }
13959
13960    void startCleaningPackages() {
13961        // reader
13962        if (!isExternalMediaAvailable()) {
13963            return;
13964        }
13965        synchronized (mPackages) {
13966            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13967                return;
13968            }
13969        }
13970        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13971        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13972        IActivityManager am = ActivityManager.getService();
13973        if (am != null) {
13974            int dcsUid = -1;
13975            synchronized (mPackages) {
13976                if (!mDefaultContainerWhitelisted) {
13977                    mDefaultContainerWhitelisted = true;
13978                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13979                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13980                }
13981            }
13982            try {
13983                if (dcsUid > 0) {
13984                    am.backgroundWhitelistUid(dcsUid);
13985                }
13986                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13987                        UserHandle.USER_SYSTEM);
13988            } catch (RemoteException e) {
13989            }
13990        }
13991    }
13992
13993    @Override
13994    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13995            int installFlags, String installerPackageName, int userId) {
13996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13997
13998        final int callingUid = Binder.getCallingUid();
13999        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14000                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14001
14002        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14003            try {
14004                if (observer != null) {
14005                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14006                }
14007            } catch (RemoteException re) {
14008            }
14009            return;
14010        }
14011
14012        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14013            installFlags |= PackageManager.INSTALL_FROM_ADB;
14014
14015        } else {
14016            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14017            // about installerPackageName.
14018
14019            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14020            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14021        }
14022
14023        UserHandle user;
14024        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14025            user = UserHandle.ALL;
14026        } else {
14027            user = new UserHandle(userId);
14028        }
14029
14030        // Only system components can circumvent runtime permissions when installing.
14031        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14032                && mContext.checkCallingOrSelfPermission(Manifest.permission
14033                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14034            throw new SecurityException("You need the "
14035                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14036                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14037        }
14038
14039        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14040                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14041            throw new IllegalArgumentException(
14042                    "New installs into ASEC containers no longer supported");
14043        }
14044
14045        final File originFile = new File(originPath);
14046        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14047
14048        final Message msg = mHandler.obtainMessage(INIT_COPY);
14049        final VerificationInfo verificationInfo = new VerificationInfo(
14050                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14051        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14052                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14053                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14054                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14055        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14056        msg.obj = params;
14057
14058        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14059                System.identityHashCode(msg.obj));
14060        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14061                System.identityHashCode(msg.obj));
14062
14063        mHandler.sendMessage(msg);
14064    }
14065
14066
14067    /**
14068     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14069     * it is acting on behalf on an enterprise or the user).
14070     *
14071     * Note that the ordering of the conditionals in this method is important. The checks we perform
14072     * are as follows, in this order:
14073     *
14074     * 1) If the install is being performed by a system app, we can trust the app to have set the
14075     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14076     *    what it is.
14077     * 2) If the install is being performed by a device or profile owner app, the install reason
14078     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14079     *    set the install reason correctly. If the app targets an older SDK version where install
14080     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14081     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14082     * 3) In all other cases, the install is being performed by a regular app that is neither part
14083     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14084     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14085     *    set to enterprise policy and if so, change it to unknown instead.
14086     */
14087    private int fixUpInstallReason(String installerPackageName, int installerUid,
14088            int installReason) {
14089        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14090                == PERMISSION_GRANTED) {
14091            // If the install is being performed by a system app, we trust that app to have set the
14092            // install reason correctly.
14093            return installReason;
14094        }
14095
14096        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14097            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14098        if (dpm != null) {
14099            ComponentName owner = null;
14100            try {
14101                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14102                if (owner == null) {
14103                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14104                }
14105            } catch (RemoteException e) {
14106            }
14107            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14108                // If the install is being performed by a device or profile owner, the install
14109                // reason should be enterprise policy.
14110                return PackageManager.INSTALL_REASON_POLICY;
14111            }
14112        }
14113
14114        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14115            // If the install is being performed by a regular app (i.e. neither system app nor
14116            // device or profile owner), we have no reason to believe that the app is acting on
14117            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14118            // change it to unknown instead.
14119            return PackageManager.INSTALL_REASON_UNKNOWN;
14120        }
14121
14122        // If the install is being performed by a regular app and the install reason was set to any
14123        // value but enterprise policy, leave the install reason unchanged.
14124        return installReason;
14125    }
14126
14127    void installStage(String packageName, File stagedDir,
14128            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14129            String installerPackageName, int installerUid, UserHandle user,
14130            Certificate[][] certificates) {
14131        if (DEBUG_EPHEMERAL) {
14132            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14133                Slog.d(TAG, "Ephemeral install of " + packageName);
14134            }
14135        }
14136        final VerificationInfo verificationInfo = new VerificationInfo(
14137                sessionParams.originatingUri, sessionParams.referrerUri,
14138                sessionParams.originatingUid, installerUid);
14139
14140        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
14141
14142        final Message msg = mHandler.obtainMessage(INIT_COPY);
14143        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14144                sessionParams.installReason);
14145        final InstallParams params = new InstallParams(origin, null, observer,
14146                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14147                verificationInfo, user, sessionParams.abiOverride,
14148                sessionParams.grantedRuntimePermissions, certificates, installReason);
14149        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14150        msg.obj = params;
14151
14152        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14153                System.identityHashCode(msg.obj));
14154        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14155                System.identityHashCode(msg.obj));
14156
14157        mHandler.sendMessage(msg);
14158    }
14159
14160    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14161            int userId) {
14162        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14163        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14164                false /*startReceiver*/, pkgSetting.appId, userId);
14165
14166        // Send a session commit broadcast
14167        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14168        info.installReason = pkgSetting.getInstallReason(userId);
14169        info.appPackageName = packageName;
14170        sendSessionCommitBroadcast(info, userId);
14171    }
14172
14173    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14174            boolean includeStopped, int appId, int... userIds) {
14175        if (ArrayUtils.isEmpty(userIds)) {
14176            return;
14177        }
14178        Bundle extras = new Bundle(1);
14179        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14180        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14181
14182        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14183                packageName, extras, 0, null, null, userIds);
14184        if (sendBootCompleted) {
14185            mHandler.post(() -> {
14186                        for (int userId : userIds) {
14187                            sendBootCompletedBroadcastToSystemApp(
14188                                    packageName, includeStopped, userId);
14189                        }
14190                    }
14191            );
14192        }
14193    }
14194
14195    /**
14196     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14197     * automatically without needing an explicit launch.
14198     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14199     */
14200    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14201            int userId) {
14202        // If user is not running, the app didn't miss any broadcast
14203        if (!mUserManagerInternal.isUserRunning(userId)) {
14204            return;
14205        }
14206        final IActivityManager am = ActivityManager.getService();
14207        try {
14208            // Deliver LOCKED_BOOT_COMPLETED first
14209            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14210                    .setPackage(packageName);
14211            if (includeStopped) {
14212                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14213            }
14214            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14215            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14216                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14217
14218            // Deliver BOOT_COMPLETED only if user is unlocked
14219            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14220                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14221                if (includeStopped) {
14222                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14223                }
14224                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14225                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14226            }
14227        } catch (RemoteException e) {
14228            throw e.rethrowFromSystemServer();
14229        }
14230    }
14231
14232    @Override
14233    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14234            int userId) {
14235        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14236        PackageSetting pkgSetting;
14237        final int callingUid = Binder.getCallingUid();
14238        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14239                true /* requireFullPermission */, true /* checkShell */,
14240                "setApplicationHiddenSetting for user " + userId);
14241
14242        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14243            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14244            return false;
14245        }
14246
14247        long callingId = Binder.clearCallingIdentity();
14248        try {
14249            boolean sendAdded = false;
14250            boolean sendRemoved = false;
14251            // writer
14252            synchronized (mPackages) {
14253                pkgSetting = mSettings.mPackages.get(packageName);
14254                if (pkgSetting == null) {
14255                    return false;
14256                }
14257                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14258                    return false;
14259                }
14260                // Do not allow "android" is being disabled
14261                if ("android".equals(packageName)) {
14262                    Slog.w(TAG, "Cannot hide package: android");
14263                    return false;
14264                }
14265                // Cannot hide static shared libs as they are considered
14266                // a part of the using app (emulating static linking). Also
14267                // static libs are installed always on internal storage.
14268                PackageParser.Package pkg = mPackages.get(packageName);
14269                if (pkg != null && pkg.staticSharedLibName != null) {
14270                    Slog.w(TAG, "Cannot hide package: " + packageName
14271                            + " providing static shared library: "
14272                            + pkg.staticSharedLibName);
14273                    return false;
14274                }
14275                // Only allow protected packages to hide themselves.
14276                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14277                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14278                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14279                    return false;
14280                }
14281
14282                if (pkgSetting.getHidden(userId) != hidden) {
14283                    pkgSetting.setHidden(hidden, userId);
14284                    mSettings.writePackageRestrictionsLPr(userId);
14285                    if (hidden) {
14286                        sendRemoved = true;
14287                    } else {
14288                        sendAdded = true;
14289                    }
14290                }
14291            }
14292            if (sendAdded) {
14293                sendPackageAddedForUser(packageName, pkgSetting, userId);
14294                return true;
14295            }
14296            if (sendRemoved) {
14297                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14298                        "hiding pkg");
14299                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14300                return true;
14301            }
14302        } finally {
14303            Binder.restoreCallingIdentity(callingId);
14304        }
14305        return false;
14306    }
14307
14308    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14309            int userId) {
14310        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14311        info.removedPackage = packageName;
14312        info.installerPackageName = pkgSetting.installerPackageName;
14313        info.removedUsers = new int[] {userId};
14314        info.broadcastUsers = new int[] {userId};
14315        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14316        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14317    }
14318
14319    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14320        if (pkgList.length > 0) {
14321            Bundle extras = new Bundle(1);
14322            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14323
14324            sendPackageBroadcast(
14325                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14326                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14327                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14328                    new int[] {userId});
14329        }
14330    }
14331
14332    /**
14333     * Returns true if application is not found or there was an error. Otherwise it returns
14334     * the hidden state of the package for the given user.
14335     */
14336    @Override
14337    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14338        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14339        final int callingUid = Binder.getCallingUid();
14340        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14341                true /* requireFullPermission */, false /* checkShell */,
14342                "getApplicationHidden for user " + userId);
14343        PackageSetting ps;
14344        long callingId = Binder.clearCallingIdentity();
14345        try {
14346            // writer
14347            synchronized (mPackages) {
14348                ps = mSettings.mPackages.get(packageName);
14349                if (ps == null) {
14350                    return true;
14351                }
14352                if (filterAppAccessLPr(ps, callingUid, userId)) {
14353                    return true;
14354                }
14355                return ps.getHidden(userId);
14356            }
14357        } finally {
14358            Binder.restoreCallingIdentity(callingId);
14359        }
14360    }
14361
14362    /**
14363     * @hide
14364     */
14365    @Override
14366    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14367            int installReason) {
14368        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14369                null);
14370        PackageSetting pkgSetting;
14371        final int callingUid = Binder.getCallingUid();
14372        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14373                true /* requireFullPermission */, true /* checkShell */,
14374                "installExistingPackage for user " + userId);
14375        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14376            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14377        }
14378
14379        long callingId = Binder.clearCallingIdentity();
14380        try {
14381            boolean installed = false;
14382            final boolean instantApp =
14383                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14384            final boolean fullApp =
14385                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14386
14387            // writer
14388            synchronized (mPackages) {
14389                pkgSetting = mSettings.mPackages.get(packageName);
14390                if (pkgSetting == null) {
14391                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14392                }
14393                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14394                    // only allow the existing package to be used if it's installed as a full
14395                    // application for at least one user
14396                    boolean installAllowed = false;
14397                    for (int checkUserId : sUserManager.getUserIds()) {
14398                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14399                        if (installAllowed) {
14400                            break;
14401                        }
14402                    }
14403                    if (!installAllowed) {
14404                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14405                    }
14406                }
14407                if (!pkgSetting.getInstalled(userId)) {
14408                    pkgSetting.setInstalled(true, userId);
14409                    pkgSetting.setHidden(false, userId);
14410                    pkgSetting.setInstallReason(installReason, userId);
14411                    mSettings.writePackageRestrictionsLPr(userId);
14412                    mSettings.writeKernelMappingLPr(pkgSetting);
14413                    installed = true;
14414                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14415                    // upgrade app from instant to full; we don't allow app downgrade
14416                    installed = true;
14417                }
14418                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14419            }
14420
14421            if (installed) {
14422                if (pkgSetting.pkg != null) {
14423                    synchronized (mInstallLock) {
14424                        // We don't need to freeze for a brand new install
14425                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14426                    }
14427                }
14428                sendPackageAddedForUser(packageName, pkgSetting, userId);
14429                synchronized (mPackages) {
14430                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14431                }
14432            }
14433        } finally {
14434            Binder.restoreCallingIdentity(callingId);
14435        }
14436
14437        return PackageManager.INSTALL_SUCCEEDED;
14438    }
14439
14440    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14441            boolean instantApp, boolean fullApp) {
14442        // no state specified; do nothing
14443        if (!instantApp && !fullApp) {
14444            return;
14445        }
14446        if (userId != UserHandle.USER_ALL) {
14447            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14448                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14449            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14450                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14451            }
14452        } else {
14453            for (int currentUserId : sUserManager.getUserIds()) {
14454                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14455                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14456                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14457                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14458                }
14459            }
14460        }
14461    }
14462
14463    boolean isUserRestricted(int userId, String restrictionKey) {
14464        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14465        if (restrictions.getBoolean(restrictionKey, false)) {
14466            Log.w(TAG, "User is restricted: " + restrictionKey);
14467            return true;
14468        }
14469        return false;
14470    }
14471
14472    @Override
14473    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14474            int userId) {
14475        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14476        final int callingUid = Binder.getCallingUid();
14477        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14478                true /* requireFullPermission */, true /* checkShell */,
14479                "setPackagesSuspended for user " + userId);
14480
14481        if (ArrayUtils.isEmpty(packageNames)) {
14482            return packageNames;
14483        }
14484
14485        // List of package names for whom the suspended state has changed.
14486        List<String> changedPackages = new ArrayList<>(packageNames.length);
14487        // List of package names for whom the suspended state is not set as requested in this
14488        // method.
14489        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14490        long callingId = Binder.clearCallingIdentity();
14491        try {
14492            for (int i = 0; i < packageNames.length; i++) {
14493                String packageName = packageNames[i];
14494                boolean changed = false;
14495                final int appId;
14496                synchronized (mPackages) {
14497                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14498                    if (pkgSetting == null
14499                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14500                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14501                                + "\". Skipping suspending/un-suspending.");
14502                        unactionedPackages.add(packageName);
14503                        continue;
14504                    }
14505                    appId = pkgSetting.appId;
14506                    if (pkgSetting.getSuspended(userId) != suspended) {
14507                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14508                            unactionedPackages.add(packageName);
14509                            continue;
14510                        }
14511                        pkgSetting.setSuspended(suspended, userId);
14512                        mSettings.writePackageRestrictionsLPr(userId);
14513                        changed = true;
14514                        changedPackages.add(packageName);
14515                    }
14516                }
14517
14518                if (changed && suspended) {
14519                    killApplication(packageName, UserHandle.getUid(userId, appId),
14520                            "suspending package");
14521                }
14522            }
14523        } finally {
14524            Binder.restoreCallingIdentity(callingId);
14525        }
14526
14527        if (!changedPackages.isEmpty()) {
14528            sendPackagesSuspendedForUser(changedPackages.toArray(
14529                    new String[changedPackages.size()]), userId, suspended);
14530        }
14531
14532        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14533    }
14534
14535    @Override
14536    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14537        final int callingUid = Binder.getCallingUid();
14538        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14539                true /* requireFullPermission */, false /* checkShell */,
14540                "isPackageSuspendedForUser for user " + userId);
14541        synchronized (mPackages) {
14542            final PackageSetting ps = mSettings.mPackages.get(packageName);
14543            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14544                throw new IllegalArgumentException("Unknown target package: " + packageName);
14545            }
14546            return ps.getSuspended(userId);
14547        }
14548    }
14549
14550    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14551        if (isPackageDeviceAdmin(packageName, userId)) {
14552            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14553                    + "\": has an active device admin");
14554            return false;
14555        }
14556
14557        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14558        if (packageName.equals(activeLauncherPackageName)) {
14559            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14560                    + "\": contains the active launcher");
14561            return false;
14562        }
14563
14564        if (packageName.equals(mRequiredInstallerPackage)) {
14565            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14566                    + "\": required for package installation");
14567            return false;
14568        }
14569
14570        if (packageName.equals(mRequiredUninstallerPackage)) {
14571            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14572                    + "\": required for package uninstallation");
14573            return false;
14574        }
14575
14576        if (packageName.equals(mRequiredVerifierPackage)) {
14577            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14578                    + "\": required for package verification");
14579            return false;
14580        }
14581
14582        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14583            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14584                    + "\": is the default dialer");
14585            return false;
14586        }
14587
14588        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14589            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14590                    + "\": protected package");
14591            return false;
14592        }
14593
14594        // Cannot suspend static shared libs as they are considered
14595        // a part of the using app (emulating static linking). Also
14596        // static libs are installed always on internal storage.
14597        PackageParser.Package pkg = mPackages.get(packageName);
14598        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14599            Slog.w(TAG, "Cannot suspend package: " + packageName
14600                    + " providing static shared library: "
14601                    + pkg.staticSharedLibName);
14602            return false;
14603        }
14604
14605        return true;
14606    }
14607
14608    private String getActiveLauncherPackageName(int userId) {
14609        Intent intent = new Intent(Intent.ACTION_MAIN);
14610        intent.addCategory(Intent.CATEGORY_HOME);
14611        ResolveInfo resolveInfo = resolveIntent(
14612                intent,
14613                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14614                PackageManager.MATCH_DEFAULT_ONLY,
14615                userId);
14616
14617        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14618    }
14619
14620    private String getDefaultDialerPackageName(int userId) {
14621        synchronized (mPackages) {
14622            return mSettings.getDefaultDialerPackageNameLPw(userId);
14623        }
14624    }
14625
14626    @Override
14627    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14628        mContext.enforceCallingOrSelfPermission(
14629                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14630                "Only package verification agents can verify applications");
14631
14632        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14633        final PackageVerificationResponse response = new PackageVerificationResponse(
14634                verificationCode, Binder.getCallingUid());
14635        msg.arg1 = id;
14636        msg.obj = response;
14637        mHandler.sendMessage(msg);
14638    }
14639
14640    @Override
14641    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14642            long millisecondsToDelay) {
14643        mContext.enforceCallingOrSelfPermission(
14644                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14645                "Only package verification agents can extend verification timeouts");
14646
14647        final PackageVerificationState state = mPendingVerification.get(id);
14648        final PackageVerificationResponse response = new PackageVerificationResponse(
14649                verificationCodeAtTimeout, Binder.getCallingUid());
14650
14651        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14652            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14653        }
14654        if (millisecondsToDelay < 0) {
14655            millisecondsToDelay = 0;
14656        }
14657        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14658                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14659            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14660        }
14661
14662        if ((state != null) && !state.timeoutExtended()) {
14663            state.extendTimeout();
14664
14665            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14666            msg.arg1 = id;
14667            msg.obj = response;
14668            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14669        }
14670    }
14671
14672    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14673            int verificationCode, UserHandle user) {
14674        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14675        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14676        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14677        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14678        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14679
14680        mContext.sendBroadcastAsUser(intent, user,
14681                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14682    }
14683
14684    private ComponentName matchComponentForVerifier(String packageName,
14685            List<ResolveInfo> receivers) {
14686        ActivityInfo targetReceiver = null;
14687
14688        final int NR = receivers.size();
14689        for (int i = 0; i < NR; i++) {
14690            final ResolveInfo info = receivers.get(i);
14691            if (info.activityInfo == null) {
14692                continue;
14693            }
14694
14695            if (packageName.equals(info.activityInfo.packageName)) {
14696                targetReceiver = info.activityInfo;
14697                break;
14698            }
14699        }
14700
14701        if (targetReceiver == null) {
14702            return null;
14703        }
14704
14705        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14706    }
14707
14708    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14709            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14710        if (pkgInfo.verifiers.length == 0) {
14711            return null;
14712        }
14713
14714        final int N = pkgInfo.verifiers.length;
14715        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14716        for (int i = 0; i < N; i++) {
14717            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14718
14719            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14720                    receivers);
14721            if (comp == null) {
14722                continue;
14723            }
14724
14725            final int verifierUid = getUidForVerifier(verifierInfo);
14726            if (verifierUid == -1) {
14727                continue;
14728            }
14729
14730            if (DEBUG_VERIFY) {
14731                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14732                        + " with the correct signature");
14733            }
14734            sufficientVerifiers.add(comp);
14735            verificationState.addSufficientVerifier(verifierUid);
14736        }
14737
14738        return sufficientVerifiers;
14739    }
14740
14741    private int getUidForVerifier(VerifierInfo verifierInfo) {
14742        synchronized (mPackages) {
14743            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14744            if (pkg == null) {
14745                return -1;
14746            } else if (pkg.mSignatures.length != 1) {
14747                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14748                        + " has more than one signature; ignoring");
14749                return -1;
14750            }
14751
14752            /*
14753             * If the public key of the package's signature does not match
14754             * our expected public key, then this is a different package and
14755             * we should skip.
14756             */
14757
14758            final byte[] expectedPublicKey;
14759            try {
14760                final Signature verifierSig = pkg.mSignatures[0];
14761                final PublicKey publicKey = verifierSig.getPublicKey();
14762                expectedPublicKey = publicKey.getEncoded();
14763            } catch (CertificateException e) {
14764                return -1;
14765            }
14766
14767            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14768
14769            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14770                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14771                        + " does not have the expected public key; ignoring");
14772                return -1;
14773            }
14774
14775            return pkg.applicationInfo.uid;
14776        }
14777    }
14778
14779    @Override
14780    public void finishPackageInstall(int token, boolean didLaunch) {
14781        enforceSystemOrRoot("Only the system is allowed to finish installs");
14782
14783        if (DEBUG_INSTALL) {
14784            Slog.v(TAG, "BM finishing package install for " + token);
14785        }
14786        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14787
14788        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14789        mHandler.sendMessage(msg);
14790    }
14791
14792    /**
14793     * Get the verification agent timeout.  Used for both the APK verifier and the
14794     * intent filter verifier.
14795     *
14796     * @return verification timeout in milliseconds
14797     */
14798    private long getVerificationTimeout() {
14799        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14800                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14801                DEFAULT_VERIFICATION_TIMEOUT);
14802    }
14803
14804    /**
14805     * Get the default verification agent response code.
14806     *
14807     * @return default verification response code
14808     */
14809    private int getDefaultVerificationResponse(UserHandle user) {
14810        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14811            return PackageManager.VERIFICATION_REJECT;
14812        }
14813        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14814                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14815                DEFAULT_VERIFICATION_RESPONSE);
14816    }
14817
14818    /**
14819     * Check whether or not package verification has been enabled.
14820     *
14821     * @return true if verification should be performed
14822     */
14823    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14824        if (!DEFAULT_VERIFY_ENABLE) {
14825            return false;
14826        }
14827
14828        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14829
14830        // Check if installing from ADB
14831        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14832            // Do not run verification in a test harness environment
14833            if (ActivityManager.isRunningInTestHarness()) {
14834                return false;
14835            }
14836            if (ensureVerifyAppsEnabled) {
14837                return true;
14838            }
14839            // Check if the developer does not want package verification for ADB installs
14840            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14841                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14842                return false;
14843            }
14844        } else {
14845            // only when not installed from ADB, skip verification for instant apps when
14846            // the installer and verifier are the same.
14847            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14848                if (mInstantAppInstallerActivity != null
14849                        && mInstantAppInstallerActivity.packageName.equals(
14850                                mRequiredVerifierPackage)) {
14851                    try {
14852                        mContext.getSystemService(AppOpsManager.class)
14853                                .checkPackage(installerUid, mRequiredVerifierPackage);
14854                        if (DEBUG_VERIFY) {
14855                            Slog.i(TAG, "disable verification for instant app");
14856                        }
14857                        return false;
14858                    } catch (SecurityException ignore) { }
14859                }
14860            }
14861        }
14862
14863        if (ensureVerifyAppsEnabled) {
14864            return true;
14865        }
14866
14867        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14868                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14869    }
14870
14871    @Override
14872    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14873            throws RemoteException {
14874        mContext.enforceCallingOrSelfPermission(
14875                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14876                "Only intentfilter verification agents can verify applications");
14877
14878        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14879        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14880                Binder.getCallingUid(), verificationCode, failedDomains);
14881        msg.arg1 = id;
14882        msg.obj = response;
14883        mHandler.sendMessage(msg);
14884    }
14885
14886    @Override
14887    public int getIntentVerificationStatus(String packageName, int userId) {
14888        final int callingUid = Binder.getCallingUid();
14889        if (UserHandle.getUserId(callingUid) != userId) {
14890            mContext.enforceCallingOrSelfPermission(
14891                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14892                    "getIntentVerificationStatus" + userId);
14893        }
14894        if (getInstantAppPackageName(callingUid) != null) {
14895            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14896        }
14897        synchronized (mPackages) {
14898            final PackageSetting ps = mSettings.mPackages.get(packageName);
14899            if (ps == null
14900                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14901                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14902            }
14903            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14904        }
14905    }
14906
14907    @Override
14908    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14909        mContext.enforceCallingOrSelfPermission(
14910                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14911
14912        boolean result = false;
14913        synchronized (mPackages) {
14914            final PackageSetting ps = mSettings.mPackages.get(packageName);
14915            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14916                return false;
14917            }
14918            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14919        }
14920        if (result) {
14921            scheduleWritePackageRestrictionsLocked(userId);
14922        }
14923        return result;
14924    }
14925
14926    @Override
14927    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14928            String packageName) {
14929        final int callingUid = Binder.getCallingUid();
14930        if (getInstantAppPackageName(callingUid) != null) {
14931            return ParceledListSlice.emptyList();
14932        }
14933        synchronized (mPackages) {
14934            final PackageSetting ps = mSettings.mPackages.get(packageName);
14935            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14936                return ParceledListSlice.emptyList();
14937            }
14938            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14939        }
14940    }
14941
14942    @Override
14943    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14944        if (TextUtils.isEmpty(packageName)) {
14945            return ParceledListSlice.emptyList();
14946        }
14947        final int callingUid = Binder.getCallingUid();
14948        final int callingUserId = UserHandle.getUserId(callingUid);
14949        synchronized (mPackages) {
14950            PackageParser.Package pkg = mPackages.get(packageName);
14951            if (pkg == null || pkg.activities == null) {
14952                return ParceledListSlice.emptyList();
14953            }
14954            if (pkg.mExtras == null) {
14955                return ParceledListSlice.emptyList();
14956            }
14957            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14958            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14959                return ParceledListSlice.emptyList();
14960            }
14961            final int count = pkg.activities.size();
14962            ArrayList<IntentFilter> result = new ArrayList<>();
14963            for (int n=0; n<count; n++) {
14964                PackageParser.Activity activity = pkg.activities.get(n);
14965                if (activity.intents != null && activity.intents.size() > 0) {
14966                    result.addAll(activity.intents);
14967                }
14968            }
14969            return new ParceledListSlice<>(result);
14970        }
14971    }
14972
14973    @Override
14974    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14975        mContext.enforceCallingOrSelfPermission(
14976                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14977        if (UserHandle.getCallingUserId() != userId) {
14978            mContext.enforceCallingOrSelfPermission(
14979                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14980        }
14981
14982        synchronized (mPackages) {
14983            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14984            if (packageName != null) {
14985                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14986                        packageName, userId);
14987            }
14988            return result;
14989        }
14990    }
14991
14992    @Override
14993    public String getDefaultBrowserPackageName(int userId) {
14994        if (UserHandle.getCallingUserId() != userId) {
14995            mContext.enforceCallingOrSelfPermission(
14996                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14997        }
14998        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14999            return null;
15000        }
15001        synchronized (mPackages) {
15002            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15003        }
15004    }
15005
15006    /**
15007     * Get the "allow unknown sources" setting.
15008     *
15009     * @return the current "allow unknown sources" setting
15010     */
15011    private int getUnknownSourcesSettings() {
15012        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15013                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15014                -1);
15015    }
15016
15017    @Override
15018    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15019        final int callingUid = Binder.getCallingUid();
15020        if (getInstantAppPackageName(callingUid) != null) {
15021            return;
15022        }
15023        // writer
15024        synchronized (mPackages) {
15025            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15026            if (targetPackageSetting == null
15027                    || filterAppAccessLPr(
15028                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15029                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15030            }
15031
15032            PackageSetting installerPackageSetting;
15033            if (installerPackageName != null) {
15034                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15035                if (installerPackageSetting == null) {
15036                    throw new IllegalArgumentException("Unknown installer package: "
15037                            + installerPackageName);
15038                }
15039            } else {
15040                installerPackageSetting = null;
15041            }
15042
15043            Signature[] callerSignature;
15044            Object obj = mSettings.getUserIdLPr(callingUid);
15045            if (obj != null) {
15046                if (obj instanceof SharedUserSetting) {
15047                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15048                } else if (obj instanceof PackageSetting) {
15049                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15050                } else {
15051                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15052                }
15053            } else {
15054                throw new SecurityException("Unknown calling UID: " + callingUid);
15055            }
15056
15057            // Verify: can't set installerPackageName to a package that is
15058            // not signed with the same cert as the caller.
15059            if (installerPackageSetting != null) {
15060                if (compareSignatures(callerSignature,
15061                        installerPackageSetting.signatures.mSignatures)
15062                        != PackageManager.SIGNATURE_MATCH) {
15063                    throw new SecurityException(
15064                            "Caller does not have same cert as new installer package "
15065                            + installerPackageName);
15066                }
15067            }
15068
15069            // Verify: if target already has an installer package, it must
15070            // be signed with the same cert as the caller.
15071            if (targetPackageSetting.installerPackageName != null) {
15072                PackageSetting setting = mSettings.mPackages.get(
15073                        targetPackageSetting.installerPackageName);
15074                // If the currently set package isn't valid, then it's always
15075                // okay to change it.
15076                if (setting != null) {
15077                    if (compareSignatures(callerSignature,
15078                            setting.signatures.mSignatures)
15079                            != PackageManager.SIGNATURE_MATCH) {
15080                        throw new SecurityException(
15081                                "Caller does not have same cert as old installer package "
15082                                + targetPackageSetting.installerPackageName);
15083                    }
15084                }
15085            }
15086
15087            // Okay!
15088            targetPackageSetting.installerPackageName = installerPackageName;
15089            if (installerPackageName != null) {
15090                mSettings.mInstallerPackages.add(installerPackageName);
15091            }
15092            scheduleWriteSettingsLocked();
15093        }
15094    }
15095
15096    @Override
15097    public void setApplicationCategoryHint(String packageName, int categoryHint,
15098            String callerPackageName) {
15099        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15100            throw new SecurityException("Instant applications don't have access to this method");
15101        }
15102        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15103                callerPackageName);
15104        synchronized (mPackages) {
15105            PackageSetting ps = mSettings.mPackages.get(packageName);
15106            if (ps == null) {
15107                throw new IllegalArgumentException("Unknown target package " + packageName);
15108            }
15109            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15110                throw new IllegalArgumentException("Unknown target package " + packageName);
15111            }
15112            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15113                throw new IllegalArgumentException("Calling package " + callerPackageName
15114                        + " is not installer for " + packageName);
15115            }
15116
15117            if (ps.categoryHint != categoryHint) {
15118                ps.categoryHint = categoryHint;
15119                scheduleWriteSettingsLocked();
15120            }
15121        }
15122    }
15123
15124    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15125        // Queue up an async operation since the package installation may take a little while.
15126        mHandler.post(new Runnable() {
15127            public void run() {
15128                mHandler.removeCallbacks(this);
15129                 // Result object to be returned
15130                PackageInstalledInfo res = new PackageInstalledInfo();
15131                res.setReturnCode(currentStatus);
15132                res.uid = -1;
15133                res.pkg = null;
15134                res.removedInfo = null;
15135                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15136                    args.doPreInstall(res.returnCode);
15137                    synchronized (mInstallLock) {
15138                        installPackageTracedLI(args, res);
15139                    }
15140                    args.doPostInstall(res.returnCode, res.uid);
15141                }
15142
15143                // A restore should be performed at this point if (a) the install
15144                // succeeded, (b) the operation is not an update, and (c) the new
15145                // package has not opted out of backup participation.
15146                final boolean update = res.removedInfo != null
15147                        && res.removedInfo.removedPackage != null;
15148                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15149                boolean doRestore = !update
15150                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15151
15152                // Set up the post-install work request bookkeeping.  This will be used
15153                // and cleaned up by the post-install event handling regardless of whether
15154                // there's a restore pass performed.  Token values are >= 1.
15155                int token;
15156                if (mNextInstallToken < 0) mNextInstallToken = 1;
15157                token = mNextInstallToken++;
15158
15159                PostInstallData data = new PostInstallData(args, res);
15160                mRunningInstalls.put(token, data);
15161                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15162
15163                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15164                    // Pass responsibility to the Backup Manager.  It will perform a
15165                    // restore if appropriate, then pass responsibility back to the
15166                    // Package Manager to run the post-install observer callbacks
15167                    // and broadcasts.
15168                    IBackupManager bm = IBackupManager.Stub.asInterface(
15169                            ServiceManager.getService(Context.BACKUP_SERVICE));
15170                    if (bm != null) {
15171                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15172                                + " to BM for possible restore");
15173                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15174                        try {
15175                            // TODO: http://b/22388012
15176                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15177                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15178                            } else {
15179                                doRestore = false;
15180                            }
15181                        } catch (RemoteException e) {
15182                            // can't happen; the backup manager is local
15183                        } catch (Exception e) {
15184                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15185                            doRestore = false;
15186                        }
15187                    } else {
15188                        Slog.e(TAG, "Backup Manager not found!");
15189                        doRestore = false;
15190                    }
15191                }
15192
15193                if (!doRestore) {
15194                    // No restore possible, or the Backup Manager was mysteriously not
15195                    // available -- just fire the post-install work request directly.
15196                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15197
15198                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15199
15200                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15201                    mHandler.sendMessage(msg);
15202                }
15203            }
15204        });
15205    }
15206
15207    /**
15208     * Callback from PackageSettings whenever an app is first transitioned out of the
15209     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15210     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15211     * here whether the app is the target of an ongoing install, and only send the
15212     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15213     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15214     * handling.
15215     */
15216    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15217        // Serialize this with the rest of the install-process message chain.  In the
15218        // restore-at-install case, this Runnable will necessarily run before the
15219        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15220        // are coherent.  In the non-restore case, the app has already completed install
15221        // and been launched through some other means, so it is not in a problematic
15222        // state for observers to see the FIRST_LAUNCH signal.
15223        mHandler.post(new Runnable() {
15224            @Override
15225            public void run() {
15226                for (int i = 0; i < mRunningInstalls.size(); i++) {
15227                    final PostInstallData data = mRunningInstalls.valueAt(i);
15228                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15229                        continue;
15230                    }
15231                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15232                        // right package; but is it for the right user?
15233                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15234                            if (userId == data.res.newUsers[uIndex]) {
15235                                if (DEBUG_BACKUP) {
15236                                    Slog.i(TAG, "Package " + pkgName
15237                                            + " being restored so deferring FIRST_LAUNCH");
15238                                }
15239                                return;
15240                            }
15241                        }
15242                    }
15243                }
15244                // didn't find it, so not being restored
15245                if (DEBUG_BACKUP) {
15246                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15247                }
15248                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15249            }
15250        });
15251    }
15252
15253    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15254        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15255                installerPkg, null, userIds);
15256    }
15257
15258    private abstract class HandlerParams {
15259        private static final int MAX_RETRIES = 4;
15260
15261        /**
15262         * Number of times startCopy() has been attempted and had a non-fatal
15263         * error.
15264         */
15265        private int mRetries = 0;
15266
15267        /** User handle for the user requesting the information or installation. */
15268        private final UserHandle mUser;
15269        String traceMethod;
15270        int traceCookie;
15271
15272        HandlerParams(UserHandle user) {
15273            mUser = user;
15274        }
15275
15276        UserHandle getUser() {
15277            return mUser;
15278        }
15279
15280        HandlerParams setTraceMethod(String traceMethod) {
15281            this.traceMethod = traceMethod;
15282            return this;
15283        }
15284
15285        HandlerParams setTraceCookie(int traceCookie) {
15286            this.traceCookie = traceCookie;
15287            return this;
15288        }
15289
15290        final boolean startCopy() {
15291            boolean res;
15292            try {
15293                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15294
15295                if (++mRetries > MAX_RETRIES) {
15296                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15297                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15298                    handleServiceError();
15299                    return false;
15300                } else {
15301                    handleStartCopy();
15302                    res = true;
15303                }
15304            } catch (RemoteException e) {
15305                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15306                mHandler.sendEmptyMessage(MCS_RECONNECT);
15307                res = false;
15308            }
15309            handleReturnCode();
15310            return res;
15311        }
15312
15313        final void serviceError() {
15314            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15315            handleServiceError();
15316            handleReturnCode();
15317        }
15318
15319        abstract void handleStartCopy() throws RemoteException;
15320        abstract void handleServiceError();
15321        abstract void handleReturnCode();
15322    }
15323
15324    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15325        for (File path : paths) {
15326            try {
15327                mcs.clearDirectory(path.getAbsolutePath());
15328            } catch (RemoteException e) {
15329            }
15330        }
15331    }
15332
15333    static class OriginInfo {
15334        /**
15335         * Location where install is coming from, before it has been
15336         * copied/renamed into place. This could be a single monolithic APK
15337         * file, or a cluster directory. This location may be untrusted.
15338         */
15339        final File file;
15340
15341        /**
15342         * Flag indicating that {@link #file} or {@link #cid} has already been
15343         * staged, meaning downstream users don't need to defensively copy the
15344         * contents.
15345         */
15346        final boolean staged;
15347
15348        /**
15349         * Flag indicating that {@link #file} or {@link #cid} is an already
15350         * installed app that is being moved.
15351         */
15352        final boolean existing;
15353
15354        final String resolvedPath;
15355        final File resolvedFile;
15356
15357        static OriginInfo fromNothing() {
15358            return new OriginInfo(null, false, false);
15359        }
15360
15361        static OriginInfo fromUntrustedFile(File file) {
15362            return new OriginInfo(file, false, false);
15363        }
15364
15365        static OriginInfo fromExistingFile(File file) {
15366            return new OriginInfo(file, false, true);
15367        }
15368
15369        static OriginInfo fromStagedFile(File file) {
15370            return new OriginInfo(file, true, false);
15371        }
15372
15373        private OriginInfo(File file, boolean staged, boolean existing) {
15374            this.file = file;
15375            this.staged = staged;
15376            this.existing = existing;
15377
15378            if (file != null) {
15379                resolvedPath = file.getAbsolutePath();
15380                resolvedFile = file;
15381            } else {
15382                resolvedPath = null;
15383                resolvedFile = null;
15384            }
15385        }
15386    }
15387
15388    static class MoveInfo {
15389        final int moveId;
15390        final String fromUuid;
15391        final String toUuid;
15392        final String packageName;
15393        final String dataAppName;
15394        final int appId;
15395        final String seinfo;
15396        final int targetSdkVersion;
15397
15398        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15399                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15400            this.moveId = moveId;
15401            this.fromUuid = fromUuid;
15402            this.toUuid = toUuid;
15403            this.packageName = packageName;
15404            this.dataAppName = dataAppName;
15405            this.appId = appId;
15406            this.seinfo = seinfo;
15407            this.targetSdkVersion = targetSdkVersion;
15408        }
15409    }
15410
15411    static class VerificationInfo {
15412        /** A constant used to indicate that a uid value is not present. */
15413        public static final int NO_UID = -1;
15414
15415        /** URI referencing where the package was downloaded from. */
15416        final Uri originatingUri;
15417
15418        /** HTTP referrer URI associated with the originatingURI. */
15419        final Uri referrer;
15420
15421        /** UID of the application that the install request originated from. */
15422        final int originatingUid;
15423
15424        /** UID of application requesting the install */
15425        final int installerUid;
15426
15427        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15428            this.originatingUri = originatingUri;
15429            this.referrer = referrer;
15430            this.originatingUid = originatingUid;
15431            this.installerUid = installerUid;
15432        }
15433    }
15434
15435    class InstallParams extends HandlerParams {
15436        final OriginInfo origin;
15437        final MoveInfo move;
15438        final IPackageInstallObserver2 observer;
15439        int installFlags;
15440        final String installerPackageName;
15441        final String volumeUuid;
15442        private InstallArgs mArgs;
15443        private int mRet;
15444        final String packageAbiOverride;
15445        final String[] grantedRuntimePermissions;
15446        final VerificationInfo verificationInfo;
15447        final Certificate[][] certificates;
15448        final int installReason;
15449
15450        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15451                int installFlags, String installerPackageName, String volumeUuid,
15452                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15453                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15454            super(user);
15455            this.origin = origin;
15456            this.move = move;
15457            this.observer = observer;
15458            this.installFlags = installFlags;
15459            this.installerPackageName = installerPackageName;
15460            this.volumeUuid = volumeUuid;
15461            this.verificationInfo = verificationInfo;
15462            this.packageAbiOverride = packageAbiOverride;
15463            this.grantedRuntimePermissions = grantedPermissions;
15464            this.certificates = certificates;
15465            this.installReason = installReason;
15466        }
15467
15468        @Override
15469        public String toString() {
15470            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15471                    + " file=" + origin.file + "}";
15472        }
15473
15474        private int installLocationPolicy(PackageInfoLite pkgLite) {
15475            String packageName = pkgLite.packageName;
15476            int installLocation = pkgLite.installLocation;
15477            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15478            // reader
15479            synchronized (mPackages) {
15480                // Currently installed package which the new package is attempting to replace or
15481                // null if no such package is installed.
15482                PackageParser.Package installedPkg = mPackages.get(packageName);
15483                // Package which currently owns the data which the new package will own if installed.
15484                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15485                // will be null whereas dataOwnerPkg will contain information about the package
15486                // which was uninstalled while keeping its data.
15487                PackageParser.Package dataOwnerPkg = installedPkg;
15488                if (dataOwnerPkg  == null) {
15489                    PackageSetting ps = mSettings.mPackages.get(packageName);
15490                    if (ps != null) {
15491                        dataOwnerPkg = ps.pkg;
15492                    }
15493                }
15494
15495                if (dataOwnerPkg != null) {
15496                    // If installed, the package will get access to data left on the device by its
15497                    // predecessor. As a security measure, this is permited only if this is not a
15498                    // version downgrade or if the predecessor package is marked as debuggable and
15499                    // a downgrade is explicitly requested.
15500                    //
15501                    // On debuggable platform builds, downgrades are permitted even for
15502                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15503                    // not offer security guarantees and thus it's OK to disable some security
15504                    // mechanisms to make debugging/testing easier on those builds. However, even on
15505                    // debuggable builds downgrades of packages are permitted only if requested via
15506                    // installFlags. This is because we aim to keep the behavior of debuggable
15507                    // platform builds as close as possible to the behavior of non-debuggable
15508                    // platform builds.
15509                    final boolean downgradeRequested =
15510                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15511                    final boolean packageDebuggable =
15512                                (dataOwnerPkg.applicationInfo.flags
15513                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15514                    final boolean downgradePermitted =
15515                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15516                    if (!downgradePermitted) {
15517                        try {
15518                            checkDowngrade(dataOwnerPkg, pkgLite);
15519                        } catch (PackageManagerException e) {
15520                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15521                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15522                        }
15523                    }
15524                }
15525
15526                if (installedPkg != null) {
15527                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15528                        // Check for updated system application.
15529                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15530                            if (onSd) {
15531                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15532                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15533                            }
15534                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15535                        } else {
15536                            if (onSd) {
15537                                // Install flag overrides everything.
15538                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15539                            }
15540                            // If current upgrade specifies particular preference
15541                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15542                                // Application explicitly specified internal.
15543                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15544                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15545                                // App explictly prefers external. Let policy decide
15546                            } else {
15547                                // Prefer previous location
15548                                if (isExternal(installedPkg)) {
15549                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15550                                }
15551                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15552                            }
15553                        }
15554                    } else {
15555                        // Invalid install. Return error code
15556                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15557                    }
15558                }
15559            }
15560            // All the special cases have been taken care of.
15561            // Return result based on recommended install location.
15562            if (onSd) {
15563                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15564            }
15565            return pkgLite.recommendedInstallLocation;
15566        }
15567
15568        /*
15569         * Invoke remote method to get package information and install
15570         * location values. Override install location based on default
15571         * policy if needed and then create install arguments based
15572         * on the install location.
15573         */
15574        public void handleStartCopy() throws RemoteException {
15575            int ret = PackageManager.INSTALL_SUCCEEDED;
15576
15577            // If we're already staged, we've firmly committed to an install location
15578            if (origin.staged) {
15579                if (origin.file != null) {
15580                    installFlags |= PackageManager.INSTALL_INTERNAL;
15581                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15582                } else {
15583                    throw new IllegalStateException("Invalid stage location");
15584                }
15585            }
15586
15587            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15588            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15589            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15590            PackageInfoLite pkgLite = null;
15591
15592            if (onInt && onSd) {
15593                // Check if both bits are set.
15594                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15595                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15596            } else if (onSd && ephemeral) {
15597                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15598                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15599            } else {
15600                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15601                        packageAbiOverride);
15602
15603                if (DEBUG_EPHEMERAL && ephemeral) {
15604                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15605                }
15606
15607                /*
15608                 * If we have too little free space, try to free cache
15609                 * before giving up.
15610                 */
15611                if (!origin.staged && pkgLite.recommendedInstallLocation
15612                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15613                    // TODO: focus freeing disk space on the target device
15614                    final StorageManager storage = StorageManager.from(mContext);
15615                    final long lowThreshold = storage.getStorageLowBytes(
15616                            Environment.getDataDirectory());
15617
15618                    final long sizeBytes = mContainerService.calculateInstalledSize(
15619                            origin.resolvedPath, packageAbiOverride);
15620
15621                    try {
15622                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15623                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15624                                installFlags, packageAbiOverride);
15625                    } catch (InstallerException e) {
15626                        Slog.w(TAG, "Failed to free cache", e);
15627                    }
15628
15629                    /*
15630                     * The cache free must have deleted the file we
15631                     * downloaded to install.
15632                     *
15633                     * TODO: fix the "freeCache" call to not delete
15634                     *       the file we care about.
15635                     */
15636                    if (pkgLite.recommendedInstallLocation
15637                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15638                        pkgLite.recommendedInstallLocation
15639                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15640                    }
15641                }
15642            }
15643
15644            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15645                int loc = pkgLite.recommendedInstallLocation;
15646                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15647                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15648                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15649                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15650                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15651                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15652                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15653                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15654                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15655                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15656                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15657                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15658                } else {
15659                    // Override with defaults if needed.
15660                    loc = installLocationPolicy(pkgLite);
15661                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15662                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15663                    } else if (!onSd && !onInt) {
15664                        // Override install location with flags
15665                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15666                            // Set the flag to install on external media.
15667                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15668                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15669                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15670                            if (DEBUG_EPHEMERAL) {
15671                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15672                            }
15673                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15674                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15675                                    |PackageManager.INSTALL_INTERNAL);
15676                        } else {
15677                            // Make sure the flag for installing on external
15678                            // media is unset
15679                            installFlags |= PackageManager.INSTALL_INTERNAL;
15680                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15681                        }
15682                    }
15683                }
15684            }
15685
15686            final InstallArgs args = createInstallArgs(this);
15687            mArgs = args;
15688
15689            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15690                // TODO: http://b/22976637
15691                // Apps installed for "all" users use the device owner to verify the app
15692                UserHandle verifierUser = getUser();
15693                if (verifierUser == UserHandle.ALL) {
15694                    verifierUser = UserHandle.SYSTEM;
15695                }
15696
15697                /*
15698                 * Determine if we have any installed package verifiers. If we
15699                 * do, then we'll defer to them to verify the packages.
15700                 */
15701                final int requiredUid = mRequiredVerifierPackage == null ? -1
15702                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15703                                verifierUser.getIdentifier());
15704                final int installerUid =
15705                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15706                if (!origin.existing && requiredUid != -1
15707                        && isVerificationEnabled(
15708                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15709                    final Intent verification = new Intent(
15710                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15711                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15712                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15713                            PACKAGE_MIME_TYPE);
15714                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15715
15716                    // Query all live verifiers based on current user state
15717                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15718                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15719                            false /*allowDynamicSplits*/);
15720
15721                    if (DEBUG_VERIFY) {
15722                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15723                                + verification.toString() + " with " + pkgLite.verifiers.length
15724                                + " optional verifiers");
15725                    }
15726
15727                    final int verificationId = mPendingVerificationToken++;
15728
15729                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15730
15731                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15732                            installerPackageName);
15733
15734                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15735                            installFlags);
15736
15737                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15738                            pkgLite.packageName);
15739
15740                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15741                            pkgLite.versionCode);
15742
15743                    if (verificationInfo != null) {
15744                        if (verificationInfo.originatingUri != null) {
15745                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15746                                    verificationInfo.originatingUri);
15747                        }
15748                        if (verificationInfo.referrer != null) {
15749                            verification.putExtra(Intent.EXTRA_REFERRER,
15750                                    verificationInfo.referrer);
15751                        }
15752                        if (verificationInfo.originatingUid >= 0) {
15753                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15754                                    verificationInfo.originatingUid);
15755                        }
15756                        if (verificationInfo.installerUid >= 0) {
15757                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15758                                    verificationInfo.installerUid);
15759                        }
15760                    }
15761
15762                    final PackageVerificationState verificationState = new PackageVerificationState(
15763                            requiredUid, args);
15764
15765                    mPendingVerification.append(verificationId, verificationState);
15766
15767                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15768                            receivers, verificationState);
15769
15770                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15771                    final long idleDuration = getVerificationTimeout();
15772
15773                    /*
15774                     * If any sufficient verifiers were listed in the package
15775                     * manifest, attempt to ask them.
15776                     */
15777                    if (sufficientVerifiers != null) {
15778                        final int N = sufficientVerifiers.size();
15779                        if (N == 0) {
15780                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15781                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15782                        } else {
15783                            for (int i = 0; i < N; i++) {
15784                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15785                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15786                                        verifierComponent.getPackageName(), idleDuration,
15787                                        verifierUser.getIdentifier(), false, "package verifier");
15788
15789                                final Intent sufficientIntent = new Intent(verification);
15790                                sufficientIntent.setComponent(verifierComponent);
15791                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15792                            }
15793                        }
15794                    }
15795
15796                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15797                            mRequiredVerifierPackage, receivers);
15798                    if (ret == PackageManager.INSTALL_SUCCEEDED
15799                            && mRequiredVerifierPackage != null) {
15800                        Trace.asyncTraceBegin(
15801                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15802                        /*
15803                         * Send the intent to the required verification agent,
15804                         * but only start the verification timeout after the
15805                         * target BroadcastReceivers have run.
15806                         */
15807                        verification.setComponent(requiredVerifierComponent);
15808                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15809                                mRequiredVerifierPackage, idleDuration,
15810                                verifierUser.getIdentifier(), false, "package verifier");
15811                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15812                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15813                                new BroadcastReceiver() {
15814                                    @Override
15815                                    public void onReceive(Context context, Intent intent) {
15816                                        final Message msg = mHandler
15817                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15818                                        msg.arg1 = verificationId;
15819                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15820                                    }
15821                                }, null, 0, null, null);
15822
15823                        /*
15824                         * We don't want the copy to proceed until verification
15825                         * succeeds, so null out this field.
15826                         */
15827                        mArgs = null;
15828                    }
15829                } else {
15830                    /*
15831                     * No package verification is enabled, so immediately start
15832                     * the remote call to initiate copy using temporary file.
15833                     */
15834                    ret = args.copyApk(mContainerService, true);
15835                }
15836            }
15837
15838            mRet = ret;
15839        }
15840
15841        @Override
15842        void handleReturnCode() {
15843            // If mArgs is null, then MCS couldn't be reached. When it
15844            // reconnects, it will try again to install. At that point, this
15845            // will succeed.
15846            if (mArgs != null) {
15847                processPendingInstall(mArgs, mRet);
15848            }
15849        }
15850
15851        @Override
15852        void handleServiceError() {
15853            mArgs = createInstallArgs(this);
15854            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15855        }
15856    }
15857
15858    private InstallArgs createInstallArgs(InstallParams params) {
15859        if (params.move != null) {
15860            return new MoveInstallArgs(params);
15861        } else {
15862            return new FileInstallArgs(params);
15863        }
15864    }
15865
15866    /**
15867     * Create args that describe an existing installed package. Typically used
15868     * when cleaning up old installs, or used as a move source.
15869     */
15870    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15871            String resourcePath, String[] instructionSets) {
15872        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15873    }
15874
15875    static abstract class InstallArgs {
15876        /** @see InstallParams#origin */
15877        final OriginInfo origin;
15878        /** @see InstallParams#move */
15879        final MoveInfo move;
15880
15881        final IPackageInstallObserver2 observer;
15882        // Always refers to PackageManager flags only
15883        final int installFlags;
15884        final String installerPackageName;
15885        final String volumeUuid;
15886        final UserHandle user;
15887        final String abiOverride;
15888        final String[] installGrantPermissions;
15889        /** If non-null, drop an async trace when the install completes */
15890        final String traceMethod;
15891        final int traceCookie;
15892        final Certificate[][] certificates;
15893        final int installReason;
15894
15895        // The list of instruction sets supported by this app. This is currently
15896        // only used during the rmdex() phase to clean up resources. We can get rid of this
15897        // if we move dex files under the common app path.
15898        /* nullable */ String[] instructionSets;
15899
15900        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15901                int installFlags, String installerPackageName, String volumeUuid,
15902                UserHandle user, String[] instructionSets,
15903                String abiOverride, String[] installGrantPermissions,
15904                String traceMethod, int traceCookie, Certificate[][] certificates,
15905                int installReason) {
15906            this.origin = origin;
15907            this.move = move;
15908            this.installFlags = installFlags;
15909            this.observer = observer;
15910            this.installerPackageName = installerPackageName;
15911            this.volumeUuid = volumeUuid;
15912            this.user = user;
15913            this.instructionSets = instructionSets;
15914            this.abiOverride = abiOverride;
15915            this.installGrantPermissions = installGrantPermissions;
15916            this.traceMethod = traceMethod;
15917            this.traceCookie = traceCookie;
15918            this.certificates = certificates;
15919            this.installReason = installReason;
15920        }
15921
15922        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15923        abstract int doPreInstall(int status);
15924
15925        /**
15926         * Rename package into final resting place. All paths on the given
15927         * scanned package should be updated to reflect the rename.
15928         */
15929        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15930        abstract int doPostInstall(int status, int uid);
15931
15932        /** @see PackageSettingBase#codePathString */
15933        abstract String getCodePath();
15934        /** @see PackageSettingBase#resourcePathString */
15935        abstract String getResourcePath();
15936
15937        // Need installer lock especially for dex file removal.
15938        abstract void cleanUpResourcesLI();
15939        abstract boolean doPostDeleteLI(boolean delete);
15940
15941        /**
15942         * Called before the source arguments are copied. This is used mostly
15943         * for MoveParams when it needs to read the source file to put it in the
15944         * destination.
15945         */
15946        int doPreCopy() {
15947            return PackageManager.INSTALL_SUCCEEDED;
15948        }
15949
15950        /**
15951         * Called after the source arguments are copied. This is used mostly for
15952         * MoveParams when it needs to read the source file to put it in the
15953         * destination.
15954         */
15955        int doPostCopy(int uid) {
15956            return PackageManager.INSTALL_SUCCEEDED;
15957        }
15958
15959        protected boolean isFwdLocked() {
15960            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15961        }
15962
15963        protected boolean isExternalAsec() {
15964            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15965        }
15966
15967        protected boolean isEphemeral() {
15968            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15969        }
15970
15971        UserHandle getUser() {
15972            return user;
15973        }
15974    }
15975
15976    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15977        if (!allCodePaths.isEmpty()) {
15978            if (instructionSets == null) {
15979                throw new IllegalStateException("instructionSet == null");
15980            }
15981            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15982            for (String codePath : allCodePaths) {
15983                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15984                    try {
15985                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15986                    } catch (InstallerException ignored) {
15987                    }
15988                }
15989            }
15990        }
15991    }
15992
15993    /**
15994     * Logic to handle installation of non-ASEC applications, including copying
15995     * and renaming logic.
15996     */
15997    class FileInstallArgs extends InstallArgs {
15998        private File codeFile;
15999        private File resourceFile;
16000
16001        // Example topology:
16002        // /data/app/com.example/base.apk
16003        // /data/app/com.example/split_foo.apk
16004        // /data/app/com.example/lib/arm/libfoo.so
16005        // /data/app/com.example/lib/arm64/libfoo.so
16006        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16007
16008        /** New install */
16009        FileInstallArgs(InstallParams params) {
16010            super(params.origin, params.move, params.observer, params.installFlags,
16011                    params.installerPackageName, params.volumeUuid,
16012                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16013                    params.grantedRuntimePermissions,
16014                    params.traceMethod, params.traceCookie, params.certificates,
16015                    params.installReason);
16016            if (isFwdLocked()) {
16017                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16018            }
16019        }
16020
16021        /** Existing install */
16022        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16023            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16024                    null, null, null, 0, null /*certificates*/,
16025                    PackageManager.INSTALL_REASON_UNKNOWN);
16026            this.codeFile = (codePath != null) ? new File(codePath) : null;
16027            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16028        }
16029
16030        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16031            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16032            try {
16033                return doCopyApk(imcs, temp);
16034            } finally {
16035                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16036            }
16037        }
16038
16039        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16040            if (origin.staged) {
16041                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16042                codeFile = origin.file;
16043                resourceFile = origin.file;
16044                return PackageManager.INSTALL_SUCCEEDED;
16045            }
16046
16047            try {
16048                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16049                final File tempDir =
16050                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16051                codeFile = tempDir;
16052                resourceFile = tempDir;
16053            } catch (IOException e) {
16054                Slog.w(TAG, "Failed to create copy file: " + e);
16055                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16056            }
16057
16058            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16059                @Override
16060                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16061                    if (!FileUtils.isValidExtFilename(name)) {
16062                        throw new IllegalArgumentException("Invalid filename: " + name);
16063                    }
16064                    try {
16065                        final File file = new File(codeFile, name);
16066                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16067                                O_RDWR | O_CREAT, 0644);
16068                        Os.chmod(file.getAbsolutePath(), 0644);
16069                        return new ParcelFileDescriptor(fd);
16070                    } catch (ErrnoException e) {
16071                        throw new RemoteException("Failed to open: " + e.getMessage());
16072                    }
16073                }
16074            };
16075
16076            int ret = PackageManager.INSTALL_SUCCEEDED;
16077            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16078            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16079                Slog.e(TAG, "Failed to copy package");
16080                return ret;
16081            }
16082
16083            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16084            NativeLibraryHelper.Handle handle = null;
16085            try {
16086                handle = NativeLibraryHelper.Handle.create(codeFile);
16087                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16088                        abiOverride);
16089            } catch (IOException e) {
16090                Slog.e(TAG, "Copying native libraries failed", e);
16091                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16092            } finally {
16093                IoUtils.closeQuietly(handle);
16094            }
16095
16096            return ret;
16097        }
16098
16099        int doPreInstall(int status) {
16100            if (status != PackageManager.INSTALL_SUCCEEDED) {
16101                cleanUp();
16102            }
16103            return status;
16104        }
16105
16106        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16107            if (status != PackageManager.INSTALL_SUCCEEDED) {
16108                cleanUp();
16109                return false;
16110            }
16111
16112            final File targetDir = codeFile.getParentFile();
16113            final File beforeCodeFile = codeFile;
16114            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16115
16116            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16117            try {
16118                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16119            } catch (ErrnoException e) {
16120                Slog.w(TAG, "Failed to rename", e);
16121                return false;
16122            }
16123
16124            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16125                Slog.w(TAG, "Failed to restorecon");
16126                return false;
16127            }
16128
16129            // Reflect the rename internally
16130            codeFile = afterCodeFile;
16131            resourceFile = afterCodeFile;
16132
16133            // Reflect the rename in scanned details
16134            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16135            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16136                    afterCodeFile, pkg.baseCodePath));
16137            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16138                    afterCodeFile, pkg.splitCodePaths));
16139
16140            // Reflect the rename in app info
16141            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16142            pkg.setApplicationInfoCodePath(pkg.codePath);
16143            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16144            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16145            pkg.setApplicationInfoResourcePath(pkg.codePath);
16146            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16147            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16148
16149            return true;
16150        }
16151
16152        int doPostInstall(int status, int uid) {
16153            if (status != PackageManager.INSTALL_SUCCEEDED) {
16154                cleanUp();
16155            }
16156            return status;
16157        }
16158
16159        @Override
16160        String getCodePath() {
16161            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16162        }
16163
16164        @Override
16165        String getResourcePath() {
16166            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16167        }
16168
16169        private boolean cleanUp() {
16170            if (codeFile == null || !codeFile.exists()) {
16171                return false;
16172            }
16173
16174            removeCodePathLI(codeFile);
16175
16176            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16177                resourceFile.delete();
16178            }
16179
16180            return true;
16181        }
16182
16183        void cleanUpResourcesLI() {
16184            // Try enumerating all code paths before deleting
16185            List<String> allCodePaths = Collections.EMPTY_LIST;
16186            if (codeFile != null && codeFile.exists()) {
16187                try {
16188                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16189                    allCodePaths = pkg.getAllCodePaths();
16190                } catch (PackageParserException e) {
16191                    // Ignored; we tried our best
16192                }
16193            }
16194
16195            cleanUp();
16196            removeDexFiles(allCodePaths, instructionSets);
16197        }
16198
16199        boolean doPostDeleteLI(boolean delete) {
16200            // XXX err, shouldn't we respect the delete flag?
16201            cleanUpResourcesLI();
16202            return true;
16203        }
16204    }
16205
16206    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16207            PackageManagerException {
16208        if (copyRet < 0) {
16209            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16210                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16211                throw new PackageManagerException(copyRet, message);
16212            }
16213        }
16214    }
16215
16216    /**
16217     * Extract the StorageManagerService "container ID" from the full code path of an
16218     * .apk.
16219     */
16220    static String cidFromCodePath(String fullCodePath) {
16221        int eidx = fullCodePath.lastIndexOf("/");
16222        String subStr1 = fullCodePath.substring(0, eidx);
16223        int sidx = subStr1.lastIndexOf("/");
16224        return subStr1.substring(sidx+1, eidx);
16225    }
16226
16227    /**
16228     * Logic to handle movement of existing installed applications.
16229     */
16230    class MoveInstallArgs extends InstallArgs {
16231        private File codeFile;
16232        private File resourceFile;
16233
16234        /** New install */
16235        MoveInstallArgs(InstallParams params) {
16236            super(params.origin, params.move, params.observer, params.installFlags,
16237                    params.installerPackageName, params.volumeUuid,
16238                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16239                    params.grantedRuntimePermissions,
16240                    params.traceMethod, params.traceCookie, params.certificates,
16241                    params.installReason);
16242        }
16243
16244        int copyApk(IMediaContainerService imcs, boolean temp) {
16245            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16246                    + move.fromUuid + " to " + move.toUuid);
16247            synchronized (mInstaller) {
16248                try {
16249                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16250                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16251                } catch (InstallerException e) {
16252                    Slog.w(TAG, "Failed to move app", e);
16253                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16254                }
16255            }
16256
16257            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16258            resourceFile = codeFile;
16259            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16260
16261            return PackageManager.INSTALL_SUCCEEDED;
16262        }
16263
16264        int doPreInstall(int status) {
16265            if (status != PackageManager.INSTALL_SUCCEEDED) {
16266                cleanUp(move.toUuid);
16267            }
16268            return status;
16269        }
16270
16271        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16272            if (status != PackageManager.INSTALL_SUCCEEDED) {
16273                cleanUp(move.toUuid);
16274                return false;
16275            }
16276
16277            // Reflect the move in app info
16278            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16279            pkg.setApplicationInfoCodePath(pkg.codePath);
16280            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16281            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16282            pkg.setApplicationInfoResourcePath(pkg.codePath);
16283            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16284            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16285
16286            return true;
16287        }
16288
16289        int doPostInstall(int status, int uid) {
16290            if (status == PackageManager.INSTALL_SUCCEEDED) {
16291                cleanUp(move.fromUuid);
16292            } else {
16293                cleanUp(move.toUuid);
16294            }
16295            return status;
16296        }
16297
16298        @Override
16299        String getCodePath() {
16300            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16301        }
16302
16303        @Override
16304        String getResourcePath() {
16305            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16306        }
16307
16308        private boolean cleanUp(String volumeUuid) {
16309            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16310                    move.dataAppName);
16311            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16312            final int[] userIds = sUserManager.getUserIds();
16313            synchronized (mInstallLock) {
16314                // Clean up both app data and code
16315                // All package moves are frozen until finished
16316                for (int userId : userIds) {
16317                    try {
16318                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16319                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16320                    } catch (InstallerException e) {
16321                        Slog.w(TAG, String.valueOf(e));
16322                    }
16323                }
16324                removeCodePathLI(codeFile);
16325            }
16326            return true;
16327        }
16328
16329        void cleanUpResourcesLI() {
16330            throw new UnsupportedOperationException();
16331        }
16332
16333        boolean doPostDeleteLI(boolean delete) {
16334            throw new UnsupportedOperationException();
16335        }
16336    }
16337
16338    static String getAsecPackageName(String packageCid) {
16339        int idx = packageCid.lastIndexOf("-");
16340        if (idx == -1) {
16341            return packageCid;
16342        }
16343        return packageCid.substring(0, idx);
16344    }
16345
16346    // Utility method used to create code paths based on package name and available index.
16347    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16348        String idxStr = "";
16349        int idx = 1;
16350        // Fall back to default value of idx=1 if prefix is not
16351        // part of oldCodePath
16352        if (oldCodePath != null) {
16353            String subStr = oldCodePath;
16354            // Drop the suffix right away
16355            if (suffix != null && subStr.endsWith(suffix)) {
16356                subStr = subStr.substring(0, subStr.length() - suffix.length());
16357            }
16358            // If oldCodePath already contains prefix find out the
16359            // ending index to either increment or decrement.
16360            int sidx = subStr.lastIndexOf(prefix);
16361            if (sidx != -1) {
16362                subStr = subStr.substring(sidx + prefix.length());
16363                if (subStr != null) {
16364                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16365                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16366                    }
16367                    try {
16368                        idx = Integer.parseInt(subStr);
16369                        if (idx <= 1) {
16370                            idx++;
16371                        } else {
16372                            idx--;
16373                        }
16374                    } catch(NumberFormatException e) {
16375                    }
16376                }
16377            }
16378        }
16379        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16380        return prefix + idxStr;
16381    }
16382
16383    private File getNextCodePath(File targetDir, String packageName) {
16384        File result;
16385        SecureRandom random = new SecureRandom();
16386        byte[] bytes = new byte[16];
16387        do {
16388            random.nextBytes(bytes);
16389            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16390            result = new File(targetDir, packageName + "-" + suffix);
16391        } while (result.exists());
16392        return result;
16393    }
16394
16395    // Utility method that returns the relative package path with respect
16396    // to the installation directory. Like say for /data/data/com.test-1.apk
16397    // string com.test-1 is returned.
16398    static String deriveCodePathName(String codePath) {
16399        if (codePath == null) {
16400            return null;
16401        }
16402        final File codeFile = new File(codePath);
16403        final String name = codeFile.getName();
16404        if (codeFile.isDirectory()) {
16405            return name;
16406        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16407            final int lastDot = name.lastIndexOf('.');
16408            return name.substring(0, lastDot);
16409        } else {
16410            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16411            return null;
16412        }
16413    }
16414
16415    static class PackageInstalledInfo {
16416        String name;
16417        int uid;
16418        // The set of users that originally had this package installed.
16419        int[] origUsers;
16420        // The set of users that now have this package installed.
16421        int[] newUsers;
16422        PackageParser.Package pkg;
16423        int returnCode;
16424        String returnMsg;
16425        String installerPackageName;
16426        PackageRemovedInfo removedInfo;
16427        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16428
16429        public void setError(int code, String msg) {
16430            setReturnCode(code);
16431            setReturnMessage(msg);
16432            Slog.w(TAG, msg);
16433        }
16434
16435        public void setError(String msg, PackageParserException e) {
16436            setReturnCode(e.error);
16437            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16438            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16439            for (int i = 0; i < childCount; i++) {
16440                addedChildPackages.valueAt(i).setError(msg, e);
16441            }
16442            Slog.w(TAG, msg, e);
16443        }
16444
16445        public void setError(String msg, PackageManagerException e) {
16446            returnCode = e.error;
16447            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16448            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16449            for (int i = 0; i < childCount; i++) {
16450                addedChildPackages.valueAt(i).setError(msg, e);
16451            }
16452            Slog.w(TAG, msg, e);
16453        }
16454
16455        public void setReturnCode(int returnCode) {
16456            this.returnCode = returnCode;
16457            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16458            for (int i = 0; i < childCount; i++) {
16459                addedChildPackages.valueAt(i).returnCode = returnCode;
16460            }
16461        }
16462
16463        private void setReturnMessage(String returnMsg) {
16464            this.returnMsg = returnMsg;
16465            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16466            for (int i = 0; i < childCount; i++) {
16467                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16468            }
16469        }
16470
16471        // In some error cases we want to convey more info back to the observer
16472        String origPackage;
16473        String origPermission;
16474    }
16475
16476    /*
16477     * Install a non-existing package.
16478     */
16479    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16480            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16481            PackageInstalledInfo res, int installReason) {
16482        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16483
16484        // Remember this for later, in case we need to rollback this install
16485        String pkgName = pkg.packageName;
16486
16487        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16488
16489        synchronized(mPackages) {
16490            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16491            if (renamedPackage != null) {
16492                // A package with the same name is already installed, though
16493                // it has been renamed to an older name.  The package we
16494                // are trying to install should be installed as an update to
16495                // the existing one, but that has not been requested, so bail.
16496                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16497                        + " without first uninstalling package running as "
16498                        + renamedPackage);
16499                return;
16500            }
16501            if (mPackages.containsKey(pkgName)) {
16502                // Don't allow installation over an existing package with the same name.
16503                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16504                        + " without first uninstalling.");
16505                return;
16506            }
16507        }
16508
16509        try {
16510            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16511                    System.currentTimeMillis(), user);
16512
16513            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16514
16515            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16516                prepareAppDataAfterInstallLIF(newPackage);
16517
16518            } else {
16519                // Remove package from internal structures, but keep around any
16520                // data that might have already existed
16521                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16522                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16523            }
16524        } catch (PackageManagerException e) {
16525            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16526        }
16527
16528        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16529    }
16530
16531    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16532        // Can't rotate keys during boot or if sharedUser.
16533        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16534                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16535            return false;
16536        }
16537        // app is using upgradeKeySets; make sure all are valid
16538        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16539        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16540        for (int i = 0; i < upgradeKeySets.length; i++) {
16541            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16542                Slog.wtf(TAG, "Package "
16543                         + (oldPs.name != null ? oldPs.name : "<null>")
16544                         + " contains upgrade-key-set reference to unknown key-set: "
16545                         + upgradeKeySets[i]
16546                         + " reverting to signatures check.");
16547                return false;
16548            }
16549        }
16550        return true;
16551    }
16552
16553    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16554        // Upgrade keysets are being used.  Determine if new package has a superset of the
16555        // required keys.
16556        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16557        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16558        for (int i = 0; i < upgradeKeySets.length; i++) {
16559            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16560            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16561                return true;
16562            }
16563        }
16564        return false;
16565    }
16566
16567    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16568        try (DigestInputStream digestStream =
16569                new DigestInputStream(new FileInputStream(file), digest)) {
16570            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16571        }
16572    }
16573
16574    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16575            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16576            int installReason) {
16577        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16578
16579        final PackageParser.Package oldPackage;
16580        final PackageSetting ps;
16581        final String pkgName = pkg.packageName;
16582        final int[] allUsers;
16583        final int[] installedUsers;
16584
16585        synchronized(mPackages) {
16586            oldPackage = mPackages.get(pkgName);
16587            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16588
16589            // don't allow upgrade to target a release SDK from a pre-release SDK
16590            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16591                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16592            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16593                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16594            if (oldTargetsPreRelease
16595                    && !newTargetsPreRelease
16596                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16597                Slog.w(TAG, "Can't install package targeting released sdk");
16598                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16599                return;
16600            }
16601
16602            ps = mSettings.mPackages.get(pkgName);
16603
16604            // verify signatures are valid
16605            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16606                if (!checkUpgradeKeySetLP(ps, pkg)) {
16607                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16608                            "New package not signed by keys specified by upgrade-keysets: "
16609                                    + pkgName);
16610                    return;
16611                }
16612            } else {
16613                // default to original signature matching
16614                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16615                        != PackageManager.SIGNATURE_MATCH) {
16616                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16617                            "New package has a different signature: " + pkgName);
16618                    return;
16619                }
16620            }
16621
16622            // don't allow a system upgrade unless the upgrade hash matches
16623            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16624                byte[] digestBytes = null;
16625                try {
16626                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16627                    updateDigest(digest, new File(pkg.baseCodePath));
16628                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16629                        for (String path : pkg.splitCodePaths) {
16630                            updateDigest(digest, new File(path));
16631                        }
16632                    }
16633                    digestBytes = digest.digest();
16634                } catch (NoSuchAlgorithmException | IOException e) {
16635                    res.setError(INSTALL_FAILED_INVALID_APK,
16636                            "Could not compute hash: " + pkgName);
16637                    return;
16638                }
16639                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16640                    res.setError(INSTALL_FAILED_INVALID_APK,
16641                            "New package fails restrict-update check: " + pkgName);
16642                    return;
16643                }
16644                // retain upgrade restriction
16645                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16646            }
16647
16648            // Check for shared user id changes
16649            String invalidPackageName =
16650                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16651            if (invalidPackageName != null) {
16652                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16653                        "Package " + invalidPackageName + " tried to change user "
16654                                + oldPackage.mSharedUserId);
16655                return;
16656            }
16657
16658            // In case of rollback, remember per-user/profile install state
16659            allUsers = sUserManager.getUserIds();
16660            installedUsers = ps.queryInstalledUsers(allUsers, true);
16661
16662            // don't allow an upgrade from full to ephemeral
16663            if (isInstantApp) {
16664                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16665                    for (int currentUser : allUsers) {
16666                        if (!ps.getInstantApp(currentUser)) {
16667                            // can't downgrade from full to instant
16668                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16669                                    + " for user: " + currentUser);
16670                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16671                            return;
16672                        }
16673                    }
16674                } else if (!ps.getInstantApp(user.getIdentifier())) {
16675                    // can't downgrade from full to instant
16676                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16677                            + " for user: " + user.getIdentifier());
16678                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16679                    return;
16680                }
16681            }
16682        }
16683
16684        // Update what is removed
16685        res.removedInfo = new PackageRemovedInfo(this);
16686        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16687        res.removedInfo.removedPackage = oldPackage.packageName;
16688        res.removedInfo.installerPackageName = ps.installerPackageName;
16689        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16690        res.removedInfo.isUpdate = true;
16691        res.removedInfo.origUsers = installedUsers;
16692        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16693        for (int i = 0; i < installedUsers.length; i++) {
16694            final int userId = installedUsers[i];
16695            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16696        }
16697
16698        final int childCount = (oldPackage.childPackages != null)
16699                ? oldPackage.childPackages.size() : 0;
16700        for (int i = 0; i < childCount; i++) {
16701            boolean childPackageUpdated = false;
16702            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16703            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16704            if (res.addedChildPackages != null) {
16705                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16706                if (childRes != null) {
16707                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16708                    childRes.removedInfo.removedPackage = childPkg.packageName;
16709                    if (childPs != null) {
16710                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16711                    }
16712                    childRes.removedInfo.isUpdate = true;
16713                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16714                    childPackageUpdated = true;
16715                }
16716            }
16717            if (!childPackageUpdated) {
16718                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16719                childRemovedRes.removedPackage = childPkg.packageName;
16720                if (childPs != null) {
16721                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16722                }
16723                childRemovedRes.isUpdate = false;
16724                childRemovedRes.dataRemoved = true;
16725                synchronized (mPackages) {
16726                    if (childPs != null) {
16727                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16728                    }
16729                }
16730                if (res.removedInfo.removedChildPackages == null) {
16731                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16732                }
16733                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16734            }
16735        }
16736
16737        boolean sysPkg = (isSystemApp(oldPackage));
16738        if (sysPkg) {
16739            // Set the system/privileged/oem flags as needed
16740            final boolean privileged =
16741                    (oldPackage.applicationInfo.privateFlags
16742                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16743            final boolean oem =
16744                    (oldPackage.applicationInfo.privateFlags
16745                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16746            final int systemPolicyFlags = policyFlags
16747                    | PackageParser.PARSE_IS_SYSTEM
16748                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16749                    | (oem ? PARSE_IS_OEM : 0);
16750
16751            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16752                    user, allUsers, installerPackageName, res, installReason);
16753        } else {
16754            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16755                    user, allUsers, installerPackageName, res, installReason);
16756        }
16757    }
16758
16759    @Override
16760    public List<String> getPreviousCodePaths(String packageName) {
16761        final int callingUid = Binder.getCallingUid();
16762        final List<String> result = new ArrayList<>();
16763        if (getInstantAppPackageName(callingUid) != null) {
16764            return result;
16765        }
16766        final PackageSetting ps = mSettings.mPackages.get(packageName);
16767        if (ps != null
16768                && ps.oldCodePaths != null
16769                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16770            result.addAll(ps.oldCodePaths);
16771        }
16772        return result;
16773    }
16774
16775    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16776            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16777            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16778            int installReason) {
16779        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16780                + deletedPackage);
16781
16782        String pkgName = deletedPackage.packageName;
16783        boolean deletedPkg = true;
16784        boolean addedPkg = false;
16785        boolean updatedSettings = false;
16786        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16787        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16788                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16789
16790        final long origUpdateTime = (pkg.mExtras != null)
16791                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16792
16793        // First delete the existing package while retaining the data directory
16794        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16795                res.removedInfo, true, pkg)) {
16796            // If the existing package wasn't successfully deleted
16797            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16798            deletedPkg = false;
16799        } else {
16800            // Successfully deleted the old package; proceed with replace.
16801
16802            // If deleted package lived in a container, give users a chance to
16803            // relinquish resources before killing.
16804            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16805                if (DEBUG_INSTALL) {
16806                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16807                }
16808                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16809                final ArrayList<String> pkgList = new ArrayList<String>(1);
16810                pkgList.add(deletedPackage.applicationInfo.packageName);
16811                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16812            }
16813
16814            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16815                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16816            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16817
16818            try {
16819                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16820                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16821                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16822                        installReason);
16823
16824                // Update the in-memory copy of the previous code paths.
16825                PackageSetting ps = mSettings.mPackages.get(pkgName);
16826                if (!killApp) {
16827                    if (ps.oldCodePaths == null) {
16828                        ps.oldCodePaths = new ArraySet<>();
16829                    }
16830                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16831                    if (deletedPackage.splitCodePaths != null) {
16832                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16833                    }
16834                } else {
16835                    ps.oldCodePaths = null;
16836                }
16837                if (ps.childPackageNames != null) {
16838                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16839                        final String childPkgName = ps.childPackageNames.get(i);
16840                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16841                        childPs.oldCodePaths = ps.oldCodePaths;
16842                    }
16843                }
16844                // set instant app status, but, only if it's explicitly specified
16845                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16846                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16847                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16848                prepareAppDataAfterInstallLIF(newPackage);
16849                addedPkg = true;
16850                mDexManager.notifyPackageUpdated(newPackage.packageName,
16851                        newPackage.baseCodePath, newPackage.splitCodePaths);
16852            } catch (PackageManagerException e) {
16853                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16854            }
16855        }
16856
16857        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16858            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16859
16860            // Revert all internal state mutations and added folders for the failed install
16861            if (addedPkg) {
16862                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16863                        res.removedInfo, true, null);
16864            }
16865
16866            // Restore the old package
16867            if (deletedPkg) {
16868                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16869                File restoreFile = new File(deletedPackage.codePath);
16870                // Parse old package
16871                boolean oldExternal = isExternal(deletedPackage);
16872                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16873                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16874                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16875                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16876                try {
16877                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16878                            null);
16879                } catch (PackageManagerException e) {
16880                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16881                            + e.getMessage());
16882                    return;
16883                }
16884
16885                synchronized (mPackages) {
16886                    // Ensure the installer package name up to date
16887                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16888
16889                    // Update permissions for restored package
16890                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16891
16892                    mSettings.writeLPr();
16893                }
16894
16895                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16896            }
16897        } else {
16898            synchronized (mPackages) {
16899                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16900                if (ps != null) {
16901                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16902                    if (res.removedInfo.removedChildPackages != null) {
16903                        final int childCount = res.removedInfo.removedChildPackages.size();
16904                        // Iterate in reverse as we may modify the collection
16905                        for (int i = childCount - 1; i >= 0; i--) {
16906                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16907                            if (res.addedChildPackages.containsKey(childPackageName)) {
16908                                res.removedInfo.removedChildPackages.removeAt(i);
16909                            } else {
16910                                PackageRemovedInfo childInfo = res.removedInfo
16911                                        .removedChildPackages.valueAt(i);
16912                                childInfo.removedForAllUsers = mPackages.get(
16913                                        childInfo.removedPackage) == null;
16914                            }
16915                        }
16916                    }
16917                }
16918            }
16919        }
16920    }
16921
16922    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16923            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16924            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16925            int installReason) {
16926        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16927                + ", old=" + deletedPackage);
16928
16929        final boolean disabledSystem;
16930
16931        // Remove existing system package
16932        removePackageLI(deletedPackage, true);
16933
16934        synchronized (mPackages) {
16935            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16936        }
16937        if (!disabledSystem) {
16938            // We didn't need to disable the .apk as a current system package,
16939            // which means we are replacing another update that is already
16940            // installed.  We need to make sure to delete the older one's .apk.
16941            res.removedInfo.args = createInstallArgsForExisting(0,
16942                    deletedPackage.applicationInfo.getCodePath(),
16943                    deletedPackage.applicationInfo.getResourcePath(),
16944                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16945        } else {
16946            res.removedInfo.args = null;
16947        }
16948
16949        // Successfully disabled the old package. Now proceed with re-installation
16950        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16951                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16952        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16953
16954        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16955        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16956                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16957
16958        PackageParser.Package newPackage = null;
16959        try {
16960            // Add the package to the internal data structures
16961            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16962
16963            // Set the update and install times
16964            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16965            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16966                    System.currentTimeMillis());
16967
16968            // Update the package dynamic state if succeeded
16969            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16970                // Now that the install succeeded make sure we remove data
16971                // directories for any child package the update removed.
16972                final int deletedChildCount = (deletedPackage.childPackages != null)
16973                        ? deletedPackage.childPackages.size() : 0;
16974                final int newChildCount = (newPackage.childPackages != null)
16975                        ? newPackage.childPackages.size() : 0;
16976                for (int i = 0; i < deletedChildCount; i++) {
16977                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16978                    boolean childPackageDeleted = true;
16979                    for (int j = 0; j < newChildCount; j++) {
16980                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16981                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16982                            childPackageDeleted = false;
16983                            break;
16984                        }
16985                    }
16986                    if (childPackageDeleted) {
16987                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16988                                deletedChildPkg.packageName);
16989                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16990                            PackageRemovedInfo removedChildRes = res.removedInfo
16991                                    .removedChildPackages.get(deletedChildPkg.packageName);
16992                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16993                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16994                        }
16995                    }
16996                }
16997
16998                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16999                        installReason);
17000                prepareAppDataAfterInstallLIF(newPackage);
17001
17002                mDexManager.notifyPackageUpdated(newPackage.packageName,
17003                            newPackage.baseCodePath, newPackage.splitCodePaths);
17004            }
17005        } catch (PackageManagerException e) {
17006            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17007            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17008        }
17009
17010        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17011            // Re installation failed. Restore old information
17012            // Remove new pkg information
17013            if (newPackage != null) {
17014                removeInstalledPackageLI(newPackage, true);
17015            }
17016            // Add back the old system package
17017            try {
17018                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17019            } catch (PackageManagerException e) {
17020                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17021            }
17022
17023            synchronized (mPackages) {
17024                if (disabledSystem) {
17025                    enableSystemPackageLPw(deletedPackage);
17026                }
17027
17028                // Ensure the installer package name up to date
17029                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17030
17031                // Update permissions for restored package
17032                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17033
17034                mSettings.writeLPr();
17035            }
17036
17037            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17038                    + " after failed upgrade");
17039        }
17040    }
17041
17042    /**
17043     * Checks whether the parent or any of the child packages have a change shared
17044     * user. For a package to be a valid update the shred users of the parent and
17045     * the children should match. We may later support changing child shared users.
17046     * @param oldPkg The updated package.
17047     * @param newPkg The update package.
17048     * @return The shared user that change between the versions.
17049     */
17050    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17051            PackageParser.Package newPkg) {
17052        // Check parent shared user
17053        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17054            return newPkg.packageName;
17055        }
17056        // Check child shared users
17057        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17058        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17059        for (int i = 0; i < newChildCount; i++) {
17060            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17061            // If this child was present, did it have the same shared user?
17062            for (int j = 0; j < oldChildCount; j++) {
17063                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17064                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17065                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17066                    return newChildPkg.packageName;
17067                }
17068            }
17069        }
17070        return null;
17071    }
17072
17073    private void removeNativeBinariesLI(PackageSetting ps) {
17074        // Remove the lib path for the parent package
17075        if (ps != null) {
17076            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17077            // Remove the lib path for the child packages
17078            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17079            for (int i = 0; i < childCount; i++) {
17080                PackageSetting childPs = null;
17081                synchronized (mPackages) {
17082                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17083                }
17084                if (childPs != null) {
17085                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17086                            .legacyNativeLibraryPathString);
17087                }
17088            }
17089        }
17090    }
17091
17092    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17093        // Enable the parent package
17094        mSettings.enableSystemPackageLPw(pkg.packageName);
17095        // Enable the child packages
17096        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17097        for (int i = 0; i < childCount; i++) {
17098            PackageParser.Package childPkg = pkg.childPackages.get(i);
17099            mSettings.enableSystemPackageLPw(childPkg.packageName);
17100        }
17101    }
17102
17103    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17104            PackageParser.Package newPkg) {
17105        // Disable the parent package (parent always replaced)
17106        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17107        // Disable the child packages
17108        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17109        for (int i = 0; i < childCount; i++) {
17110            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17111            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17112            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17113        }
17114        return disabled;
17115    }
17116
17117    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17118            String installerPackageName) {
17119        // Enable the parent package
17120        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17121        // Enable the child packages
17122        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17123        for (int i = 0; i < childCount; i++) {
17124            PackageParser.Package childPkg = pkg.childPackages.get(i);
17125            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17126        }
17127    }
17128
17129    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17130            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17131        // Update the parent package setting
17132        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17133                res, user, installReason);
17134        // Update the child packages setting
17135        final int childCount = (newPackage.childPackages != null)
17136                ? newPackage.childPackages.size() : 0;
17137        for (int i = 0; i < childCount; i++) {
17138            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17139            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17140            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17141                    childRes.origUsers, childRes, user, installReason);
17142        }
17143    }
17144
17145    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17146            String installerPackageName, int[] allUsers, int[] installedForUsers,
17147            PackageInstalledInfo res, UserHandle user, int installReason) {
17148        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17149
17150        String pkgName = newPackage.packageName;
17151        synchronized (mPackages) {
17152            //write settings. the installStatus will be incomplete at this stage.
17153            //note that the new package setting would have already been
17154            //added to mPackages. It hasn't been persisted yet.
17155            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17156            // TODO: Remove this write? It's also written at the end of this method
17157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17158            mSettings.writeLPr();
17159            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17160        }
17161
17162        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17163        synchronized (mPackages) {
17164            updatePermissionsLPw(newPackage.packageName, newPackage,
17165                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17166                            ? UPDATE_PERMISSIONS_ALL : 0));
17167            // For system-bundled packages, we assume that installing an upgraded version
17168            // of the package implies that the user actually wants to run that new code,
17169            // so we enable the package.
17170            PackageSetting ps = mSettings.mPackages.get(pkgName);
17171            final int userId = user.getIdentifier();
17172            if (ps != null) {
17173                if (isSystemApp(newPackage)) {
17174                    if (DEBUG_INSTALL) {
17175                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17176                    }
17177                    // Enable system package for requested users
17178                    if (res.origUsers != null) {
17179                        for (int origUserId : res.origUsers) {
17180                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17181                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17182                                        origUserId, installerPackageName);
17183                            }
17184                        }
17185                    }
17186                    // Also convey the prior install/uninstall state
17187                    if (allUsers != null && installedForUsers != null) {
17188                        for (int currentUserId : allUsers) {
17189                            final boolean installed = ArrayUtils.contains(
17190                                    installedForUsers, currentUserId);
17191                            if (DEBUG_INSTALL) {
17192                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17193                            }
17194                            ps.setInstalled(installed, currentUserId);
17195                        }
17196                        // these install state changes will be persisted in the
17197                        // upcoming call to mSettings.writeLPr().
17198                    }
17199                }
17200                // It's implied that when a user requests installation, they want the app to be
17201                // installed and enabled.
17202                if (userId != UserHandle.USER_ALL) {
17203                    ps.setInstalled(true, userId);
17204                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17205                }
17206
17207                // When replacing an existing package, preserve the original install reason for all
17208                // users that had the package installed before.
17209                final Set<Integer> previousUserIds = new ArraySet<>();
17210                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17211                    final int installReasonCount = res.removedInfo.installReasons.size();
17212                    for (int i = 0; i < installReasonCount; i++) {
17213                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17214                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17215                        ps.setInstallReason(previousInstallReason, previousUserId);
17216                        previousUserIds.add(previousUserId);
17217                    }
17218                }
17219
17220                // Set install reason for users that are having the package newly installed.
17221                if (userId == UserHandle.USER_ALL) {
17222                    for (int currentUserId : sUserManager.getUserIds()) {
17223                        if (!previousUserIds.contains(currentUserId)) {
17224                            ps.setInstallReason(installReason, currentUserId);
17225                        }
17226                    }
17227                } else if (!previousUserIds.contains(userId)) {
17228                    ps.setInstallReason(installReason, userId);
17229                }
17230                mSettings.writeKernelMappingLPr(ps);
17231            }
17232            res.name = pkgName;
17233            res.uid = newPackage.applicationInfo.uid;
17234            res.pkg = newPackage;
17235            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17236            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17237            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17238            //to update install status
17239            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17240            mSettings.writeLPr();
17241            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17242        }
17243
17244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17245    }
17246
17247    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17248        try {
17249            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17250            installPackageLI(args, res);
17251        } finally {
17252            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17253        }
17254    }
17255
17256    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17257        final int installFlags = args.installFlags;
17258        final String installerPackageName = args.installerPackageName;
17259        final String volumeUuid = args.volumeUuid;
17260        final File tmpPackageFile = new File(args.getCodePath());
17261        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17262        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17263                || (args.volumeUuid != null));
17264        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17265        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17266        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17267        final boolean virtualPreload =
17268                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17269        boolean replace = false;
17270        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17271        if (args.move != null) {
17272            // moving a complete application; perform an initial scan on the new install location
17273            scanFlags |= SCAN_INITIAL;
17274        }
17275        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17276            scanFlags |= SCAN_DONT_KILL_APP;
17277        }
17278        if (instantApp) {
17279            scanFlags |= SCAN_AS_INSTANT_APP;
17280        }
17281        if (fullApp) {
17282            scanFlags |= SCAN_AS_FULL_APP;
17283        }
17284        if (virtualPreload) {
17285            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17286        }
17287
17288        // Result object to be returned
17289        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17290        res.installerPackageName = installerPackageName;
17291
17292        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17293
17294        // Sanity check
17295        if (instantApp && (forwardLocked || onExternal)) {
17296            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17297                    + " external=" + onExternal);
17298            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17299            return;
17300        }
17301
17302        // Retrieve PackageSettings and parse package
17303        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17304                | PackageParser.PARSE_ENFORCE_CODE
17305                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17306                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17307                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17308                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17309        PackageParser pp = new PackageParser();
17310        pp.setSeparateProcesses(mSeparateProcesses);
17311        pp.setDisplayMetrics(mMetrics);
17312        pp.setCallback(mPackageParserCallback);
17313
17314        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17315        final PackageParser.Package pkg;
17316        try {
17317            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17318        } catch (PackageParserException e) {
17319            res.setError("Failed parse during installPackageLI", e);
17320            return;
17321        } finally {
17322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17323        }
17324
17325        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17326        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17327            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17328            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17329                    "Instant app package must target O");
17330            return;
17331        }
17332        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17333            Slog.w(TAG, "Instant app package " + pkg.packageName
17334                    + " does not target targetSandboxVersion 2");
17335            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17336                    "Instant app package must use targetSanboxVersion 2");
17337            return;
17338        }
17339
17340        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17341            // Static shared libraries have synthetic package names
17342            renameStaticSharedLibraryPackage(pkg);
17343
17344            // No static shared libs on external storage
17345            if (onExternal) {
17346                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17347                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17348                        "Packages declaring static-shared libs cannot be updated");
17349                return;
17350            }
17351        }
17352
17353        // If we are installing a clustered package add results for the children
17354        if (pkg.childPackages != null) {
17355            synchronized (mPackages) {
17356                final int childCount = pkg.childPackages.size();
17357                for (int i = 0; i < childCount; i++) {
17358                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17359                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17360                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17361                    childRes.pkg = childPkg;
17362                    childRes.name = childPkg.packageName;
17363                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17364                    if (childPs != null) {
17365                        childRes.origUsers = childPs.queryInstalledUsers(
17366                                sUserManager.getUserIds(), true);
17367                    }
17368                    if ((mPackages.containsKey(childPkg.packageName))) {
17369                        childRes.removedInfo = new PackageRemovedInfo(this);
17370                        childRes.removedInfo.removedPackage = childPkg.packageName;
17371                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17372                    }
17373                    if (res.addedChildPackages == null) {
17374                        res.addedChildPackages = new ArrayMap<>();
17375                    }
17376                    res.addedChildPackages.put(childPkg.packageName, childRes);
17377                }
17378            }
17379        }
17380
17381        // If package doesn't declare API override, mark that we have an install
17382        // time CPU ABI override.
17383        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17384            pkg.cpuAbiOverride = args.abiOverride;
17385        }
17386
17387        String pkgName = res.name = pkg.packageName;
17388        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17389            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17390                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17391                return;
17392            }
17393        }
17394
17395        try {
17396            // either use what we've been given or parse directly from the APK
17397            if (args.certificates != null) {
17398                try {
17399                    PackageParser.populateCertificates(pkg, args.certificates);
17400                } catch (PackageParserException e) {
17401                    // there was something wrong with the certificates we were given;
17402                    // try to pull them from the APK
17403                    PackageParser.collectCertificates(pkg, parseFlags);
17404                }
17405            } else {
17406                PackageParser.collectCertificates(pkg, parseFlags);
17407            }
17408        } catch (PackageParserException e) {
17409            res.setError("Failed collect during installPackageLI", e);
17410            return;
17411        }
17412
17413        // Get rid of all references to package scan path via parser.
17414        pp = null;
17415        String oldCodePath = null;
17416        boolean systemApp = false;
17417        synchronized (mPackages) {
17418            // Check if installing already existing package
17419            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17420                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17421                if (pkg.mOriginalPackages != null
17422                        && pkg.mOriginalPackages.contains(oldName)
17423                        && mPackages.containsKey(oldName)) {
17424                    // This package is derived from an original package,
17425                    // and this device has been updating from that original
17426                    // name.  We must continue using the original name, so
17427                    // rename the new package here.
17428                    pkg.setPackageName(oldName);
17429                    pkgName = pkg.packageName;
17430                    replace = true;
17431                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17432                            + oldName + " pkgName=" + pkgName);
17433                } else if (mPackages.containsKey(pkgName)) {
17434                    // This package, under its official name, already exists
17435                    // on the device; we should replace it.
17436                    replace = true;
17437                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17438                }
17439
17440                // Child packages are installed through the parent package
17441                if (pkg.parentPackage != null) {
17442                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17443                            "Package " + pkg.packageName + " is child of package "
17444                                    + pkg.parentPackage.parentPackage + ". Child packages "
17445                                    + "can be updated only through the parent package.");
17446                    return;
17447                }
17448
17449                if (replace) {
17450                    // Prevent apps opting out from runtime permissions
17451                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17452                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17453                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17454                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17455                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17456                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17457                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17458                                        + " doesn't support runtime permissions but the old"
17459                                        + " target SDK " + oldTargetSdk + " does.");
17460                        return;
17461                    }
17462                    // Prevent apps from downgrading their targetSandbox.
17463                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17464                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17465                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17466                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17467                                "Package " + pkg.packageName + " new target sandbox "
17468                                + newTargetSandbox + " is incompatible with the previous value of"
17469                                + oldTargetSandbox + ".");
17470                        return;
17471                    }
17472
17473                    // Prevent installing of child packages
17474                    if (oldPackage.parentPackage != null) {
17475                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17476                                "Package " + pkg.packageName + " is child of package "
17477                                        + oldPackage.parentPackage + ". Child packages "
17478                                        + "can be updated only through the parent package.");
17479                        return;
17480                    }
17481                }
17482            }
17483
17484            PackageSetting ps = mSettings.mPackages.get(pkgName);
17485            if (ps != null) {
17486                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17487
17488                // Static shared libs have same package with different versions where
17489                // we internally use a synthetic package name to allow multiple versions
17490                // of the same package, therefore we need to compare signatures against
17491                // the package setting for the latest library version.
17492                PackageSetting signatureCheckPs = ps;
17493                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17494                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17495                    if (libraryEntry != null) {
17496                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17497                    }
17498                }
17499
17500                // Quick sanity check that we're signed correctly if updating;
17501                // we'll check this again later when scanning, but we want to
17502                // bail early here before tripping over redefined permissions.
17503                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17504                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17505                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17506                                + pkg.packageName + " upgrade keys do not match the "
17507                                + "previously installed version");
17508                        return;
17509                    }
17510                } else {
17511                    try {
17512                        verifySignaturesLP(signatureCheckPs, pkg);
17513                    } catch (PackageManagerException e) {
17514                        res.setError(e.error, e.getMessage());
17515                        return;
17516                    }
17517                }
17518
17519                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17520                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17521                    systemApp = (ps.pkg.applicationInfo.flags &
17522                            ApplicationInfo.FLAG_SYSTEM) != 0;
17523                }
17524                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17525            }
17526
17527            int N = pkg.permissions.size();
17528            for (int i = N-1; i >= 0; i--) {
17529                final PackageParser.Permission perm = pkg.permissions.get(i);
17530                final BasePermission bp =
17531                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17532
17533                // Don't allow anyone but the system to define ephemeral permissions.
17534                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17535                        && !systemApp) {
17536                    Slog.w(TAG, "Non-System package " + pkg.packageName
17537                            + " attempting to delcare ephemeral permission "
17538                            + perm.info.name + "; Removing ephemeral.");
17539                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17540                }
17541
17542                // Check whether the newly-scanned package wants to define an already-defined perm
17543                if (bp != null) {
17544                    // If the defining package is signed with our cert, it's okay.  This
17545                    // also includes the "updating the same package" case, of course.
17546                    // "updating same package" could also involve key-rotation.
17547                    final boolean sigsOk;
17548                    final String sourcePackageName = bp.getSourcePackageName();
17549                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17550                    if (sourcePackageName.equals(pkg.packageName)
17551                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17552                                    scanFlags))) {
17553                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17554                    } else {
17555                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17556                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17557                    }
17558                    if (!sigsOk) {
17559                        // If the owning package is the system itself, we log but allow
17560                        // install to proceed; we fail the install on all other permission
17561                        // redefinitions.
17562                        if (!sourcePackageName.equals("android")) {
17563                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17564                                    + pkg.packageName + " attempting to redeclare permission "
17565                                    + perm.info.name + " already owned by " + sourcePackageName);
17566                            res.origPermission = perm.info.name;
17567                            res.origPackage = sourcePackageName;
17568                            return;
17569                        } else {
17570                            Slog.w(TAG, "Package " + pkg.packageName
17571                                    + " attempting to redeclare system permission "
17572                                    + perm.info.name + "; ignoring new declaration");
17573                            pkg.permissions.remove(i);
17574                        }
17575                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17576                        // Prevent apps to change protection level to dangerous from any other
17577                        // type as this would allow a privilege escalation where an app adds a
17578                        // normal/signature permission in other app's group and later redefines
17579                        // it as dangerous leading to the group auto-grant.
17580                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17581                                == PermissionInfo.PROTECTION_DANGEROUS) {
17582                            if (bp != null && !bp.isRuntime()) {
17583                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17584                                        + "non-runtime permission " + perm.info.name
17585                                        + " to runtime; keeping old protection level");
17586                                perm.info.protectionLevel = bp.getProtectionLevel();
17587                            }
17588                        }
17589                    }
17590                }
17591            }
17592        }
17593
17594        if (systemApp) {
17595            if (onExternal) {
17596                // Abort update; system app can't be replaced with app on sdcard
17597                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17598                        "Cannot install updates to system apps on sdcard");
17599                return;
17600            } else if (instantApp) {
17601                // Abort update; system app can't be replaced with an instant app
17602                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17603                        "Cannot update a system app with an instant app");
17604                return;
17605            }
17606        }
17607
17608        if (args.move != null) {
17609            // We did an in-place move, so dex is ready to roll
17610            scanFlags |= SCAN_NO_DEX;
17611            scanFlags |= SCAN_MOVE;
17612
17613            synchronized (mPackages) {
17614                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17615                if (ps == null) {
17616                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17617                            "Missing settings for moved package " + pkgName);
17618                }
17619
17620                // We moved the entire application as-is, so bring over the
17621                // previously derived ABI information.
17622                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17623                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17624            }
17625
17626        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17627            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17628            scanFlags |= SCAN_NO_DEX;
17629
17630            try {
17631                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17632                    args.abiOverride : pkg.cpuAbiOverride);
17633                final boolean extractNativeLibs = !pkg.isLibrary();
17634                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17635                        extractNativeLibs, mAppLib32InstallDir);
17636            } catch (PackageManagerException pme) {
17637                Slog.e(TAG, "Error deriving application ABI", pme);
17638                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17639                return;
17640            }
17641
17642            // Shared libraries for the package need to be updated.
17643            synchronized (mPackages) {
17644                try {
17645                    updateSharedLibrariesLPr(pkg, null);
17646                } catch (PackageManagerException e) {
17647                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17648                }
17649            }
17650        }
17651
17652        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17653            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17654            return;
17655        }
17656
17657        // Verify if we need to dexopt the app.
17658        //
17659        // NOTE: it is *important* to call dexopt after doRename which will sync the
17660        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17661        //
17662        // We only need to dexopt if the package meets ALL of the following conditions:
17663        //   1) it is not forward locked.
17664        //   2) it is not on on an external ASEC container.
17665        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17666        //
17667        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17668        // complete, so we skip this step during installation. Instead, we'll take extra time
17669        // the first time the instant app starts. It's preferred to do it this way to provide
17670        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17671        // middle of running an instant app. The default behaviour can be overridden
17672        // via gservices.
17673        final boolean performDexopt = !forwardLocked
17674            && !pkg.applicationInfo.isExternalAsec()
17675            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17676                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17677
17678        if (performDexopt) {
17679            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17680            // Do not run PackageDexOptimizer through the local performDexOpt
17681            // method because `pkg` may not be in `mPackages` yet.
17682            //
17683            // Also, don't fail application installs if the dexopt step fails.
17684            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17685                REASON_INSTALL,
17686                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17687            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17688                null /* instructionSets */,
17689                getOrCreateCompilerPackageStats(pkg),
17690                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17691                dexoptOptions);
17692            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17693        }
17694
17695        // Notify BackgroundDexOptService that the package has been changed.
17696        // If this is an update of a package which used to fail to compile,
17697        // BackgroundDexOptService will remove it from its blacklist.
17698        // TODO: Layering violation
17699        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17700
17701        if (!instantApp) {
17702            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17703        } else {
17704            if (DEBUG_DOMAIN_VERIFICATION) {
17705                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17706            }
17707        }
17708
17709        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17710                "installPackageLI")) {
17711            if (replace) {
17712                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17713                    // Static libs have a synthetic package name containing the version
17714                    // and cannot be updated as an update would get a new package name,
17715                    // unless this is the exact same version code which is useful for
17716                    // development.
17717                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17718                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17719                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17720                                + "static-shared libs cannot be updated");
17721                        return;
17722                    }
17723                }
17724                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17725                        installerPackageName, res, args.installReason);
17726            } else {
17727                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17728                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17729            }
17730        }
17731
17732        synchronized (mPackages) {
17733            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17734            if (ps != null) {
17735                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17736                ps.setUpdateAvailable(false /*updateAvailable*/);
17737            }
17738
17739            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17740            for (int i = 0; i < childCount; i++) {
17741                PackageParser.Package childPkg = pkg.childPackages.get(i);
17742                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17743                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17744                if (childPs != null) {
17745                    childRes.newUsers = childPs.queryInstalledUsers(
17746                            sUserManager.getUserIds(), true);
17747                }
17748            }
17749
17750            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17751                updateSequenceNumberLP(ps, res.newUsers);
17752                updateInstantAppInstallerLocked(pkgName);
17753            }
17754        }
17755    }
17756
17757    private void startIntentFilterVerifications(int userId, boolean replacing,
17758            PackageParser.Package pkg) {
17759        if (mIntentFilterVerifierComponent == null) {
17760            Slog.w(TAG, "No IntentFilter verification will not be done as "
17761                    + "there is no IntentFilterVerifier available!");
17762            return;
17763        }
17764
17765        final int verifierUid = getPackageUid(
17766                mIntentFilterVerifierComponent.getPackageName(),
17767                MATCH_DEBUG_TRIAGED_MISSING,
17768                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17769
17770        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17771        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17772        mHandler.sendMessage(msg);
17773
17774        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17775        for (int i = 0; i < childCount; i++) {
17776            PackageParser.Package childPkg = pkg.childPackages.get(i);
17777            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17778            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17779            mHandler.sendMessage(msg);
17780        }
17781    }
17782
17783    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17784            PackageParser.Package pkg) {
17785        int size = pkg.activities.size();
17786        if (size == 0) {
17787            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17788                    "No activity, so no need to verify any IntentFilter!");
17789            return;
17790        }
17791
17792        final boolean hasDomainURLs = hasDomainURLs(pkg);
17793        if (!hasDomainURLs) {
17794            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17795                    "No domain URLs, so no need to verify any IntentFilter!");
17796            return;
17797        }
17798
17799        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17800                + " if any IntentFilter from the " + size
17801                + " Activities needs verification ...");
17802
17803        int count = 0;
17804        final String packageName = pkg.packageName;
17805
17806        synchronized (mPackages) {
17807            // If this is a new install and we see that we've already run verification for this
17808            // package, we have nothing to do: it means the state was restored from backup.
17809            if (!replacing) {
17810                IntentFilterVerificationInfo ivi =
17811                        mSettings.getIntentFilterVerificationLPr(packageName);
17812                if (ivi != null) {
17813                    if (DEBUG_DOMAIN_VERIFICATION) {
17814                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17815                                + ivi.getStatusString());
17816                    }
17817                    return;
17818                }
17819            }
17820
17821            // If any filters need to be verified, then all need to be.
17822            boolean needToVerify = false;
17823            for (PackageParser.Activity a : pkg.activities) {
17824                for (ActivityIntentInfo filter : a.intents) {
17825                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17826                        if (DEBUG_DOMAIN_VERIFICATION) {
17827                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17828                        }
17829                        needToVerify = true;
17830                        break;
17831                    }
17832                }
17833            }
17834
17835            if (needToVerify) {
17836                final int verificationId = mIntentFilterVerificationToken++;
17837                for (PackageParser.Activity a : pkg.activities) {
17838                    for (ActivityIntentInfo filter : a.intents) {
17839                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17840                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17841                                    "Verification needed for IntentFilter:" + filter.toString());
17842                            mIntentFilterVerifier.addOneIntentFilterVerification(
17843                                    verifierUid, userId, verificationId, filter, packageName);
17844                            count++;
17845                        }
17846                    }
17847                }
17848            }
17849        }
17850
17851        if (count > 0) {
17852            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17853                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17854                    +  " for userId:" + userId);
17855            mIntentFilterVerifier.startVerifications(userId);
17856        } else {
17857            if (DEBUG_DOMAIN_VERIFICATION) {
17858                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17859            }
17860        }
17861    }
17862
17863    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17864        final ComponentName cn  = filter.activity.getComponentName();
17865        final String packageName = cn.getPackageName();
17866
17867        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17868                packageName);
17869        if (ivi == null) {
17870            return true;
17871        }
17872        int status = ivi.getStatus();
17873        switch (status) {
17874            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17875            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17876                return true;
17877
17878            default:
17879                // Nothing to do
17880                return false;
17881        }
17882    }
17883
17884    private static boolean isMultiArch(ApplicationInfo info) {
17885        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17886    }
17887
17888    private static boolean isExternal(PackageParser.Package pkg) {
17889        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17890    }
17891
17892    private static boolean isExternal(PackageSetting ps) {
17893        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17894    }
17895
17896    private static boolean isSystemApp(PackageParser.Package pkg) {
17897        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17898    }
17899
17900    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17901        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17902    }
17903
17904    private static boolean isOemApp(PackageParser.Package pkg) {
17905        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17906    }
17907
17908    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17909        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17910    }
17911
17912    private static boolean isSystemApp(PackageSetting ps) {
17913        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17914    }
17915
17916    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17917        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17918    }
17919
17920    private int packageFlagsToInstallFlags(PackageSetting ps) {
17921        int installFlags = 0;
17922        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17923            // This existing package was an external ASEC install when we have
17924            // the external flag without a UUID
17925            installFlags |= PackageManager.INSTALL_EXTERNAL;
17926        }
17927        if (ps.isForwardLocked()) {
17928            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17929        }
17930        return installFlags;
17931    }
17932
17933    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17934        if (isExternal(pkg)) {
17935            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17936                return StorageManager.UUID_PRIMARY_PHYSICAL;
17937            } else {
17938                return pkg.volumeUuid;
17939            }
17940        } else {
17941            return StorageManager.UUID_PRIVATE_INTERNAL;
17942        }
17943    }
17944
17945    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17946        if (isExternal(pkg)) {
17947            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17948                return mSettings.getExternalVersion();
17949            } else {
17950                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17951            }
17952        } else {
17953            return mSettings.getInternalVersion();
17954        }
17955    }
17956
17957    private void deleteTempPackageFiles() {
17958        final FilenameFilter filter = new FilenameFilter() {
17959            public boolean accept(File dir, String name) {
17960                return name.startsWith("vmdl") && name.endsWith(".tmp");
17961            }
17962        };
17963        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17964            file.delete();
17965        }
17966    }
17967
17968    @Override
17969    public void deletePackageAsUser(String packageName, int versionCode,
17970            IPackageDeleteObserver observer, int userId, int flags) {
17971        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17972                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17973    }
17974
17975    @Override
17976    public void deletePackageVersioned(VersionedPackage versionedPackage,
17977            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17978        final int callingUid = Binder.getCallingUid();
17979        mContext.enforceCallingOrSelfPermission(
17980                android.Manifest.permission.DELETE_PACKAGES, null);
17981        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17982        Preconditions.checkNotNull(versionedPackage);
17983        Preconditions.checkNotNull(observer);
17984        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17985                PackageManager.VERSION_CODE_HIGHEST,
17986                Integer.MAX_VALUE, "versionCode must be >= -1");
17987
17988        final String packageName = versionedPackage.getPackageName();
17989        final int versionCode = versionedPackage.getVersionCode();
17990        final String internalPackageName;
17991        synchronized (mPackages) {
17992            // Normalize package name to handle renamed packages and static libs
17993            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17994                    versionedPackage.getVersionCode());
17995        }
17996
17997        final int uid = Binder.getCallingUid();
17998        if (!isOrphaned(internalPackageName)
17999                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18000            try {
18001                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18002                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18003                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18004                observer.onUserActionRequired(intent);
18005            } catch (RemoteException re) {
18006            }
18007            return;
18008        }
18009        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18010        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18011        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18012            mContext.enforceCallingOrSelfPermission(
18013                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18014                    "deletePackage for user " + userId);
18015        }
18016
18017        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18018            try {
18019                observer.onPackageDeleted(packageName,
18020                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18021            } catch (RemoteException re) {
18022            }
18023            return;
18024        }
18025
18026        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18027            try {
18028                observer.onPackageDeleted(packageName,
18029                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18030            } catch (RemoteException re) {
18031            }
18032            return;
18033        }
18034
18035        if (DEBUG_REMOVE) {
18036            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18037                    + " deleteAllUsers: " + deleteAllUsers + " version="
18038                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18039                    ? "VERSION_CODE_HIGHEST" : versionCode));
18040        }
18041        // Queue up an async operation since the package deletion may take a little while.
18042        mHandler.post(new Runnable() {
18043            public void run() {
18044                mHandler.removeCallbacks(this);
18045                int returnCode;
18046                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18047                boolean doDeletePackage = true;
18048                if (ps != null) {
18049                    final boolean targetIsInstantApp =
18050                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18051                    doDeletePackage = !targetIsInstantApp
18052                            || canViewInstantApps;
18053                }
18054                if (doDeletePackage) {
18055                    if (!deleteAllUsers) {
18056                        returnCode = deletePackageX(internalPackageName, versionCode,
18057                                userId, deleteFlags);
18058                    } else {
18059                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18060                                internalPackageName, users);
18061                        // If nobody is blocking uninstall, proceed with delete for all users
18062                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18063                            returnCode = deletePackageX(internalPackageName, versionCode,
18064                                    userId, deleteFlags);
18065                        } else {
18066                            // Otherwise uninstall individually for users with blockUninstalls=false
18067                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18068                            for (int userId : users) {
18069                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18070                                    returnCode = deletePackageX(internalPackageName, versionCode,
18071                                            userId, userFlags);
18072                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18073                                        Slog.w(TAG, "Package delete failed for user " + userId
18074                                                + ", returnCode " + returnCode);
18075                                    }
18076                                }
18077                            }
18078                            // The app has only been marked uninstalled for certain users.
18079                            // We still need to report that delete was blocked
18080                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18081                        }
18082                    }
18083                } else {
18084                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18085                }
18086                try {
18087                    observer.onPackageDeleted(packageName, returnCode, null);
18088                } catch (RemoteException e) {
18089                    Log.i(TAG, "Observer no longer exists.");
18090                } //end catch
18091            } //end run
18092        });
18093    }
18094
18095    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18096        if (pkg.staticSharedLibName != null) {
18097            return pkg.manifestPackageName;
18098        }
18099        return pkg.packageName;
18100    }
18101
18102    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18103        // Handle renamed packages
18104        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18105        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18106
18107        // Is this a static library?
18108        SparseArray<SharedLibraryEntry> versionedLib =
18109                mStaticLibsByDeclaringPackage.get(packageName);
18110        if (versionedLib == null || versionedLib.size() <= 0) {
18111            return packageName;
18112        }
18113
18114        // Figure out which lib versions the caller can see
18115        SparseIntArray versionsCallerCanSee = null;
18116        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18117        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18118                && callingAppId != Process.ROOT_UID) {
18119            versionsCallerCanSee = new SparseIntArray();
18120            String libName = versionedLib.valueAt(0).info.getName();
18121            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18122            if (uidPackages != null) {
18123                for (String uidPackage : uidPackages) {
18124                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18125                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18126                    if (libIdx >= 0) {
18127                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18128                        versionsCallerCanSee.append(libVersion, libVersion);
18129                    }
18130                }
18131            }
18132        }
18133
18134        // Caller can see nothing - done
18135        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18136            return packageName;
18137        }
18138
18139        // Find the version the caller can see and the app version code
18140        SharedLibraryEntry highestVersion = null;
18141        final int versionCount = versionedLib.size();
18142        for (int i = 0; i < versionCount; i++) {
18143            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18144            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18145                    libEntry.info.getVersion()) < 0) {
18146                continue;
18147            }
18148            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18149            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18150                if (libVersionCode == versionCode) {
18151                    return libEntry.apk;
18152                }
18153            } else if (highestVersion == null) {
18154                highestVersion = libEntry;
18155            } else if (libVersionCode  > highestVersion.info
18156                    .getDeclaringPackage().getVersionCode()) {
18157                highestVersion = libEntry;
18158            }
18159        }
18160
18161        if (highestVersion != null) {
18162            return highestVersion.apk;
18163        }
18164
18165        return packageName;
18166    }
18167
18168    boolean isCallerVerifier(int callingUid) {
18169        final int callingUserId = UserHandle.getUserId(callingUid);
18170        return mRequiredVerifierPackage != null &&
18171                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18172    }
18173
18174    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18175        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18176              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18177            return true;
18178        }
18179        final int callingUserId = UserHandle.getUserId(callingUid);
18180        // If the caller installed the pkgName, then allow it to silently uninstall.
18181        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18182            return true;
18183        }
18184
18185        // Allow package verifier to silently uninstall.
18186        if (mRequiredVerifierPackage != null &&
18187                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18188            return true;
18189        }
18190
18191        // Allow package uninstaller to silently uninstall.
18192        if (mRequiredUninstallerPackage != null &&
18193                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18194            return true;
18195        }
18196
18197        // Allow storage manager to silently uninstall.
18198        if (mStorageManagerPackage != null &&
18199                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18200            return true;
18201        }
18202
18203        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18204        // uninstall for device owner provisioning.
18205        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18206                == PERMISSION_GRANTED) {
18207            return true;
18208        }
18209
18210        return false;
18211    }
18212
18213    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18214        int[] result = EMPTY_INT_ARRAY;
18215        for (int userId : userIds) {
18216            if (getBlockUninstallForUser(packageName, userId)) {
18217                result = ArrayUtils.appendInt(result, userId);
18218            }
18219        }
18220        return result;
18221    }
18222
18223    @Override
18224    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18225        final int callingUid = Binder.getCallingUid();
18226        if (getInstantAppPackageName(callingUid) != null
18227                && !isCallerSameApp(packageName, callingUid)) {
18228            return false;
18229        }
18230        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18231    }
18232
18233    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18234        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18235                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18236        try {
18237            if (dpm != null) {
18238                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18239                        /* callingUserOnly =*/ false);
18240                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18241                        : deviceOwnerComponentName.getPackageName();
18242                // Does the package contains the device owner?
18243                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18244                // this check is probably not needed, since DO should be registered as a device
18245                // admin on some user too. (Original bug for this: b/17657954)
18246                if (packageName.equals(deviceOwnerPackageName)) {
18247                    return true;
18248                }
18249                // Does it contain a device admin for any user?
18250                int[] users;
18251                if (userId == UserHandle.USER_ALL) {
18252                    users = sUserManager.getUserIds();
18253                } else {
18254                    users = new int[]{userId};
18255                }
18256                for (int i = 0; i < users.length; ++i) {
18257                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18258                        return true;
18259                    }
18260                }
18261            }
18262        } catch (RemoteException e) {
18263        }
18264        return false;
18265    }
18266
18267    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18268        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18269    }
18270
18271    /**
18272     *  This method is an internal method that could be get invoked either
18273     *  to delete an installed package or to clean up a failed installation.
18274     *  After deleting an installed package, a broadcast is sent to notify any
18275     *  listeners that the package has been removed. For cleaning up a failed
18276     *  installation, the broadcast is not necessary since the package's
18277     *  installation wouldn't have sent the initial broadcast either
18278     *  The key steps in deleting a package are
18279     *  deleting the package information in internal structures like mPackages,
18280     *  deleting the packages base directories through installd
18281     *  updating mSettings to reflect current status
18282     *  persisting settings for later use
18283     *  sending a broadcast if necessary
18284     */
18285    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18286        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18287        final boolean res;
18288
18289        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18290                ? UserHandle.USER_ALL : userId;
18291
18292        if (isPackageDeviceAdmin(packageName, removeUser)) {
18293            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18294            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18295        }
18296
18297        PackageSetting uninstalledPs = null;
18298        PackageParser.Package pkg = null;
18299
18300        // for the uninstall-updates case and restricted profiles, remember the per-
18301        // user handle installed state
18302        int[] allUsers;
18303        synchronized (mPackages) {
18304            uninstalledPs = mSettings.mPackages.get(packageName);
18305            if (uninstalledPs == null) {
18306                Slog.w(TAG, "Not removing non-existent package " + packageName);
18307                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18308            }
18309
18310            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18311                    && uninstalledPs.versionCode != versionCode) {
18312                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18313                        + uninstalledPs.versionCode + " != " + versionCode);
18314                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18315            }
18316
18317            // Static shared libs can be declared by any package, so let us not
18318            // allow removing a package if it provides a lib others depend on.
18319            pkg = mPackages.get(packageName);
18320
18321            allUsers = sUserManager.getUserIds();
18322
18323            if (pkg != null && pkg.staticSharedLibName != null) {
18324                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18325                        pkg.staticSharedLibVersion);
18326                if (libEntry != null) {
18327                    for (int currUserId : allUsers) {
18328                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18329                            continue;
18330                        }
18331                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18332                                libEntry.info, 0, currUserId);
18333                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18334                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18335                                    + " hosting lib " + libEntry.info.getName() + " version "
18336                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18337                                    + " for user " + currUserId);
18338                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18339                        }
18340                    }
18341                }
18342            }
18343
18344            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18345        }
18346
18347        final int freezeUser;
18348        if (isUpdatedSystemApp(uninstalledPs)
18349                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18350            // We're downgrading a system app, which will apply to all users, so
18351            // freeze them all during the downgrade
18352            freezeUser = UserHandle.USER_ALL;
18353        } else {
18354            freezeUser = removeUser;
18355        }
18356
18357        synchronized (mInstallLock) {
18358            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18359            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18360                    deleteFlags, "deletePackageX")) {
18361                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18362                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18363            }
18364            synchronized (mPackages) {
18365                if (res) {
18366                    if (pkg != null) {
18367                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18368                    }
18369                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18370                    updateInstantAppInstallerLocked(packageName);
18371                }
18372            }
18373        }
18374
18375        if (res) {
18376            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18377            info.sendPackageRemovedBroadcasts(killApp);
18378            info.sendSystemPackageUpdatedBroadcasts();
18379            info.sendSystemPackageAppearedBroadcasts();
18380        }
18381        // Force a gc here.
18382        Runtime.getRuntime().gc();
18383        // Delete the resources here after sending the broadcast to let
18384        // other processes clean up before deleting resources.
18385        if (info.args != null) {
18386            synchronized (mInstallLock) {
18387                info.args.doPostDeleteLI(true);
18388            }
18389        }
18390
18391        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18392    }
18393
18394    static class PackageRemovedInfo {
18395        final PackageSender packageSender;
18396        String removedPackage;
18397        String installerPackageName;
18398        int uid = -1;
18399        int removedAppId = -1;
18400        int[] origUsers;
18401        int[] removedUsers = null;
18402        int[] broadcastUsers = null;
18403        SparseArray<Integer> installReasons;
18404        boolean isRemovedPackageSystemUpdate = false;
18405        boolean isUpdate;
18406        boolean dataRemoved;
18407        boolean removedForAllUsers;
18408        boolean isStaticSharedLib;
18409        // Clean up resources deleted packages.
18410        InstallArgs args = null;
18411        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18412        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18413
18414        PackageRemovedInfo(PackageSender packageSender) {
18415            this.packageSender = packageSender;
18416        }
18417
18418        void sendPackageRemovedBroadcasts(boolean killApp) {
18419            sendPackageRemovedBroadcastInternal(killApp);
18420            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18421            for (int i = 0; i < childCount; i++) {
18422                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18423                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18424            }
18425        }
18426
18427        void sendSystemPackageUpdatedBroadcasts() {
18428            if (isRemovedPackageSystemUpdate) {
18429                sendSystemPackageUpdatedBroadcastsInternal();
18430                final int childCount = (removedChildPackages != null)
18431                        ? removedChildPackages.size() : 0;
18432                for (int i = 0; i < childCount; i++) {
18433                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18434                    if (childInfo.isRemovedPackageSystemUpdate) {
18435                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18436                    }
18437                }
18438            }
18439        }
18440
18441        void sendSystemPackageAppearedBroadcasts() {
18442            final int packageCount = (appearedChildPackages != null)
18443                    ? appearedChildPackages.size() : 0;
18444            for (int i = 0; i < packageCount; i++) {
18445                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18446                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18447                    true /*sendBootCompleted*/, false /*startReceiver*/,
18448                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18449            }
18450        }
18451
18452        private void sendSystemPackageUpdatedBroadcastsInternal() {
18453            Bundle extras = new Bundle(2);
18454            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18455            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18456            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18457                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18458            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18459                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18460            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18461                null, null, 0, removedPackage, null, null);
18462            if (installerPackageName != null) {
18463                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18464                        removedPackage, extras, 0 /*flags*/,
18465                        installerPackageName, null, null);
18466                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18467                        removedPackage, extras, 0 /*flags*/,
18468                        installerPackageName, null, null);
18469            }
18470        }
18471
18472        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18473            // Don't send static shared library removal broadcasts as these
18474            // libs are visible only the the apps that depend on them an one
18475            // cannot remove the library if it has a dependency.
18476            if (isStaticSharedLib) {
18477                return;
18478            }
18479            Bundle extras = new Bundle(2);
18480            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18481            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18482            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18483            if (isUpdate || isRemovedPackageSystemUpdate) {
18484                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18485            }
18486            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18487            if (removedPackage != null) {
18488                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18489                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18490                if (installerPackageName != null) {
18491                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18492                            removedPackage, extras, 0 /*flags*/,
18493                            installerPackageName, null, broadcastUsers);
18494                }
18495                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18496                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18497                        removedPackage, extras,
18498                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18499                        null, null, broadcastUsers);
18500                }
18501            }
18502            if (removedAppId >= 0) {
18503                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18504                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18505                    null, null, broadcastUsers);
18506            }
18507        }
18508
18509        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18510            removedUsers = userIds;
18511            if (removedUsers == null) {
18512                broadcastUsers = null;
18513                return;
18514            }
18515
18516            broadcastUsers = EMPTY_INT_ARRAY;
18517            for (int i = userIds.length - 1; i >= 0; --i) {
18518                final int userId = userIds[i];
18519                if (deletedPackageSetting.getInstantApp(userId)) {
18520                    continue;
18521                }
18522                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18523            }
18524        }
18525    }
18526
18527    /*
18528     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18529     * flag is not set, the data directory is removed as well.
18530     * make sure this flag is set for partially installed apps. If not its meaningless to
18531     * delete a partially installed application.
18532     */
18533    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18534            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18535        String packageName = ps.name;
18536        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18537        // Retrieve object to delete permissions for shared user later on
18538        final PackageParser.Package deletedPkg;
18539        final PackageSetting deletedPs;
18540        // reader
18541        synchronized (mPackages) {
18542            deletedPkg = mPackages.get(packageName);
18543            deletedPs = mSettings.mPackages.get(packageName);
18544            if (outInfo != null) {
18545                outInfo.removedPackage = packageName;
18546                outInfo.installerPackageName = ps.installerPackageName;
18547                outInfo.isStaticSharedLib = deletedPkg != null
18548                        && deletedPkg.staticSharedLibName != null;
18549                outInfo.populateUsers(deletedPs == null ? null
18550                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18551            }
18552        }
18553
18554        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18555
18556        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18557            final PackageParser.Package resolvedPkg;
18558            if (deletedPkg != null) {
18559                resolvedPkg = deletedPkg;
18560            } else {
18561                // We don't have a parsed package when it lives on an ejected
18562                // adopted storage device, so fake something together
18563                resolvedPkg = new PackageParser.Package(ps.name);
18564                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18565            }
18566            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18567                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18568            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18569            if (outInfo != null) {
18570                outInfo.dataRemoved = true;
18571            }
18572            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18573        }
18574
18575        int removedAppId = -1;
18576
18577        // writer
18578        synchronized (mPackages) {
18579            boolean installedStateChanged = false;
18580            if (deletedPs != null) {
18581                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18582                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18583                    clearDefaultBrowserIfNeeded(packageName);
18584                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18585                    removedAppId = mSettings.removePackageLPw(packageName);
18586                    if (outInfo != null) {
18587                        outInfo.removedAppId = removedAppId;
18588                    }
18589                    updatePermissionsLPw(deletedPs.name, null, 0);
18590                    if (deletedPs.sharedUser != null) {
18591                        // Remove permissions associated with package. Since runtime
18592                        // permissions are per user we have to kill the removed package
18593                        // or packages running under the shared user of the removed
18594                        // package if revoking the permissions requested only by the removed
18595                        // package is successful and this causes a change in gids.
18596                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18597                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18598                                    userId);
18599                            if (userIdToKill == UserHandle.USER_ALL
18600                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18601                                // If gids changed for this user, kill all affected packages.
18602                                mHandler.post(new Runnable() {
18603                                    @Override
18604                                    public void run() {
18605                                        // This has to happen with no lock held.
18606                                        killApplication(deletedPs.name, deletedPs.appId,
18607                                                KILL_APP_REASON_GIDS_CHANGED);
18608                                    }
18609                                });
18610                                break;
18611                            }
18612                        }
18613                    }
18614                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18615                }
18616                // make sure to preserve per-user disabled state if this removal was just
18617                // a downgrade of a system app to the factory package
18618                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18619                    if (DEBUG_REMOVE) {
18620                        Slog.d(TAG, "Propagating install state across downgrade");
18621                    }
18622                    for (int userId : allUserHandles) {
18623                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18624                        if (DEBUG_REMOVE) {
18625                            Slog.d(TAG, "    user " + userId + " => " + installed);
18626                        }
18627                        if (installed != ps.getInstalled(userId)) {
18628                            installedStateChanged = true;
18629                        }
18630                        ps.setInstalled(installed, userId);
18631                    }
18632                }
18633            }
18634            // can downgrade to reader
18635            if (writeSettings) {
18636                // Save settings now
18637                mSettings.writeLPr();
18638            }
18639            if (installedStateChanged) {
18640                mSettings.writeKernelMappingLPr(ps);
18641            }
18642        }
18643        if (removedAppId != -1) {
18644            // A user ID was deleted here. Go through all users and remove it
18645            // from KeyStore.
18646            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18647        }
18648    }
18649
18650    static boolean locationIsPrivileged(File path) {
18651        try {
18652            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18653                    .getCanonicalPath();
18654            return path.getCanonicalPath().startsWith(privilegedAppDir);
18655        } catch (IOException e) {
18656            Slog.e(TAG, "Unable to access code path " + path);
18657        }
18658        return false;
18659    }
18660
18661    static boolean locationIsOem(File path) {
18662        try {
18663            return path.getCanonicalPath().startsWith(
18664                    Environment.getOemDirectory().getCanonicalPath());
18665        } catch (IOException e) {
18666            Slog.e(TAG, "Unable to access code path " + path);
18667        }
18668        return false;
18669    }
18670
18671    /*
18672     * Tries to delete system package.
18673     */
18674    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18675            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18676            boolean writeSettings) {
18677        if (deletedPs.parentPackageName != null) {
18678            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18679            return false;
18680        }
18681
18682        final boolean applyUserRestrictions
18683                = (allUserHandles != null) && (outInfo.origUsers != null);
18684        final PackageSetting disabledPs;
18685        // Confirm if the system package has been updated
18686        // An updated system app can be deleted. This will also have to restore
18687        // the system pkg from system partition
18688        // reader
18689        synchronized (mPackages) {
18690            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18691        }
18692
18693        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18694                + " disabledPs=" + disabledPs);
18695
18696        if (disabledPs == null) {
18697            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18698            return false;
18699        } else if (DEBUG_REMOVE) {
18700            Slog.d(TAG, "Deleting system pkg from data partition");
18701        }
18702
18703        if (DEBUG_REMOVE) {
18704            if (applyUserRestrictions) {
18705                Slog.d(TAG, "Remembering install states:");
18706                for (int userId : allUserHandles) {
18707                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18708                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18709                }
18710            }
18711        }
18712
18713        // Delete the updated package
18714        outInfo.isRemovedPackageSystemUpdate = true;
18715        if (outInfo.removedChildPackages != null) {
18716            final int childCount = (deletedPs.childPackageNames != null)
18717                    ? deletedPs.childPackageNames.size() : 0;
18718            for (int i = 0; i < childCount; i++) {
18719                String childPackageName = deletedPs.childPackageNames.get(i);
18720                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18721                        .contains(childPackageName)) {
18722                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18723                            childPackageName);
18724                    if (childInfo != null) {
18725                        childInfo.isRemovedPackageSystemUpdate = true;
18726                    }
18727                }
18728            }
18729        }
18730
18731        if (disabledPs.versionCode < deletedPs.versionCode) {
18732            // Delete data for downgrades
18733            flags &= ~PackageManager.DELETE_KEEP_DATA;
18734        } else {
18735            // Preserve data by setting flag
18736            flags |= PackageManager.DELETE_KEEP_DATA;
18737        }
18738
18739        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18740                outInfo, writeSettings, disabledPs.pkg);
18741        if (!ret) {
18742            return false;
18743        }
18744
18745        // writer
18746        synchronized (mPackages) {
18747            // NOTE: The system package always needs to be enabled; even if it's for
18748            // a compressed stub. If we don't, installing the system package fails
18749            // during scan [scanning checks the disabled packages]. We will reverse
18750            // this later, after we've "installed" the stub.
18751            // Reinstate the old system package
18752            enableSystemPackageLPw(disabledPs.pkg);
18753            // Remove any native libraries from the upgraded package.
18754            removeNativeBinariesLI(deletedPs);
18755        }
18756
18757        // Install the system package
18758        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18759        try {
18760            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18761                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18762        } catch (PackageManagerException e) {
18763            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18764                    + e.getMessage());
18765            return false;
18766        } finally {
18767            if (disabledPs.pkg.isStub) {
18768                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18769            }
18770        }
18771        return true;
18772    }
18773
18774    /**
18775     * Installs a package that's already on the system partition.
18776     */
18777    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18778            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18779            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18780                    throws PackageManagerException {
18781        int parseFlags = mDefParseFlags
18782                | PackageParser.PARSE_MUST_BE_APK
18783                | PackageParser.PARSE_IS_SYSTEM
18784                | PackageParser.PARSE_IS_SYSTEM_DIR;
18785        if (isPrivileged || locationIsPrivileged(codePath)) {
18786            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18787        }
18788        if (locationIsOem(codePath)) {
18789            parseFlags |= PackageParser.PARSE_IS_OEM;
18790        }
18791
18792        final PackageParser.Package newPkg =
18793                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18794
18795        try {
18796            // update shared libraries for the newly re-installed system package
18797            updateSharedLibrariesLPr(newPkg, null);
18798        } catch (PackageManagerException e) {
18799            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18800        }
18801
18802        prepareAppDataAfterInstallLIF(newPkg);
18803
18804        // writer
18805        synchronized (mPackages) {
18806            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18807
18808            // Propagate the permissions state as we do not want to drop on the floor
18809            // runtime permissions. The update permissions method below will take
18810            // care of removing obsolete permissions and grant install permissions.
18811            if (origPermissionState != null) {
18812                ps.getPermissionsState().copyFrom(origPermissionState);
18813            }
18814            updatePermissionsLPw(newPkg.packageName, newPkg,
18815                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18816
18817            final boolean applyUserRestrictions
18818                    = (allUserHandles != null) && (origUserHandles != null);
18819            if (applyUserRestrictions) {
18820                boolean installedStateChanged = false;
18821                if (DEBUG_REMOVE) {
18822                    Slog.d(TAG, "Propagating install state across reinstall");
18823                }
18824                for (int userId : allUserHandles) {
18825                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18826                    if (DEBUG_REMOVE) {
18827                        Slog.d(TAG, "    user " + userId + " => " + installed);
18828                    }
18829                    if (installed != ps.getInstalled(userId)) {
18830                        installedStateChanged = true;
18831                    }
18832                    ps.setInstalled(installed, userId);
18833
18834                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18835                }
18836                // Regardless of writeSettings we need to ensure that this restriction
18837                // state propagation is persisted
18838                mSettings.writeAllUsersPackageRestrictionsLPr();
18839                if (installedStateChanged) {
18840                    mSettings.writeKernelMappingLPr(ps);
18841                }
18842            }
18843            // can downgrade to reader here
18844            if (writeSettings) {
18845                mSettings.writeLPr();
18846            }
18847        }
18848        return newPkg;
18849    }
18850
18851    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18852            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18853            PackageRemovedInfo outInfo, boolean writeSettings,
18854            PackageParser.Package replacingPackage) {
18855        synchronized (mPackages) {
18856            if (outInfo != null) {
18857                outInfo.uid = ps.appId;
18858            }
18859
18860            if (outInfo != null && outInfo.removedChildPackages != null) {
18861                final int childCount = (ps.childPackageNames != null)
18862                        ? ps.childPackageNames.size() : 0;
18863                for (int i = 0; i < childCount; i++) {
18864                    String childPackageName = ps.childPackageNames.get(i);
18865                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18866                    if (childPs == null) {
18867                        return false;
18868                    }
18869                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18870                            childPackageName);
18871                    if (childInfo != null) {
18872                        childInfo.uid = childPs.appId;
18873                    }
18874                }
18875            }
18876        }
18877
18878        // Delete package data from internal structures and also remove data if flag is set
18879        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18880
18881        // Delete the child packages data
18882        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18883        for (int i = 0; i < childCount; i++) {
18884            PackageSetting childPs;
18885            synchronized (mPackages) {
18886                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18887            }
18888            if (childPs != null) {
18889                PackageRemovedInfo childOutInfo = (outInfo != null
18890                        && outInfo.removedChildPackages != null)
18891                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18892                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18893                        && (replacingPackage != null
18894                        && !replacingPackage.hasChildPackage(childPs.name))
18895                        ? flags & ~DELETE_KEEP_DATA : flags;
18896                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18897                        deleteFlags, writeSettings);
18898            }
18899        }
18900
18901        // Delete application code and resources only for parent packages
18902        if (ps.parentPackageName == null) {
18903            if (deleteCodeAndResources && (outInfo != null)) {
18904                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18905                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18906                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18907            }
18908        }
18909
18910        return true;
18911    }
18912
18913    @Override
18914    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18915            int userId) {
18916        mContext.enforceCallingOrSelfPermission(
18917                android.Manifest.permission.DELETE_PACKAGES, null);
18918        synchronized (mPackages) {
18919            // Cannot block uninstall of static shared libs as they are
18920            // considered a part of the using app (emulating static linking).
18921            // Also static libs are installed always on internal storage.
18922            PackageParser.Package pkg = mPackages.get(packageName);
18923            if (pkg != null && pkg.staticSharedLibName != null) {
18924                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18925                        + " providing static shared library: " + pkg.staticSharedLibName);
18926                return false;
18927            }
18928            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18929            mSettings.writePackageRestrictionsLPr(userId);
18930        }
18931        return true;
18932    }
18933
18934    @Override
18935    public boolean getBlockUninstallForUser(String packageName, int userId) {
18936        synchronized (mPackages) {
18937            final PackageSetting ps = mSettings.mPackages.get(packageName);
18938            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18939                return false;
18940            }
18941            return mSettings.getBlockUninstallLPr(userId, packageName);
18942        }
18943    }
18944
18945    @Override
18946    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18947        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18948        synchronized (mPackages) {
18949            PackageSetting ps = mSettings.mPackages.get(packageName);
18950            if (ps == null) {
18951                Log.w(TAG, "Package doesn't exist: " + packageName);
18952                return false;
18953            }
18954            if (systemUserApp) {
18955                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18956            } else {
18957                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18958            }
18959            mSettings.writeLPr();
18960        }
18961        return true;
18962    }
18963
18964    /*
18965     * This method handles package deletion in general
18966     */
18967    private boolean deletePackageLIF(String packageName, UserHandle user,
18968            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18969            PackageRemovedInfo outInfo, boolean writeSettings,
18970            PackageParser.Package replacingPackage) {
18971        if (packageName == null) {
18972            Slog.w(TAG, "Attempt to delete null packageName.");
18973            return false;
18974        }
18975
18976        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18977
18978        PackageSetting ps;
18979        synchronized (mPackages) {
18980            ps = mSettings.mPackages.get(packageName);
18981            if (ps == null) {
18982                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18983                return false;
18984            }
18985
18986            if (ps.parentPackageName != null && (!isSystemApp(ps)
18987                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18988                if (DEBUG_REMOVE) {
18989                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18990                            + ((user == null) ? UserHandle.USER_ALL : user));
18991                }
18992                final int removedUserId = (user != null) ? user.getIdentifier()
18993                        : UserHandle.USER_ALL;
18994                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18995                    return false;
18996                }
18997                markPackageUninstalledForUserLPw(ps, user);
18998                scheduleWritePackageRestrictionsLocked(user);
18999                return true;
19000            }
19001        }
19002
19003        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19004                && user.getIdentifier() != UserHandle.USER_ALL)) {
19005            // The caller is asking that the package only be deleted for a single
19006            // user.  To do this, we just mark its uninstalled state and delete
19007            // its data. If this is a system app, we only allow this to happen if
19008            // they have set the special DELETE_SYSTEM_APP which requests different
19009            // semantics than normal for uninstalling system apps.
19010            markPackageUninstalledForUserLPw(ps, user);
19011
19012            if (!isSystemApp(ps)) {
19013                // Do not uninstall the APK if an app should be cached
19014                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19015                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19016                    // Other user still have this package installed, so all
19017                    // we need to do is clear this user's data and save that
19018                    // it is uninstalled.
19019                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19020                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19021                        return false;
19022                    }
19023                    scheduleWritePackageRestrictionsLocked(user);
19024                    return true;
19025                } else {
19026                    // We need to set it back to 'installed' so the uninstall
19027                    // broadcasts will be sent correctly.
19028                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19029                    ps.setInstalled(true, user.getIdentifier());
19030                    mSettings.writeKernelMappingLPr(ps);
19031                }
19032            } else {
19033                // This is a system app, so we assume that the
19034                // other users still have this package installed, so all
19035                // we need to do is clear this user's data and save that
19036                // it is uninstalled.
19037                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19038                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19039                    return false;
19040                }
19041                scheduleWritePackageRestrictionsLocked(user);
19042                return true;
19043            }
19044        }
19045
19046        // If we are deleting a composite package for all users, keep track
19047        // of result for each child.
19048        if (ps.childPackageNames != null && outInfo != null) {
19049            synchronized (mPackages) {
19050                final int childCount = ps.childPackageNames.size();
19051                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19052                for (int i = 0; i < childCount; i++) {
19053                    String childPackageName = ps.childPackageNames.get(i);
19054                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19055                    childInfo.removedPackage = childPackageName;
19056                    childInfo.installerPackageName = ps.installerPackageName;
19057                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19058                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19059                    if (childPs != null) {
19060                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19061                    }
19062                }
19063            }
19064        }
19065
19066        boolean ret = false;
19067        if (isSystemApp(ps)) {
19068            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19069            // When an updated system application is deleted we delete the existing resources
19070            // as well and fall back to existing code in system partition
19071            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19072        } else {
19073            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19074            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19075                    outInfo, writeSettings, replacingPackage);
19076        }
19077
19078        // Take a note whether we deleted the package for all users
19079        if (outInfo != null) {
19080            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19081            if (outInfo.removedChildPackages != null) {
19082                synchronized (mPackages) {
19083                    final int childCount = outInfo.removedChildPackages.size();
19084                    for (int i = 0; i < childCount; i++) {
19085                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19086                        if (childInfo != null) {
19087                            childInfo.removedForAllUsers = mPackages.get(
19088                                    childInfo.removedPackage) == null;
19089                        }
19090                    }
19091                }
19092            }
19093            // If we uninstalled an update to a system app there may be some
19094            // child packages that appeared as they are declared in the system
19095            // app but were not declared in the update.
19096            if (isSystemApp(ps)) {
19097                synchronized (mPackages) {
19098                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19099                    final int childCount = (updatedPs.childPackageNames != null)
19100                            ? updatedPs.childPackageNames.size() : 0;
19101                    for (int i = 0; i < childCount; i++) {
19102                        String childPackageName = updatedPs.childPackageNames.get(i);
19103                        if (outInfo.removedChildPackages == null
19104                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19105                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19106                            if (childPs == null) {
19107                                continue;
19108                            }
19109                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19110                            installRes.name = childPackageName;
19111                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19112                            installRes.pkg = mPackages.get(childPackageName);
19113                            installRes.uid = childPs.pkg.applicationInfo.uid;
19114                            if (outInfo.appearedChildPackages == null) {
19115                                outInfo.appearedChildPackages = new ArrayMap<>();
19116                            }
19117                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19118                        }
19119                    }
19120                }
19121            }
19122        }
19123
19124        return ret;
19125    }
19126
19127    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19128        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19129                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19130        for (int nextUserId : userIds) {
19131            if (DEBUG_REMOVE) {
19132                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19133            }
19134            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19135                    false /*installed*/,
19136                    true /*stopped*/,
19137                    true /*notLaunched*/,
19138                    false /*hidden*/,
19139                    false /*suspended*/,
19140                    false /*instantApp*/,
19141                    false /*virtualPreload*/,
19142                    null /*lastDisableAppCaller*/,
19143                    null /*enabledComponents*/,
19144                    null /*disabledComponents*/,
19145                    ps.readUserState(nextUserId).domainVerificationStatus,
19146                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19147        }
19148        mSettings.writeKernelMappingLPr(ps);
19149    }
19150
19151    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19152            PackageRemovedInfo outInfo) {
19153        final PackageParser.Package pkg;
19154        synchronized (mPackages) {
19155            pkg = mPackages.get(ps.name);
19156        }
19157
19158        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19159                : new int[] {userId};
19160        for (int nextUserId : userIds) {
19161            if (DEBUG_REMOVE) {
19162                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19163                        + nextUserId);
19164            }
19165
19166            destroyAppDataLIF(pkg, userId,
19167                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19168            destroyAppProfilesLIF(pkg, userId);
19169            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19170            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19171            schedulePackageCleaning(ps.name, nextUserId, false);
19172            synchronized (mPackages) {
19173                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19174                    scheduleWritePackageRestrictionsLocked(nextUserId);
19175                }
19176                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19177            }
19178        }
19179
19180        if (outInfo != null) {
19181            outInfo.removedPackage = ps.name;
19182            outInfo.installerPackageName = ps.installerPackageName;
19183            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19184            outInfo.removedAppId = ps.appId;
19185            outInfo.removedUsers = userIds;
19186            outInfo.broadcastUsers = userIds;
19187        }
19188
19189        return true;
19190    }
19191
19192    private final class ClearStorageConnection implements ServiceConnection {
19193        IMediaContainerService mContainerService;
19194
19195        @Override
19196        public void onServiceConnected(ComponentName name, IBinder service) {
19197            synchronized (this) {
19198                mContainerService = IMediaContainerService.Stub
19199                        .asInterface(Binder.allowBlocking(service));
19200                notifyAll();
19201            }
19202        }
19203
19204        @Override
19205        public void onServiceDisconnected(ComponentName name) {
19206        }
19207    }
19208
19209    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19210        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19211
19212        final boolean mounted;
19213        if (Environment.isExternalStorageEmulated()) {
19214            mounted = true;
19215        } else {
19216            final String status = Environment.getExternalStorageState();
19217
19218            mounted = status.equals(Environment.MEDIA_MOUNTED)
19219                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19220        }
19221
19222        if (!mounted) {
19223            return;
19224        }
19225
19226        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19227        int[] users;
19228        if (userId == UserHandle.USER_ALL) {
19229            users = sUserManager.getUserIds();
19230        } else {
19231            users = new int[] { userId };
19232        }
19233        final ClearStorageConnection conn = new ClearStorageConnection();
19234        if (mContext.bindServiceAsUser(
19235                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19236            try {
19237                for (int curUser : users) {
19238                    long timeout = SystemClock.uptimeMillis() + 5000;
19239                    synchronized (conn) {
19240                        long now;
19241                        while (conn.mContainerService == null &&
19242                                (now = SystemClock.uptimeMillis()) < timeout) {
19243                            try {
19244                                conn.wait(timeout - now);
19245                            } catch (InterruptedException e) {
19246                            }
19247                        }
19248                    }
19249                    if (conn.mContainerService == null) {
19250                        return;
19251                    }
19252
19253                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19254                    clearDirectory(conn.mContainerService,
19255                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19256                    if (allData) {
19257                        clearDirectory(conn.mContainerService,
19258                                userEnv.buildExternalStorageAppDataDirs(packageName));
19259                        clearDirectory(conn.mContainerService,
19260                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19261                    }
19262                }
19263            } finally {
19264                mContext.unbindService(conn);
19265            }
19266        }
19267    }
19268
19269    @Override
19270    public void clearApplicationProfileData(String packageName) {
19271        enforceSystemOrRoot("Only the system can clear all profile data");
19272
19273        final PackageParser.Package pkg;
19274        synchronized (mPackages) {
19275            pkg = mPackages.get(packageName);
19276        }
19277
19278        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19279            synchronized (mInstallLock) {
19280                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19281            }
19282        }
19283    }
19284
19285    @Override
19286    public void clearApplicationUserData(final String packageName,
19287            final IPackageDataObserver observer, final int userId) {
19288        mContext.enforceCallingOrSelfPermission(
19289                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19290
19291        final int callingUid = Binder.getCallingUid();
19292        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19293                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19294
19295        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19296        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19297        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19298            throw new SecurityException("Cannot clear data for a protected package: "
19299                    + packageName);
19300        }
19301        // Queue up an async operation since the package deletion may take a little while.
19302        mHandler.post(new Runnable() {
19303            public void run() {
19304                mHandler.removeCallbacks(this);
19305                final boolean succeeded;
19306                if (!filterApp) {
19307                    try (PackageFreezer freezer = freezePackage(packageName,
19308                            "clearApplicationUserData")) {
19309                        synchronized (mInstallLock) {
19310                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19311                        }
19312                        clearExternalStorageDataSync(packageName, userId, true);
19313                        synchronized (mPackages) {
19314                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19315                                    packageName, userId);
19316                        }
19317                    }
19318                    if (succeeded) {
19319                        // invoke DeviceStorageMonitor's update method to clear any notifications
19320                        DeviceStorageMonitorInternal dsm = LocalServices
19321                                .getService(DeviceStorageMonitorInternal.class);
19322                        if (dsm != null) {
19323                            dsm.checkMemory();
19324                        }
19325                    }
19326                } else {
19327                    succeeded = false;
19328                }
19329                if (observer != null) {
19330                    try {
19331                        observer.onRemoveCompleted(packageName, succeeded);
19332                    } catch (RemoteException e) {
19333                        Log.i(TAG, "Observer no longer exists.");
19334                    }
19335                } //end if observer
19336            } //end run
19337        });
19338    }
19339
19340    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19341        if (packageName == null) {
19342            Slog.w(TAG, "Attempt to delete null packageName.");
19343            return false;
19344        }
19345
19346        // Try finding details about the requested package
19347        PackageParser.Package pkg;
19348        synchronized (mPackages) {
19349            pkg = mPackages.get(packageName);
19350            if (pkg == null) {
19351                final PackageSetting ps = mSettings.mPackages.get(packageName);
19352                if (ps != null) {
19353                    pkg = ps.pkg;
19354                }
19355            }
19356
19357            if (pkg == null) {
19358                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19359                return false;
19360            }
19361
19362            PackageSetting ps = (PackageSetting) pkg.mExtras;
19363            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19364        }
19365
19366        clearAppDataLIF(pkg, userId,
19367                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19368
19369        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19370        removeKeystoreDataIfNeeded(userId, appId);
19371
19372        UserManagerInternal umInternal = getUserManagerInternal();
19373        final int flags;
19374        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19375            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19376        } else if (umInternal.isUserRunning(userId)) {
19377            flags = StorageManager.FLAG_STORAGE_DE;
19378        } else {
19379            flags = 0;
19380        }
19381        prepareAppDataContentsLIF(pkg, userId, flags);
19382
19383        return true;
19384    }
19385
19386    /**
19387     * Reverts user permission state changes (permissions and flags) in
19388     * all packages for a given user.
19389     *
19390     * @param userId The device user for which to do a reset.
19391     */
19392    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19393        final int packageCount = mPackages.size();
19394        for (int i = 0; i < packageCount; i++) {
19395            PackageParser.Package pkg = mPackages.valueAt(i);
19396            PackageSetting ps = (PackageSetting) pkg.mExtras;
19397            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19398        }
19399    }
19400
19401    private void resetNetworkPolicies(int userId) {
19402        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19403    }
19404
19405    /**
19406     * Reverts user permission state changes (permissions and flags).
19407     *
19408     * @param ps The package for which to reset.
19409     * @param userId The device user for which to do a reset.
19410     */
19411    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19412            final PackageSetting ps, final int userId) {
19413        if (ps.pkg == null) {
19414            return;
19415        }
19416
19417        // These are flags that can change base on user actions.
19418        final int userSettableMask = FLAG_PERMISSION_USER_SET
19419                | FLAG_PERMISSION_USER_FIXED
19420                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19421                | FLAG_PERMISSION_REVIEW_REQUIRED;
19422
19423        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19424                | FLAG_PERMISSION_POLICY_FIXED;
19425
19426        boolean writeInstallPermissions = false;
19427        boolean writeRuntimePermissions = false;
19428
19429        final int permissionCount = ps.pkg.requestedPermissions.size();
19430        for (int i = 0; i < permissionCount; i++) {
19431            final String permName = ps.pkg.requestedPermissions.get(i);
19432            final BasePermission bp =
19433                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19434            if (bp == null) {
19435                continue;
19436            }
19437
19438            // If shared user we just reset the state to which only this app contributed.
19439            if (ps.sharedUser != null) {
19440                boolean used = false;
19441                final int packageCount = ps.sharedUser.packages.size();
19442                for (int j = 0; j < packageCount; j++) {
19443                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19444                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19445                            && pkg.pkg.requestedPermissions.contains(permName)) {
19446                        used = true;
19447                        break;
19448                    }
19449                }
19450                if (used) {
19451                    continue;
19452                }
19453            }
19454
19455            final PermissionsState permissionsState = ps.getPermissionsState();
19456
19457            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19458
19459            // Always clear the user settable flags.
19460            final boolean hasInstallState =
19461                    permissionsState.getInstallPermissionState(permName) != null;
19462            // If permission review is enabled and this is a legacy app, mark the
19463            // permission as requiring a review as this is the initial state.
19464            int flags = 0;
19465            if (mPermissionReviewRequired
19466                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19467                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19468            }
19469            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19470                if (hasInstallState) {
19471                    writeInstallPermissions = true;
19472                } else {
19473                    writeRuntimePermissions = true;
19474                }
19475            }
19476
19477            // Below is only runtime permission handling.
19478            if (!bp.isRuntime()) {
19479                continue;
19480            }
19481
19482            // Never clobber system or policy.
19483            if ((oldFlags & policyOrSystemFlags) != 0) {
19484                continue;
19485            }
19486
19487            // If this permission was granted by default, make sure it is.
19488            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19489                if (permissionsState.grantRuntimePermission(bp, userId)
19490                        != PERMISSION_OPERATION_FAILURE) {
19491                    writeRuntimePermissions = true;
19492                }
19493            // If permission review is enabled the permissions for a legacy apps
19494            // are represented as constantly granted runtime ones, so don't revoke.
19495            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19496                // Otherwise, reset the permission.
19497                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19498                switch (revokeResult) {
19499                    case PERMISSION_OPERATION_SUCCESS:
19500                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19501                        writeRuntimePermissions = true;
19502                        final int appId = ps.appId;
19503                        mHandler.post(new Runnable() {
19504                            @Override
19505                            public void run() {
19506                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19507                            }
19508                        });
19509                    } break;
19510                }
19511            }
19512        }
19513
19514        // Synchronously write as we are taking permissions away.
19515        if (writeRuntimePermissions) {
19516            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19517        }
19518
19519        // Synchronously write as we are taking permissions away.
19520        if (writeInstallPermissions) {
19521            mSettings.writeLPr();
19522        }
19523    }
19524
19525    /**
19526     * Remove entries from the keystore daemon. Will only remove it if the
19527     * {@code appId} is valid.
19528     */
19529    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19530        if (appId < 0) {
19531            return;
19532        }
19533
19534        final KeyStore keyStore = KeyStore.getInstance();
19535        if (keyStore != null) {
19536            if (userId == UserHandle.USER_ALL) {
19537                for (final int individual : sUserManager.getUserIds()) {
19538                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19539                }
19540            } else {
19541                keyStore.clearUid(UserHandle.getUid(userId, appId));
19542            }
19543        } else {
19544            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19545        }
19546    }
19547
19548    @Override
19549    public void deleteApplicationCacheFiles(final String packageName,
19550            final IPackageDataObserver observer) {
19551        final int userId = UserHandle.getCallingUserId();
19552        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19553    }
19554
19555    @Override
19556    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19557            final IPackageDataObserver observer) {
19558        final int callingUid = Binder.getCallingUid();
19559        mContext.enforceCallingOrSelfPermission(
19560                android.Manifest.permission.DELETE_CACHE_FILES, null);
19561        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19562                /* requireFullPermission= */ true, /* checkShell= */ false,
19563                "delete application cache files");
19564        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19565                android.Manifest.permission.ACCESS_INSTANT_APPS);
19566
19567        final PackageParser.Package pkg;
19568        synchronized (mPackages) {
19569            pkg = mPackages.get(packageName);
19570        }
19571
19572        // Queue up an async operation since the package deletion may take a little while.
19573        mHandler.post(new Runnable() {
19574            public void run() {
19575                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19576                boolean doClearData = true;
19577                if (ps != null) {
19578                    final boolean targetIsInstantApp =
19579                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19580                    doClearData = !targetIsInstantApp
19581                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19582                }
19583                if (doClearData) {
19584                    synchronized (mInstallLock) {
19585                        final int flags = StorageManager.FLAG_STORAGE_DE
19586                                | StorageManager.FLAG_STORAGE_CE;
19587                        // We're only clearing cache files, so we don't care if the
19588                        // app is unfrozen and still able to run
19589                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19590                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19591                    }
19592                    clearExternalStorageDataSync(packageName, userId, false);
19593                }
19594                if (observer != null) {
19595                    try {
19596                        observer.onRemoveCompleted(packageName, true);
19597                    } catch (RemoteException e) {
19598                        Log.i(TAG, "Observer no longer exists.");
19599                    }
19600                }
19601            }
19602        });
19603    }
19604
19605    @Override
19606    public void getPackageSizeInfo(final String packageName, int userHandle,
19607            final IPackageStatsObserver observer) {
19608        throw new UnsupportedOperationException(
19609                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19610    }
19611
19612    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19613        final PackageSetting ps;
19614        synchronized (mPackages) {
19615            ps = mSettings.mPackages.get(packageName);
19616            if (ps == null) {
19617                Slog.w(TAG, "Failed to find settings for " + packageName);
19618                return false;
19619            }
19620        }
19621
19622        final String[] packageNames = { packageName };
19623        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19624        final String[] codePaths = { ps.codePathString };
19625
19626        try {
19627            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19628                    ps.appId, ceDataInodes, codePaths, stats);
19629
19630            // For now, ignore code size of packages on system partition
19631            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19632                stats.codeSize = 0;
19633            }
19634
19635            // External clients expect these to be tracked separately
19636            stats.dataSize -= stats.cacheSize;
19637
19638        } catch (InstallerException e) {
19639            Slog.w(TAG, String.valueOf(e));
19640            return false;
19641        }
19642
19643        return true;
19644    }
19645
19646    private int getUidTargetSdkVersionLockedLPr(int uid) {
19647        Object obj = mSettings.getUserIdLPr(uid);
19648        if (obj instanceof SharedUserSetting) {
19649            final SharedUserSetting sus = (SharedUserSetting) obj;
19650            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19651            final Iterator<PackageSetting> it = sus.packages.iterator();
19652            while (it.hasNext()) {
19653                final PackageSetting ps = it.next();
19654                if (ps.pkg != null) {
19655                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19656                    if (v < vers) vers = v;
19657                }
19658            }
19659            return vers;
19660        } else if (obj instanceof PackageSetting) {
19661            final PackageSetting ps = (PackageSetting) obj;
19662            if (ps.pkg != null) {
19663                return ps.pkg.applicationInfo.targetSdkVersion;
19664            }
19665        }
19666        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19667    }
19668
19669    @Override
19670    public void addPreferredActivity(IntentFilter filter, int match,
19671            ComponentName[] set, ComponentName activity, int userId) {
19672        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19673                "Adding preferred");
19674    }
19675
19676    private void addPreferredActivityInternal(IntentFilter filter, int match,
19677            ComponentName[] set, ComponentName activity, boolean always, int userId,
19678            String opname) {
19679        // writer
19680        int callingUid = Binder.getCallingUid();
19681        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19682                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19683        if (filter.countActions() == 0) {
19684            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19685            return;
19686        }
19687        synchronized (mPackages) {
19688            if (mContext.checkCallingOrSelfPermission(
19689                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19690                    != PackageManager.PERMISSION_GRANTED) {
19691                if (getUidTargetSdkVersionLockedLPr(callingUid)
19692                        < Build.VERSION_CODES.FROYO) {
19693                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19694                            + callingUid);
19695                    return;
19696                }
19697                mContext.enforceCallingOrSelfPermission(
19698                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19699            }
19700
19701            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19702            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19703                    + userId + ":");
19704            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19705            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19706            scheduleWritePackageRestrictionsLocked(userId);
19707            postPreferredActivityChangedBroadcast(userId);
19708        }
19709    }
19710
19711    private void postPreferredActivityChangedBroadcast(int userId) {
19712        mHandler.post(() -> {
19713            final IActivityManager am = ActivityManager.getService();
19714            if (am == null) {
19715                return;
19716            }
19717
19718            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19719            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19720            try {
19721                am.broadcastIntent(null, intent, null, null,
19722                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19723                        null, false, false, userId);
19724            } catch (RemoteException e) {
19725            }
19726        });
19727    }
19728
19729    @Override
19730    public void replacePreferredActivity(IntentFilter filter, int match,
19731            ComponentName[] set, ComponentName activity, int userId) {
19732        if (filter.countActions() != 1) {
19733            throw new IllegalArgumentException(
19734                    "replacePreferredActivity expects filter to have only 1 action.");
19735        }
19736        if (filter.countDataAuthorities() != 0
19737                || filter.countDataPaths() != 0
19738                || filter.countDataSchemes() > 1
19739                || filter.countDataTypes() != 0) {
19740            throw new IllegalArgumentException(
19741                    "replacePreferredActivity expects filter to have no data authorities, " +
19742                    "paths, or types; and at most one scheme.");
19743        }
19744
19745        final int callingUid = Binder.getCallingUid();
19746        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19747                true /* requireFullPermission */, false /* checkShell */,
19748                "replace preferred activity");
19749        synchronized (mPackages) {
19750            if (mContext.checkCallingOrSelfPermission(
19751                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19752                    != PackageManager.PERMISSION_GRANTED) {
19753                if (getUidTargetSdkVersionLockedLPr(callingUid)
19754                        < Build.VERSION_CODES.FROYO) {
19755                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19756                            + Binder.getCallingUid());
19757                    return;
19758                }
19759                mContext.enforceCallingOrSelfPermission(
19760                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19761            }
19762
19763            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19764            if (pir != null) {
19765                // Get all of the existing entries that exactly match this filter.
19766                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19767                if (existing != null && existing.size() == 1) {
19768                    PreferredActivity cur = existing.get(0);
19769                    if (DEBUG_PREFERRED) {
19770                        Slog.i(TAG, "Checking replace of preferred:");
19771                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19772                        if (!cur.mPref.mAlways) {
19773                            Slog.i(TAG, "  -- CUR; not mAlways!");
19774                        } else {
19775                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19776                            Slog.i(TAG, "  -- CUR: mSet="
19777                                    + Arrays.toString(cur.mPref.mSetComponents));
19778                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19779                            Slog.i(TAG, "  -- NEW: mMatch="
19780                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19781                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19782                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19783                        }
19784                    }
19785                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19786                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19787                            && cur.mPref.sameSet(set)) {
19788                        // Setting the preferred activity to what it happens to be already
19789                        if (DEBUG_PREFERRED) {
19790                            Slog.i(TAG, "Replacing with same preferred activity "
19791                                    + cur.mPref.mShortComponent + " for user "
19792                                    + userId + ":");
19793                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19794                        }
19795                        return;
19796                    }
19797                }
19798
19799                if (existing != null) {
19800                    if (DEBUG_PREFERRED) {
19801                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19802                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19803                    }
19804                    for (int i = 0; i < existing.size(); i++) {
19805                        PreferredActivity pa = existing.get(i);
19806                        if (DEBUG_PREFERRED) {
19807                            Slog.i(TAG, "Removing existing preferred activity "
19808                                    + pa.mPref.mComponent + ":");
19809                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19810                        }
19811                        pir.removeFilter(pa);
19812                    }
19813                }
19814            }
19815            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19816                    "Replacing preferred");
19817        }
19818    }
19819
19820    @Override
19821    public void clearPackagePreferredActivities(String packageName) {
19822        final int callingUid = Binder.getCallingUid();
19823        if (getInstantAppPackageName(callingUid) != null) {
19824            return;
19825        }
19826        // writer
19827        synchronized (mPackages) {
19828            PackageParser.Package pkg = mPackages.get(packageName);
19829            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19830                if (mContext.checkCallingOrSelfPermission(
19831                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19832                        != PackageManager.PERMISSION_GRANTED) {
19833                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19834                            < Build.VERSION_CODES.FROYO) {
19835                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19836                                + callingUid);
19837                        return;
19838                    }
19839                    mContext.enforceCallingOrSelfPermission(
19840                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19841                }
19842            }
19843            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19844            if (ps != null
19845                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19846                return;
19847            }
19848            int user = UserHandle.getCallingUserId();
19849            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19850                scheduleWritePackageRestrictionsLocked(user);
19851            }
19852        }
19853    }
19854
19855    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19856    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19857        ArrayList<PreferredActivity> removed = null;
19858        boolean changed = false;
19859        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19860            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19861            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19862            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19863                continue;
19864            }
19865            Iterator<PreferredActivity> it = pir.filterIterator();
19866            while (it.hasNext()) {
19867                PreferredActivity pa = it.next();
19868                // Mark entry for removal only if it matches the package name
19869                // and the entry is of type "always".
19870                if (packageName == null ||
19871                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19872                                && pa.mPref.mAlways)) {
19873                    if (removed == null) {
19874                        removed = new ArrayList<PreferredActivity>();
19875                    }
19876                    removed.add(pa);
19877                }
19878            }
19879            if (removed != null) {
19880                for (int j=0; j<removed.size(); j++) {
19881                    PreferredActivity pa = removed.get(j);
19882                    pir.removeFilter(pa);
19883                }
19884                changed = true;
19885            }
19886        }
19887        if (changed) {
19888            postPreferredActivityChangedBroadcast(userId);
19889        }
19890        return changed;
19891    }
19892
19893    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19894    private void clearIntentFilterVerificationsLPw(int userId) {
19895        final int packageCount = mPackages.size();
19896        for (int i = 0; i < packageCount; i++) {
19897            PackageParser.Package pkg = mPackages.valueAt(i);
19898            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19899        }
19900    }
19901
19902    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19903    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19904        if (userId == UserHandle.USER_ALL) {
19905            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19906                    sUserManager.getUserIds())) {
19907                for (int oneUserId : sUserManager.getUserIds()) {
19908                    scheduleWritePackageRestrictionsLocked(oneUserId);
19909                }
19910            }
19911        } else {
19912            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19913                scheduleWritePackageRestrictionsLocked(userId);
19914            }
19915        }
19916    }
19917
19918    /** Clears state for all users, and touches intent filter verification policy */
19919    void clearDefaultBrowserIfNeeded(String packageName) {
19920        for (int oneUserId : sUserManager.getUserIds()) {
19921            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19922        }
19923    }
19924
19925    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19926        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19927        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19928            if (packageName.equals(defaultBrowserPackageName)) {
19929                setDefaultBrowserPackageName(null, userId);
19930            }
19931        }
19932    }
19933
19934    @Override
19935    public void resetApplicationPreferences(int userId) {
19936        mContext.enforceCallingOrSelfPermission(
19937                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19938        final long identity = Binder.clearCallingIdentity();
19939        // writer
19940        try {
19941            synchronized (mPackages) {
19942                clearPackagePreferredActivitiesLPw(null, userId);
19943                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19944                // TODO: We have to reset the default SMS and Phone. This requires
19945                // significant refactoring to keep all default apps in the package
19946                // manager (cleaner but more work) or have the services provide
19947                // callbacks to the package manager to request a default app reset.
19948                applyFactoryDefaultBrowserLPw(userId);
19949                clearIntentFilterVerificationsLPw(userId);
19950                primeDomainVerificationsLPw(userId);
19951                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19952                scheduleWritePackageRestrictionsLocked(userId);
19953            }
19954            resetNetworkPolicies(userId);
19955        } finally {
19956            Binder.restoreCallingIdentity(identity);
19957        }
19958    }
19959
19960    @Override
19961    public int getPreferredActivities(List<IntentFilter> outFilters,
19962            List<ComponentName> outActivities, String packageName) {
19963        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19964            return 0;
19965        }
19966        int num = 0;
19967        final int userId = UserHandle.getCallingUserId();
19968        // reader
19969        synchronized (mPackages) {
19970            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19971            if (pir != null) {
19972                final Iterator<PreferredActivity> it = pir.filterIterator();
19973                while (it.hasNext()) {
19974                    final PreferredActivity pa = it.next();
19975                    if (packageName == null
19976                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19977                                    && pa.mPref.mAlways)) {
19978                        if (outFilters != null) {
19979                            outFilters.add(new IntentFilter(pa));
19980                        }
19981                        if (outActivities != null) {
19982                            outActivities.add(pa.mPref.mComponent);
19983                        }
19984                    }
19985                }
19986            }
19987        }
19988
19989        return num;
19990    }
19991
19992    @Override
19993    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19994            int userId) {
19995        int callingUid = Binder.getCallingUid();
19996        if (callingUid != Process.SYSTEM_UID) {
19997            throw new SecurityException(
19998                    "addPersistentPreferredActivity can only be run by the system");
19999        }
20000        if (filter.countActions() == 0) {
20001            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20002            return;
20003        }
20004        synchronized (mPackages) {
20005            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20006                    ":");
20007            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20008            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20009                    new PersistentPreferredActivity(filter, activity));
20010            scheduleWritePackageRestrictionsLocked(userId);
20011            postPreferredActivityChangedBroadcast(userId);
20012        }
20013    }
20014
20015    @Override
20016    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20017        int callingUid = Binder.getCallingUid();
20018        if (callingUid != Process.SYSTEM_UID) {
20019            throw new SecurityException(
20020                    "clearPackagePersistentPreferredActivities can only be run by the system");
20021        }
20022        ArrayList<PersistentPreferredActivity> removed = null;
20023        boolean changed = false;
20024        synchronized (mPackages) {
20025            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20026                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20027                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20028                        .valueAt(i);
20029                if (userId != thisUserId) {
20030                    continue;
20031                }
20032                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20033                while (it.hasNext()) {
20034                    PersistentPreferredActivity ppa = it.next();
20035                    // Mark entry for removal only if it matches the package name.
20036                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20037                        if (removed == null) {
20038                            removed = new ArrayList<PersistentPreferredActivity>();
20039                        }
20040                        removed.add(ppa);
20041                    }
20042                }
20043                if (removed != null) {
20044                    for (int j=0; j<removed.size(); j++) {
20045                        PersistentPreferredActivity ppa = removed.get(j);
20046                        ppir.removeFilter(ppa);
20047                    }
20048                    changed = true;
20049                }
20050            }
20051
20052            if (changed) {
20053                scheduleWritePackageRestrictionsLocked(userId);
20054                postPreferredActivityChangedBroadcast(userId);
20055            }
20056        }
20057    }
20058
20059    /**
20060     * Common machinery for picking apart a restored XML blob and passing
20061     * it to a caller-supplied functor to be applied to the running system.
20062     */
20063    private void restoreFromXml(XmlPullParser parser, int userId,
20064            String expectedStartTag, BlobXmlRestorer functor)
20065            throws IOException, XmlPullParserException {
20066        int type;
20067        while ((type = parser.next()) != XmlPullParser.START_TAG
20068                && type != XmlPullParser.END_DOCUMENT) {
20069        }
20070        if (type != XmlPullParser.START_TAG) {
20071            // oops didn't find a start tag?!
20072            if (DEBUG_BACKUP) {
20073                Slog.e(TAG, "Didn't find start tag during restore");
20074            }
20075            return;
20076        }
20077Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20078        // this is supposed to be TAG_PREFERRED_BACKUP
20079        if (!expectedStartTag.equals(parser.getName())) {
20080            if (DEBUG_BACKUP) {
20081                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20082            }
20083            return;
20084        }
20085
20086        // skip interfering stuff, then we're aligned with the backing implementation
20087        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20088Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20089        functor.apply(parser, userId);
20090    }
20091
20092    private interface BlobXmlRestorer {
20093        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20094    }
20095
20096    /**
20097     * Non-Binder method, support for the backup/restore mechanism: write the
20098     * full set of preferred activities in its canonical XML format.  Returns the
20099     * XML output as a byte array, or null if there is none.
20100     */
20101    @Override
20102    public byte[] getPreferredActivityBackup(int userId) {
20103        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20104            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20105        }
20106
20107        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20108        try {
20109            final XmlSerializer serializer = new FastXmlSerializer();
20110            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20111            serializer.startDocument(null, true);
20112            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20113
20114            synchronized (mPackages) {
20115                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20116            }
20117
20118            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20119            serializer.endDocument();
20120            serializer.flush();
20121        } catch (Exception e) {
20122            if (DEBUG_BACKUP) {
20123                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20124            }
20125            return null;
20126        }
20127
20128        return dataStream.toByteArray();
20129    }
20130
20131    @Override
20132    public void restorePreferredActivities(byte[] backup, int userId) {
20133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20134            throw new SecurityException("Only the system may call restorePreferredActivities()");
20135        }
20136
20137        try {
20138            final XmlPullParser parser = Xml.newPullParser();
20139            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20140            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20141                    new BlobXmlRestorer() {
20142                        @Override
20143                        public void apply(XmlPullParser parser, int userId)
20144                                throws XmlPullParserException, IOException {
20145                            synchronized (mPackages) {
20146                                mSettings.readPreferredActivitiesLPw(parser, userId);
20147                            }
20148                        }
20149                    } );
20150        } catch (Exception e) {
20151            if (DEBUG_BACKUP) {
20152                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20153            }
20154        }
20155    }
20156
20157    /**
20158     * Non-Binder method, support for the backup/restore mechanism: write the
20159     * default browser (etc) settings in its canonical XML format.  Returns the default
20160     * browser XML representation as a byte array, or null if there is none.
20161     */
20162    @Override
20163    public byte[] getDefaultAppsBackup(int userId) {
20164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20165            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20166        }
20167
20168        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20169        try {
20170            final XmlSerializer serializer = new FastXmlSerializer();
20171            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20172            serializer.startDocument(null, true);
20173            serializer.startTag(null, TAG_DEFAULT_APPS);
20174
20175            synchronized (mPackages) {
20176                mSettings.writeDefaultAppsLPr(serializer, userId);
20177            }
20178
20179            serializer.endTag(null, TAG_DEFAULT_APPS);
20180            serializer.endDocument();
20181            serializer.flush();
20182        } catch (Exception e) {
20183            if (DEBUG_BACKUP) {
20184                Slog.e(TAG, "Unable to write default apps for backup", e);
20185            }
20186            return null;
20187        }
20188
20189        return dataStream.toByteArray();
20190    }
20191
20192    @Override
20193    public void restoreDefaultApps(byte[] backup, int userId) {
20194        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20195            throw new SecurityException("Only the system may call restoreDefaultApps()");
20196        }
20197
20198        try {
20199            final XmlPullParser parser = Xml.newPullParser();
20200            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20201            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20202                    new BlobXmlRestorer() {
20203                        @Override
20204                        public void apply(XmlPullParser parser, int userId)
20205                                throws XmlPullParserException, IOException {
20206                            synchronized (mPackages) {
20207                                mSettings.readDefaultAppsLPw(parser, userId);
20208                            }
20209                        }
20210                    } );
20211        } catch (Exception e) {
20212            if (DEBUG_BACKUP) {
20213                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20214            }
20215        }
20216    }
20217
20218    @Override
20219    public byte[] getIntentFilterVerificationBackup(int userId) {
20220        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20221            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20222        }
20223
20224        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20225        try {
20226            final XmlSerializer serializer = new FastXmlSerializer();
20227            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20228            serializer.startDocument(null, true);
20229            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20230
20231            synchronized (mPackages) {
20232                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20233            }
20234
20235            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20236            serializer.endDocument();
20237            serializer.flush();
20238        } catch (Exception e) {
20239            if (DEBUG_BACKUP) {
20240                Slog.e(TAG, "Unable to write default apps for backup", e);
20241            }
20242            return null;
20243        }
20244
20245        return dataStream.toByteArray();
20246    }
20247
20248    @Override
20249    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20250        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20251            throw new SecurityException("Only the system may call restorePreferredActivities()");
20252        }
20253
20254        try {
20255            final XmlPullParser parser = Xml.newPullParser();
20256            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20257            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20258                    new BlobXmlRestorer() {
20259                        @Override
20260                        public void apply(XmlPullParser parser, int userId)
20261                                throws XmlPullParserException, IOException {
20262                            synchronized (mPackages) {
20263                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20264                                mSettings.writeLPr();
20265                            }
20266                        }
20267                    } );
20268        } catch (Exception e) {
20269            if (DEBUG_BACKUP) {
20270                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20271            }
20272        }
20273    }
20274
20275    @Override
20276    public byte[] getPermissionGrantBackup(int userId) {
20277        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20278            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20279        }
20280
20281        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20282        try {
20283            final XmlSerializer serializer = new FastXmlSerializer();
20284            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20285            serializer.startDocument(null, true);
20286            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20287
20288            synchronized (mPackages) {
20289                serializeRuntimePermissionGrantsLPr(serializer, userId);
20290            }
20291
20292            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20293            serializer.endDocument();
20294            serializer.flush();
20295        } catch (Exception e) {
20296            if (DEBUG_BACKUP) {
20297                Slog.e(TAG, "Unable to write default apps for backup", e);
20298            }
20299            return null;
20300        }
20301
20302        return dataStream.toByteArray();
20303    }
20304
20305    @Override
20306    public void restorePermissionGrants(byte[] backup, int userId) {
20307        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20308            throw new SecurityException("Only the system may call restorePermissionGrants()");
20309        }
20310
20311        try {
20312            final XmlPullParser parser = Xml.newPullParser();
20313            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20314            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20315                    new BlobXmlRestorer() {
20316                        @Override
20317                        public void apply(XmlPullParser parser, int userId)
20318                                throws XmlPullParserException, IOException {
20319                            synchronized (mPackages) {
20320                                processRestoredPermissionGrantsLPr(parser, userId);
20321                            }
20322                        }
20323                    } );
20324        } catch (Exception e) {
20325            if (DEBUG_BACKUP) {
20326                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20327            }
20328        }
20329    }
20330
20331    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20332            throws IOException {
20333        serializer.startTag(null, TAG_ALL_GRANTS);
20334
20335        final int N = mSettings.mPackages.size();
20336        for (int i = 0; i < N; i++) {
20337            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20338            boolean pkgGrantsKnown = false;
20339
20340            PermissionsState packagePerms = ps.getPermissionsState();
20341
20342            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20343                final int grantFlags = state.getFlags();
20344                // only look at grants that are not system/policy fixed
20345                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20346                    final boolean isGranted = state.isGranted();
20347                    // And only back up the user-twiddled state bits
20348                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20349                        final String packageName = mSettings.mPackages.keyAt(i);
20350                        if (!pkgGrantsKnown) {
20351                            serializer.startTag(null, TAG_GRANT);
20352                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20353                            pkgGrantsKnown = true;
20354                        }
20355
20356                        final boolean userSet =
20357                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20358                        final boolean userFixed =
20359                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20360                        final boolean revoke =
20361                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20362
20363                        serializer.startTag(null, TAG_PERMISSION);
20364                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20365                        if (isGranted) {
20366                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20367                        }
20368                        if (userSet) {
20369                            serializer.attribute(null, ATTR_USER_SET, "true");
20370                        }
20371                        if (userFixed) {
20372                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20373                        }
20374                        if (revoke) {
20375                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20376                        }
20377                        serializer.endTag(null, TAG_PERMISSION);
20378                    }
20379                }
20380            }
20381
20382            if (pkgGrantsKnown) {
20383                serializer.endTag(null, TAG_GRANT);
20384            }
20385        }
20386
20387        serializer.endTag(null, TAG_ALL_GRANTS);
20388    }
20389
20390    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20391            throws XmlPullParserException, IOException {
20392        String pkgName = null;
20393        int outerDepth = parser.getDepth();
20394        int type;
20395        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20396                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20397            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20398                continue;
20399            }
20400
20401            final String tagName = parser.getName();
20402            if (tagName.equals(TAG_GRANT)) {
20403                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20404                if (DEBUG_BACKUP) {
20405                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20406                }
20407            } else if (tagName.equals(TAG_PERMISSION)) {
20408
20409                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20410                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20411
20412                int newFlagSet = 0;
20413                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20414                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20415                }
20416                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20417                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20418                }
20419                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20420                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20421                }
20422                if (DEBUG_BACKUP) {
20423                    Slog.v(TAG, "  + Restoring grant:"
20424                            + " pkg=" + pkgName
20425                            + " perm=" + permName
20426                            + " granted=" + isGranted
20427                            + " bits=0x" + Integer.toHexString(newFlagSet));
20428                }
20429                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20430                if (ps != null) {
20431                    // Already installed so we apply the grant immediately
20432                    if (DEBUG_BACKUP) {
20433                        Slog.v(TAG, "        + already installed; applying");
20434                    }
20435                    PermissionsState perms = ps.getPermissionsState();
20436                    BasePermission bp =
20437                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20438                    if (bp != null) {
20439                        if (isGranted) {
20440                            perms.grantRuntimePermission(bp, userId);
20441                        }
20442                        if (newFlagSet != 0) {
20443                            perms.updatePermissionFlags(
20444                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20445                        }
20446                    }
20447                } else {
20448                    // Need to wait for post-restore install to apply the grant
20449                    if (DEBUG_BACKUP) {
20450                        Slog.v(TAG, "        - not yet installed; saving for later");
20451                    }
20452                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20453                            isGranted, newFlagSet, userId);
20454                }
20455            } else {
20456                PackageManagerService.reportSettingsProblem(Log.WARN,
20457                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20458                XmlUtils.skipCurrentTag(parser);
20459            }
20460        }
20461
20462        scheduleWriteSettingsLocked();
20463        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20464    }
20465
20466    @Override
20467    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20468            int sourceUserId, int targetUserId, int flags) {
20469        mContext.enforceCallingOrSelfPermission(
20470                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20471        int callingUid = Binder.getCallingUid();
20472        enforceOwnerRights(ownerPackage, callingUid);
20473        PackageManagerServiceUtils.enforceShellRestriction(
20474                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20475        if (intentFilter.countActions() == 0) {
20476            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20477            return;
20478        }
20479        synchronized (mPackages) {
20480            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20481                    ownerPackage, targetUserId, flags);
20482            CrossProfileIntentResolver resolver =
20483                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20484            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20485            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20486            if (existing != null) {
20487                int size = existing.size();
20488                for (int i = 0; i < size; i++) {
20489                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20490                        return;
20491                    }
20492                }
20493            }
20494            resolver.addFilter(newFilter);
20495            scheduleWritePackageRestrictionsLocked(sourceUserId);
20496        }
20497    }
20498
20499    @Override
20500    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20501        mContext.enforceCallingOrSelfPermission(
20502                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20503        final int callingUid = Binder.getCallingUid();
20504        enforceOwnerRights(ownerPackage, callingUid);
20505        PackageManagerServiceUtils.enforceShellRestriction(
20506                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20507        synchronized (mPackages) {
20508            CrossProfileIntentResolver resolver =
20509                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20510            ArraySet<CrossProfileIntentFilter> set =
20511                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20512            for (CrossProfileIntentFilter filter : set) {
20513                if (filter.getOwnerPackage().equals(ownerPackage)) {
20514                    resolver.removeFilter(filter);
20515                }
20516            }
20517            scheduleWritePackageRestrictionsLocked(sourceUserId);
20518        }
20519    }
20520
20521    // Enforcing that callingUid is owning pkg on userId
20522    private void enforceOwnerRights(String pkg, int callingUid) {
20523        // The system owns everything.
20524        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20525            return;
20526        }
20527        final int callingUserId = UserHandle.getUserId(callingUid);
20528        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20529        if (pi == null) {
20530            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20531                    + callingUserId);
20532        }
20533        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20534            throw new SecurityException("Calling uid " + callingUid
20535                    + " does not own package " + pkg);
20536        }
20537    }
20538
20539    @Override
20540    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20541        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20542            return null;
20543        }
20544        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20545    }
20546
20547    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20548        UserManagerService ums = UserManagerService.getInstance();
20549        if (ums != null) {
20550            final UserInfo parent = ums.getProfileParent(userId);
20551            final int launcherUid = (parent != null) ? parent.id : userId;
20552            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20553            if (launcherComponent != null) {
20554                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20555                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20556                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20557                        .setPackage(launcherComponent.getPackageName());
20558                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20559            }
20560        }
20561    }
20562
20563    /**
20564     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20565     * then reports the most likely home activity or null if there are more than one.
20566     */
20567    private ComponentName getDefaultHomeActivity(int userId) {
20568        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20569        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20570        if (cn != null) {
20571            return cn;
20572        }
20573
20574        // Find the launcher with the highest priority and return that component if there are no
20575        // other home activity with the same priority.
20576        int lastPriority = Integer.MIN_VALUE;
20577        ComponentName lastComponent = null;
20578        final int size = allHomeCandidates.size();
20579        for (int i = 0; i < size; i++) {
20580            final ResolveInfo ri = allHomeCandidates.get(i);
20581            if (ri.priority > lastPriority) {
20582                lastComponent = ri.activityInfo.getComponentName();
20583                lastPriority = ri.priority;
20584            } else if (ri.priority == lastPriority) {
20585                // Two components found with same priority.
20586                lastComponent = null;
20587            }
20588        }
20589        return lastComponent;
20590    }
20591
20592    private Intent getHomeIntent() {
20593        Intent intent = new Intent(Intent.ACTION_MAIN);
20594        intent.addCategory(Intent.CATEGORY_HOME);
20595        intent.addCategory(Intent.CATEGORY_DEFAULT);
20596        return intent;
20597    }
20598
20599    private IntentFilter getHomeFilter() {
20600        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20601        filter.addCategory(Intent.CATEGORY_HOME);
20602        filter.addCategory(Intent.CATEGORY_DEFAULT);
20603        return filter;
20604    }
20605
20606    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20607            int userId) {
20608        Intent intent  = getHomeIntent();
20609        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20610                PackageManager.GET_META_DATA, userId);
20611        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20612                true, false, false, userId);
20613
20614        allHomeCandidates.clear();
20615        if (list != null) {
20616            for (ResolveInfo ri : list) {
20617                allHomeCandidates.add(ri);
20618            }
20619        }
20620        return (preferred == null || preferred.activityInfo == null)
20621                ? null
20622                : new ComponentName(preferred.activityInfo.packageName,
20623                        preferred.activityInfo.name);
20624    }
20625
20626    @Override
20627    public void setHomeActivity(ComponentName comp, int userId) {
20628        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20629            return;
20630        }
20631        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20632        getHomeActivitiesAsUser(homeActivities, userId);
20633
20634        boolean found = false;
20635
20636        final int size = homeActivities.size();
20637        final ComponentName[] set = new ComponentName[size];
20638        for (int i = 0; i < size; i++) {
20639            final ResolveInfo candidate = homeActivities.get(i);
20640            final ActivityInfo info = candidate.activityInfo;
20641            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20642            set[i] = activityName;
20643            if (!found && activityName.equals(comp)) {
20644                found = true;
20645            }
20646        }
20647        if (!found) {
20648            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20649                    + userId);
20650        }
20651        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20652                set, comp, userId);
20653    }
20654
20655    private @Nullable String getSetupWizardPackageName() {
20656        final Intent intent = new Intent(Intent.ACTION_MAIN);
20657        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20658
20659        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20660                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20661                        | MATCH_DISABLED_COMPONENTS,
20662                UserHandle.myUserId());
20663        if (matches.size() == 1) {
20664            return matches.get(0).getComponentInfo().packageName;
20665        } else {
20666            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20667                    + ": matches=" + matches);
20668            return null;
20669        }
20670    }
20671
20672    private @Nullable String getStorageManagerPackageName() {
20673        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20674
20675        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20676                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20677                        | MATCH_DISABLED_COMPONENTS,
20678                UserHandle.myUserId());
20679        if (matches.size() == 1) {
20680            return matches.get(0).getComponentInfo().packageName;
20681        } else {
20682            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20683                    + matches.size() + ": matches=" + matches);
20684            return null;
20685        }
20686    }
20687
20688    @Override
20689    public void setApplicationEnabledSetting(String appPackageName,
20690            int newState, int flags, int userId, String callingPackage) {
20691        if (!sUserManager.exists(userId)) return;
20692        if (callingPackage == null) {
20693            callingPackage = Integer.toString(Binder.getCallingUid());
20694        }
20695        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20696    }
20697
20698    @Override
20699    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20700        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20701        synchronized (mPackages) {
20702            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20703            if (pkgSetting != null) {
20704                pkgSetting.setUpdateAvailable(updateAvailable);
20705            }
20706        }
20707    }
20708
20709    @Override
20710    public void setComponentEnabledSetting(ComponentName componentName,
20711            int newState, int flags, int userId) {
20712        if (!sUserManager.exists(userId)) return;
20713        setEnabledSetting(componentName.getPackageName(),
20714                componentName.getClassName(), newState, flags, userId, null);
20715    }
20716
20717    private void setEnabledSetting(final String packageName, String className, int newState,
20718            final int flags, int userId, String callingPackage) {
20719        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20720              || newState == COMPONENT_ENABLED_STATE_ENABLED
20721              || newState == COMPONENT_ENABLED_STATE_DISABLED
20722              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20723              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20724            throw new IllegalArgumentException("Invalid new component state: "
20725                    + newState);
20726        }
20727        PackageSetting pkgSetting;
20728        final int callingUid = Binder.getCallingUid();
20729        final int permission;
20730        if (callingUid == Process.SYSTEM_UID) {
20731            permission = PackageManager.PERMISSION_GRANTED;
20732        } else {
20733            permission = mContext.checkCallingOrSelfPermission(
20734                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20735        }
20736        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20737                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20738        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20739        boolean sendNow = false;
20740        boolean isApp = (className == null);
20741        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20742        String componentName = isApp ? packageName : className;
20743        int packageUid = -1;
20744        ArrayList<String> components;
20745
20746        // reader
20747        synchronized (mPackages) {
20748            pkgSetting = mSettings.mPackages.get(packageName);
20749            if (pkgSetting == null) {
20750                if (!isCallerInstantApp) {
20751                    if (className == null) {
20752                        throw new IllegalArgumentException("Unknown package: " + packageName);
20753                    }
20754                    throw new IllegalArgumentException(
20755                            "Unknown component: " + packageName + "/" + className);
20756                } else {
20757                    // throw SecurityException to prevent leaking package information
20758                    throw new SecurityException(
20759                            "Attempt to change component state; "
20760                            + "pid=" + Binder.getCallingPid()
20761                            + ", uid=" + callingUid
20762                            + (className == null
20763                                    ? ", package=" + packageName
20764                                    : ", component=" + packageName + "/" + className));
20765                }
20766            }
20767        }
20768
20769        // Limit who can change which apps
20770        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20771            // Don't allow apps that don't have permission to modify other apps
20772            if (!allowedByPermission
20773                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20774                throw new SecurityException(
20775                        "Attempt to change component state; "
20776                        + "pid=" + Binder.getCallingPid()
20777                        + ", uid=" + callingUid
20778                        + (className == null
20779                                ? ", package=" + packageName
20780                                : ", component=" + packageName + "/" + className));
20781            }
20782            // Don't allow changing protected packages.
20783            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20784                throw new SecurityException("Cannot disable a protected package: " + packageName);
20785            }
20786        }
20787
20788        synchronized (mPackages) {
20789            if (callingUid == Process.SHELL_UID
20790                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20791                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20792                // unless it is a test package.
20793                int oldState = pkgSetting.getEnabled(userId);
20794                if (className == null
20795                        &&
20796                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20797                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20798                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20799                        &&
20800                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20801                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20802                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20803                    // ok
20804                } else {
20805                    throw new SecurityException(
20806                            "Shell cannot change component state for " + packageName + "/"
20807                                    + className + " to " + newState);
20808                }
20809            }
20810        }
20811        if (className == null) {
20812            // We're dealing with an application/package level state change
20813            synchronized (mPackages) {
20814                if (pkgSetting.getEnabled(userId) == newState) {
20815                    // Nothing to do
20816                    return;
20817                }
20818            }
20819            // If we're enabling a system stub, there's a little more work to do.
20820            // Prior to enabling the package, we need to decompress the APK(s) to the
20821            // data partition and then replace the version on the system partition.
20822            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20823            final boolean isSystemStub = deletedPkg.isStub
20824                    && deletedPkg.isSystemApp();
20825            if (isSystemStub
20826                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20827                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20828                final File codePath = decompressPackage(deletedPkg);
20829                if (codePath == null) {
20830                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20831                    return;
20832                }
20833                // TODO remove direct parsing of the package object during internal cleanup
20834                // of scan package
20835                // We need to call parse directly here for no other reason than we need
20836                // the new package in order to disable the old one [we use the information
20837                // for some internal optimization to optionally create a new package setting
20838                // object on replace]. However, we can't get the package from the scan
20839                // because the scan modifies live structures and we need to remove the
20840                // old [system] package from the system before a scan can be attempted.
20841                // Once scan is indempotent we can remove this parse and use the package
20842                // object we scanned, prior to adding it to package settings.
20843                final PackageParser pp = new PackageParser();
20844                pp.setSeparateProcesses(mSeparateProcesses);
20845                pp.setDisplayMetrics(mMetrics);
20846                pp.setCallback(mPackageParserCallback);
20847                final PackageParser.Package tmpPkg;
20848                try {
20849                    final int parseFlags = mDefParseFlags
20850                            | PackageParser.PARSE_MUST_BE_APK
20851                            | PackageParser.PARSE_IS_SYSTEM
20852                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20853                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20854                } catch (PackageParserException e) {
20855                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20856                    return;
20857                }
20858                synchronized (mInstallLock) {
20859                    // Disable the stub and remove any package entries
20860                    removePackageLI(deletedPkg, true);
20861                    synchronized (mPackages) {
20862                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20863                    }
20864                    final PackageParser.Package newPkg;
20865                    try (PackageFreezer freezer =
20866                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20867                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20868                                | PackageParser.PARSE_ENFORCE_CODE;
20869                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20870                                0 /*currentTime*/, null /*user*/);
20871                        prepareAppDataAfterInstallLIF(newPkg);
20872                        synchronized (mPackages) {
20873                            try {
20874                                updateSharedLibrariesLPr(newPkg, null);
20875                            } catch (PackageManagerException e) {
20876                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20877                            }
20878                            updatePermissionsLPw(newPkg.packageName, newPkg,
20879                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20880                            mSettings.writeLPr();
20881                        }
20882                    } catch (PackageManagerException e) {
20883                        // Whoops! Something went wrong; try to roll back to the stub
20884                        Slog.w(TAG, "Failed to install compressed system package:"
20885                                + pkgSetting.name, e);
20886                        // Remove the failed install
20887                        removeCodePathLI(codePath);
20888
20889                        // Install the system package
20890                        try (PackageFreezer freezer =
20891                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20892                            synchronized (mPackages) {
20893                                // NOTE: The system package always needs to be enabled; even
20894                                // if it's for a compressed stub. If we don't, installing the
20895                                // system package fails during scan [scanning checks the disabled
20896                                // packages]. We will reverse this later, after we've "installed"
20897                                // the stub.
20898                                // This leaves us in a fragile state; the stub should never be
20899                                // enabled, so, cross your fingers and hope nothing goes wrong
20900                                // until we can disable the package later.
20901                                enableSystemPackageLPw(deletedPkg);
20902                            }
20903                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20904                                    false /*isPrivileged*/, null /*allUserHandles*/,
20905                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20906                                    true /*writeSettings*/);
20907                        } catch (PackageManagerException pme) {
20908                            Slog.w(TAG, "Failed to restore system package:"
20909                                    + deletedPkg.packageName, pme);
20910                        } finally {
20911                            synchronized (mPackages) {
20912                                mSettings.disableSystemPackageLPw(
20913                                        deletedPkg.packageName, true /*replaced*/);
20914                                mSettings.writeLPr();
20915                            }
20916                        }
20917                        return;
20918                    }
20919                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20920                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20921                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20922                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20923                            newPkg.baseCodePath, newPkg.splitCodePaths);
20924                }
20925            }
20926            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20927                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20928                // Don't care about who enables an app.
20929                callingPackage = null;
20930            }
20931            synchronized (mPackages) {
20932                pkgSetting.setEnabled(newState, userId, callingPackage);
20933            }
20934        } else {
20935            synchronized (mPackages) {
20936                // We're dealing with a component level state change
20937                // First, verify that this is a valid class name.
20938                PackageParser.Package pkg = pkgSetting.pkg;
20939                if (pkg == null || !pkg.hasComponentClassName(className)) {
20940                    if (pkg != null &&
20941                            pkg.applicationInfo.targetSdkVersion >=
20942                                    Build.VERSION_CODES.JELLY_BEAN) {
20943                        throw new IllegalArgumentException("Component class " + className
20944                                + " does not exist in " + packageName);
20945                    } else {
20946                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20947                                + className + " does not exist in " + packageName);
20948                    }
20949                }
20950                switch (newState) {
20951                    case COMPONENT_ENABLED_STATE_ENABLED:
20952                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20953                            return;
20954                        }
20955                        break;
20956                    case COMPONENT_ENABLED_STATE_DISABLED:
20957                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20958                            return;
20959                        }
20960                        break;
20961                    case COMPONENT_ENABLED_STATE_DEFAULT:
20962                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20963                            return;
20964                        }
20965                        break;
20966                    default:
20967                        Slog.e(TAG, "Invalid new component state: " + newState);
20968                        return;
20969                }
20970            }
20971        }
20972        synchronized (mPackages) {
20973            scheduleWritePackageRestrictionsLocked(userId);
20974            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20975            final long callingId = Binder.clearCallingIdentity();
20976            try {
20977                updateInstantAppInstallerLocked(packageName);
20978            } finally {
20979                Binder.restoreCallingIdentity(callingId);
20980            }
20981            components = mPendingBroadcasts.get(userId, packageName);
20982            final boolean newPackage = components == null;
20983            if (newPackage) {
20984                components = new ArrayList<String>();
20985            }
20986            if (!components.contains(componentName)) {
20987                components.add(componentName);
20988            }
20989            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20990                sendNow = true;
20991                // Purge entry from pending broadcast list if another one exists already
20992                // since we are sending one right away.
20993                mPendingBroadcasts.remove(userId, packageName);
20994            } else {
20995                if (newPackage) {
20996                    mPendingBroadcasts.put(userId, packageName, components);
20997                }
20998                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20999                    // Schedule a message
21000                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21001                }
21002            }
21003        }
21004
21005        long callingId = Binder.clearCallingIdentity();
21006        try {
21007            if (sendNow) {
21008                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21009                sendPackageChangedBroadcast(packageName,
21010                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21011            }
21012        } finally {
21013            Binder.restoreCallingIdentity(callingId);
21014        }
21015    }
21016
21017    @Override
21018    public void flushPackageRestrictionsAsUser(int userId) {
21019        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21020            return;
21021        }
21022        if (!sUserManager.exists(userId)) {
21023            return;
21024        }
21025        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21026                false /* checkShell */, "flushPackageRestrictions");
21027        synchronized (mPackages) {
21028            mSettings.writePackageRestrictionsLPr(userId);
21029            mDirtyUsers.remove(userId);
21030            if (mDirtyUsers.isEmpty()) {
21031                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21032            }
21033        }
21034    }
21035
21036    private void sendPackageChangedBroadcast(String packageName,
21037            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21038        if (DEBUG_INSTALL)
21039            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21040                    + componentNames);
21041        Bundle extras = new Bundle(4);
21042        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21043        String nameList[] = new String[componentNames.size()];
21044        componentNames.toArray(nameList);
21045        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21046        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21047        extras.putInt(Intent.EXTRA_UID, packageUid);
21048        // If this is not reporting a change of the overall package, then only send it
21049        // to registered receivers.  We don't want to launch a swath of apps for every
21050        // little component state change.
21051        final int flags = !componentNames.contains(packageName)
21052                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21053        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21054                new int[] {UserHandle.getUserId(packageUid)});
21055    }
21056
21057    @Override
21058    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21059        if (!sUserManager.exists(userId)) return;
21060        final int callingUid = Binder.getCallingUid();
21061        if (getInstantAppPackageName(callingUid) != null) {
21062            return;
21063        }
21064        final int permission = mContext.checkCallingOrSelfPermission(
21065                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21066        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21067        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21068                true /* requireFullPermission */, true /* checkShell */, "stop package");
21069        // writer
21070        synchronized (mPackages) {
21071            final PackageSetting ps = mSettings.mPackages.get(packageName);
21072            if (!filterAppAccessLPr(ps, callingUid, userId)
21073                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21074                            allowedByPermission, callingUid, userId)) {
21075                scheduleWritePackageRestrictionsLocked(userId);
21076            }
21077        }
21078    }
21079
21080    @Override
21081    public String getInstallerPackageName(String packageName) {
21082        final int callingUid = Binder.getCallingUid();
21083        if (getInstantAppPackageName(callingUid) != null) {
21084            return null;
21085        }
21086        // reader
21087        synchronized (mPackages) {
21088            final PackageSetting ps = mSettings.mPackages.get(packageName);
21089            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21090                return null;
21091            }
21092            return mSettings.getInstallerPackageNameLPr(packageName);
21093        }
21094    }
21095
21096    public boolean isOrphaned(String packageName) {
21097        // reader
21098        synchronized (mPackages) {
21099            return mSettings.isOrphaned(packageName);
21100        }
21101    }
21102
21103    @Override
21104    public int getApplicationEnabledSetting(String packageName, int userId) {
21105        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21106        int callingUid = Binder.getCallingUid();
21107        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21108                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21109        // reader
21110        synchronized (mPackages) {
21111            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21112                return COMPONENT_ENABLED_STATE_DISABLED;
21113            }
21114            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21115        }
21116    }
21117
21118    @Override
21119    public int getComponentEnabledSetting(ComponentName component, int userId) {
21120        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21121        int callingUid = Binder.getCallingUid();
21122        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21123                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21124        synchronized (mPackages) {
21125            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21126                    component, TYPE_UNKNOWN, userId)) {
21127                return COMPONENT_ENABLED_STATE_DISABLED;
21128            }
21129            return mSettings.getComponentEnabledSettingLPr(component, userId);
21130        }
21131    }
21132
21133    @Override
21134    public void enterSafeMode() {
21135        enforceSystemOrRoot("Only the system can request entering safe mode");
21136
21137        if (!mSystemReady) {
21138            mSafeMode = true;
21139        }
21140    }
21141
21142    @Override
21143    public void systemReady() {
21144        enforceSystemOrRoot("Only the system can claim the system is ready");
21145
21146        mSystemReady = true;
21147        final ContentResolver resolver = mContext.getContentResolver();
21148        ContentObserver co = new ContentObserver(mHandler) {
21149            @Override
21150            public void onChange(boolean selfChange) {
21151                mEphemeralAppsDisabled =
21152                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21153                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21154            }
21155        };
21156        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21157                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21158                false, co, UserHandle.USER_SYSTEM);
21159        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21160                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21161        co.onChange(true);
21162
21163        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21164        // disabled after already being started.
21165        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21166                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21167
21168        // Read the compatibilty setting when the system is ready.
21169        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21170                mContext.getContentResolver(),
21171                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21172        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21173        if (DEBUG_SETTINGS) {
21174            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21175        }
21176
21177        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21178
21179        synchronized (mPackages) {
21180            // Verify that all of the preferred activity components actually
21181            // exist.  It is possible for applications to be updated and at
21182            // that point remove a previously declared activity component that
21183            // had been set as a preferred activity.  We try to clean this up
21184            // the next time we encounter that preferred activity, but it is
21185            // possible for the user flow to never be able to return to that
21186            // situation so here we do a sanity check to make sure we haven't
21187            // left any junk around.
21188            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21189            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21190                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21191                removed.clear();
21192                for (PreferredActivity pa : pir.filterSet()) {
21193                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21194                        removed.add(pa);
21195                    }
21196                }
21197                if (removed.size() > 0) {
21198                    for (int r=0; r<removed.size(); r++) {
21199                        PreferredActivity pa = removed.get(r);
21200                        Slog.w(TAG, "Removing dangling preferred activity: "
21201                                + pa.mPref.mComponent);
21202                        pir.removeFilter(pa);
21203                    }
21204                    mSettings.writePackageRestrictionsLPr(
21205                            mSettings.mPreferredActivities.keyAt(i));
21206                }
21207            }
21208
21209            for (int userId : UserManagerService.getInstance().getUserIds()) {
21210                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21211                    grantPermissionsUserIds = ArrayUtils.appendInt(
21212                            grantPermissionsUserIds, userId);
21213                }
21214            }
21215        }
21216        sUserManager.systemReady();
21217
21218        synchronized(mPackages) {
21219            // If we upgraded grant all default permissions before kicking off.
21220            for (int userId : grantPermissionsUserIds) {
21221                mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21222            }
21223        }
21224
21225        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21226            // If we did not grant default permissions, we preload from this the
21227            // default permission exceptions lazily to ensure we don't hit the
21228            // disk on a new user creation.
21229            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21230        }
21231
21232        // Now that we've scanned all packages, and granted any default
21233        // permissions, ensure permissions are updated. Beware of dragons if you
21234        // try optimizing this.
21235        synchronized (mPackages) {
21236            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21237                    UPDATE_PERMISSIONS_ALL);
21238        }
21239
21240        // Kick off any messages waiting for system ready
21241        if (mPostSystemReadyMessages != null) {
21242            for (Message msg : mPostSystemReadyMessages) {
21243                msg.sendToTarget();
21244            }
21245            mPostSystemReadyMessages = null;
21246        }
21247
21248        // Watch for external volumes that come and go over time
21249        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21250        storage.registerListener(mStorageListener);
21251
21252        mInstallerService.systemReady();
21253        mPackageDexOptimizer.systemReady();
21254
21255        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21256                StorageManagerInternal.class);
21257        StorageManagerInternal.addExternalStoragePolicy(
21258                new StorageManagerInternal.ExternalStorageMountPolicy() {
21259            @Override
21260            public int getMountMode(int uid, String packageName) {
21261                if (Process.isIsolated(uid)) {
21262                    return Zygote.MOUNT_EXTERNAL_NONE;
21263                }
21264                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21265                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21266                }
21267                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21268                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21269                }
21270                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21271                    return Zygote.MOUNT_EXTERNAL_READ;
21272                }
21273                return Zygote.MOUNT_EXTERNAL_WRITE;
21274            }
21275
21276            @Override
21277            public boolean hasExternalStorage(int uid, String packageName) {
21278                return true;
21279            }
21280        });
21281
21282        // Now that we're mostly running, clean up stale users and apps
21283        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21284        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21285
21286        if (mPrivappPermissionsViolations != null) {
21287            Slog.wtf(TAG,"Signature|privileged permissions not in "
21288                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21289            mPrivappPermissionsViolations = null;
21290        }
21291    }
21292
21293    public void waitForAppDataPrepared() {
21294        if (mPrepareAppDataFuture == null) {
21295            return;
21296        }
21297        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21298        mPrepareAppDataFuture = null;
21299    }
21300
21301    @Override
21302    public boolean isSafeMode() {
21303        // allow instant applications
21304        return mSafeMode;
21305    }
21306
21307    @Override
21308    public boolean hasSystemUidErrors() {
21309        // allow instant applications
21310        return mHasSystemUidErrors;
21311    }
21312
21313    static String arrayToString(int[] array) {
21314        StringBuffer buf = new StringBuffer(128);
21315        buf.append('[');
21316        if (array != null) {
21317            for (int i=0; i<array.length; i++) {
21318                if (i > 0) buf.append(", ");
21319                buf.append(array[i]);
21320            }
21321        }
21322        buf.append(']');
21323        return buf.toString();
21324    }
21325
21326    @Override
21327    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21328            FileDescriptor err, String[] args, ShellCallback callback,
21329            ResultReceiver resultReceiver) {
21330        (new PackageManagerShellCommand(this)).exec(
21331                this, in, out, err, args, callback, resultReceiver);
21332    }
21333
21334    @Override
21335    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21336        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21337
21338        DumpState dumpState = new DumpState();
21339        boolean fullPreferred = false;
21340        boolean checkin = false;
21341
21342        String packageName = null;
21343        ArraySet<String> permissionNames = null;
21344
21345        int opti = 0;
21346        while (opti < args.length) {
21347            String opt = args[opti];
21348            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21349                break;
21350            }
21351            opti++;
21352
21353            if ("-a".equals(opt)) {
21354                // Right now we only know how to print all.
21355            } else if ("-h".equals(opt)) {
21356                pw.println("Package manager dump options:");
21357                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21358                pw.println("    --checkin: dump for a checkin");
21359                pw.println("    -f: print details of intent filters");
21360                pw.println("    -h: print this help");
21361                pw.println("  cmd may be one of:");
21362                pw.println("    l[ibraries]: list known shared libraries");
21363                pw.println("    f[eatures]: list device features");
21364                pw.println("    k[eysets]: print known keysets");
21365                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21366                pw.println("    perm[issions]: dump permissions");
21367                pw.println("    permission [name ...]: dump declaration and use of given permission");
21368                pw.println("    pref[erred]: print preferred package settings");
21369                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21370                pw.println("    prov[iders]: dump content providers");
21371                pw.println("    p[ackages]: dump installed packages");
21372                pw.println("    s[hared-users]: dump shared user IDs");
21373                pw.println("    m[essages]: print collected runtime messages");
21374                pw.println("    v[erifiers]: print package verifier info");
21375                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21376                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21377                pw.println("    version: print database version info");
21378                pw.println("    write: write current settings now");
21379                pw.println("    installs: details about install sessions");
21380                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21381                pw.println("    dexopt: dump dexopt state");
21382                pw.println("    compiler-stats: dump compiler statistics");
21383                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21384                pw.println("    <package.name>: info about given package");
21385                return;
21386            } else if ("--checkin".equals(opt)) {
21387                checkin = true;
21388            } else if ("-f".equals(opt)) {
21389                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21390            } else if ("--proto".equals(opt)) {
21391                dumpProto(fd);
21392                return;
21393            } else {
21394                pw.println("Unknown argument: " + opt + "; use -h for help");
21395            }
21396        }
21397
21398        // Is the caller requesting to dump a particular piece of data?
21399        if (opti < args.length) {
21400            String cmd = args[opti];
21401            opti++;
21402            // Is this a package name?
21403            if ("android".equals(cmd) || cmd.contains(".")) {
21404                packageName = cmd;
21405                // When dumping a single package, we always dump all of its
21406                // filter information since the amount of data will be reasonable.
21407                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21408            } else if ("check-permission".equals(cmd)) {
21409                if (opti >= args.length) {
21410                    pw.println("Error: check-permission missing permission argument");
21411                    return;
21412                }
21413                String perm = args[opti];
21414                opti++;
21415                if (opti >= args.length) {
21416                    pw.println("Error: check-permission missing package argument");
21417                    return;
21418                }
21419
21420                String pkg = args[opti];
21421                opti++;
21422                int user = UserHandle.getUserId(Binder.getCallingUid());
21423                if (opti < args.length) {
21424                    try {
21425                        user = Integer.parseInt(args[opti]);
21426                    } catch (NumberFormatException e) {
21427                        pw.println("Error: check-permission user argument is not a number: "
21428                                + args[opti]);
21429                        return;
21430                    }
21431                }
21432
21433                // Normalize package name to handle renamed packages and static libs
21434                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21435
21436                pw.println(checkPermission(perm, pkg, user));
21437                return;
21438            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21439                dumpState.setDump(DumpState.DUMP_LIBS);
21440            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21441                dumpState.setDump(DumpState.DUMP_FEATURES);
21442            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21443                if (opti >= args.length) {
21444                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21445                            | DumpState.DUMP_SERVICE_RESOLVERS
21446                            | DumpState.DUMP_RECEIVER_RESOLVERS
21447                            | DumpState.DUMP_CONTENT_RESOLVERS);
21448                } else {
21449                    while (opti < args.length) {
21450                        String name = args[opti];
21451                        if ("a".equals(name) || "activity".equals(name)) {
21452                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21453                        } else if ("s".equals(name) || "service".equals(name)) {
21454                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21455                        } else if ("r".equals(name) || "receiver".equals(name)) {
21456                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21457                        } else if ("c".equals(name) || "content".equals(name)) {
21458                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21459                        } else {
21460                            pw.println("Error: unknown resolver table type: " + name);
21461                            return;
21462                        }
21463                        opti++;
21464                    }
21465                }
21466            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21467                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21468            } else if ("permission".equals(cmd)) {
21469                if (opti >= args.length) {
21470                    pw.println("Error: permission requires permission name");
21471                    return;
21472                }
21473                permissionNames = new ArraySet<>();
21474                while (opti < args.length) {
21475                    permissionNames.add(args[opti]);
21476                    opti++;
21477                }
21478                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21479                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21480            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21481                dumpState.setDump(DumpState.DUMP_PREFERRED);
21482            } else if ("preferred-xml".equals(cmd)) {
21483                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21484                if (opti < args.length && "--full".equals(args[opti])) {
21485                    fullPreferred = true;
21486                    opti++;
21487                }
21488            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21489                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21490            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21491                dumpState.setDump(DumpState.DUMP_PACKAGES);
21492            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21493                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21494            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21495                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21496            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21497                dumpState.setDump(DumpState.DUMP_MESSAGES);
21498            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21499                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21500            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21501                    || "intent-filter-verifiers".equals(cmd)) {
21502                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21503            } else if ("version".equals(cmd)) {
21504                dumpState.setDump(DumpState.DUMP_VERSION);
21505            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21506                dumpState.setDump(DumpState.DUMP_KEYSETS);
21507            } else if ("installs".equals(cmd)) {
21508                dumpState.setDump(DumpState.DUMP_INSTALLS);
21509            } else if ("frozen".equals(cmd)) {
21510                dumpState.setDump(DumpState.DUMP_FROZEN);
21511            } else if ("volumes".equals(cmd)) {
21512                dumpState.setDump(DumpState.DUMP_VOLUMES);
21513            } else if ("dexopt".equals(cmd)) {
21514                dumpState.setDump(DumpState.DUMP_DEXOPT);
21515            } else if ("compiler-stats".equals(cmd)) {
21516                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21517            } else if ("changes".equals(cmd)) {
21518                dumpState.setDump(DumpState.DUMP_CHANGES);
21519            } else if ("write".equals(cmd)) {
21520                synchronized (mPackages) {
21521                    mSettings.writeLPr();
21522                    pw.println("Settings written.");
21523                    return;
21524                }
21525            }
21526        }
21527
21528        if (checkin) {
21529            pw.println("vers,1");
21530        }
21531
21532        // reader
21533        synchronized (mPackages) {
21534            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21535                if (!checkin) {
21536                    if (dumpState.onTitlePrinted())
21537                        pw.println();
21538                    pw.println("Database versions:");
21539                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21540                }
21541            }
21542
21543            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21544                if (!checkin) {
21545                    if (dumpState.onTitlePrinted())
21546                        pw.println();
21547                    pw.println("Verifiers:");
21548                    pw.print("  Required: ");
21549                    pw.print(mRequiredVerifierPackage);
21550                    pw.print(" (uid=");
21551                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21552                            UserHandle.USER_SYSTEM));
21553                    pw.println(")");
21554                } else if (mRequiredVerifierPackage != null) {
21555                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21556                    pw.print(",");
21557                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21558                            UserHandle.USER_SYSTEM));
21559                }
21560            }
21561
21562            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21563                    packageName == null) {
21564                if (mIntentFilterVerifierComponent != null) {
21565                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21566                    if (!checkin) {
21567                        if (dumpState.onTitlePrinted())
21568                            pw.println();
21569                        pw.println("Intent Filter Verifier:");
21570                        pw.print("  Using: ");
21571                        pw.print(verifierPackageName);
21572                        pw.print(" (uid=");
21573                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21574                                UserHandle.USER_SYSTEM));
21575                        pw.println(")");
21576                    } else if (verifierPackageName != null) {
21577                        pw.print("ifv,"); pw.print(verifierPackageName);
21578                        pw.print(",");
21579                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21580                                UserHandle.USER_SYSTEM));
21581                    }
21582                } else {
21583                    pw.println();
21584                    pw.println("No Intent Filter Verifier available!");
21585                }
21586            }
21587
21588            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21589                boolean printedHeader = false;
21590                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21591                while (it.hasNext()) {
21592                    String libName = it.next();
21593                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21594                    if (versionedLib == null) {
21595                        continue;
21596                    }
21597                    final int versionCount = versionedLib.size();
21598                    for (int i = 0; i < versionCount; i++) {
21599                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21600                        if (!checkin) {
21601                            if (!printedHeader) {
21602                                if (dumpState.onTitlePrinted())
21603                                    pw.println();
21604                                pw.println("Libraries:");
21605                                printedHeader = true;
21606                            }
21607                            pw.print("  ");
21608                        } else {
21609                            pw.print("lib,");
21610                        }
21611                        pw.print(libEntry.info.getName());
21612                        if (libEntry.info.isStatic()) {
21613                            pw.print(" version=" + libEntry.info.getVersion());
21614                        }
21615                        if (!checkin) {
21616                            pw.print(" -> ");
21617                        }
21618                        if (libEntry.path != null) {
21619                            pw.print(" (jar) ");
21620                            pw.print(libEntry.path);
21621                        } else {
21622                            pw.print(" (apk) ");
21623                            pw.print(libEntry.apk);
21624                        }
21625                        pw.println();
21626                    }
21627                }
21628            }
21629
21630            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21631                if (dumpState.onTitlePrinted())
21632                    pw.println();
21633                if (!checkin) {
21634                    pw.println("Features:");
21635                }
21636
21637                synchronized (mAvailableFeatures) {
21638                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21639                        if (checkin) {
21640                            pw.print("feat,");
21641                            pw.print(feat.name);
21642                            pw.print(",");
21643                            pw.println(feat.version);
21644                        } else {
21645                            pw.print("  ");
21646                            pw.print(feat.name);
21647                            if (feat.version > 0) {
21648                                pw.print(" version=");
21649                                pw.print(feat.version);
21650                            }
21651                            pw.println();
21652                        }
21653                    }
21654                }
21655            }
21656
21657            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21658                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21659                        : "Activity Resolver Table:", "  ", packageName,
21660                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21661                    dumpState.setTitlePrinted(true);
21662                }
21663            }
21664            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21665                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21666                        : "Receiver Resolver Table:", "  ", packageName,
21667                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21668                    dumpState.setTitlePrinted(true);
21669                }
21670            }
21671            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21672                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21673                        : "Service Resolver Table:", "  ", packageName,
21674                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21675                    dumpState.setTitlePrinted(true);
21676                }
21677            }
21678            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21679                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21680                        : "Provider Resolver Table:", "  ", packageName,
21681                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21682                    dumpState.setTitlePrinted(true);
21683                }
21684            }
21685
21686            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21687                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21688                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21689                    int user = mSettings.mPreferredActivities.keyAt(i);
21690                    if (pir.dump(pw,
21691                            dumpState.getTitlePrinted()
21692                                ? "\nPreferred Activities User " + user + ":"
21693                                : "Preferred Activities User " + user + ":", "  ",
21694                            packageName, true, false)) {
21695                        dumpState.setTitlePrinted(true);
21696                    }
21697                }
21698            }
21699
21700            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21701                pw.flush();
21702                FileOutputStream fout = new FileOutputStream(fd);
21703                BufferedOutputStream str = new BufferedOutputStream(fout);
21704                XmlSerializer serializer = new FastXmlSerializer();
21705                try {
21706                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21707                    serializer.startDocument(null, true);
21708                    serializer.setFeature(
21709                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21710                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21711                    serializer.endDocument();
21712                    serializer.flush();
21713                } catch (IllegalArgumentException e) {
21714                    pw.println("Failed writing: " + e);
21715                } catch (IllegalStateException e) {
21716                    pw.println("Failed writing: " + e);
21717                } catch (IOException e) {
21718                    pw.println("Failed writing: " + e);
21719                }
21720            }
21721
21722            if (!checkin
21723                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21724                    && packageName == null) {
21725                pw.println();
21726                int count = mSettings.mPackages.size();
21727                if (count == 0) {
21728                    pw.println("No applications!");
21729                    pw.println();
21730                } else {
21731                    final String prefix = "  ";
21732                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21733                    if (allPackageSettings.size() == 0) {
21734                        pw.println("No domain preferred apps!");
21735                        pw.println();
21736                    } else {
21737                        pw.println("App verification status:");
21738                        pw.println();
21739                        count = 0;
21740                        for (PackageSetting ps : allPackageSettings) {
21741                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21742                            if (ivi == null || ivi.getPackageName() == null) continue;
21743                            pw.println(prefix + "Package: " + ivi.getPackageName());
21744                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21745                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21746                            pw.println();
21747                            count++;
21748                        }
21749                        if (count == 0) {
21750                            pw.println(prefix + "No app verification established.");
21751                            pw.println();
21752                        }
21753                        for (int userId : sUserManager.getUserIds()) {
21754                            pw.println("App linkages for user " + userId + ":");
21755                            pw.println();
21756                            count = 0;
21757                            for (PackageSetting ps : allPackageSettings) {
21758                                final long status = ps.getDomainVerificationStatusForUser(userId);
21759                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21760                                        && !DEBUG_DOMAIN_VERIFICATION) {
21761                                    continue;
21762                                }
21763                                pw.println(prefix + "Package: " + ps.name);
21764                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21765                                String statusStr = IntentFilterVerificationInfo.
21766                                        getStatusStringFromValue(status);
21767                                pw.println(prefix + "Status:  " + statusStr);
21768                                pw.println();
21769                                count++;
21770                            }
21771                            if (count == 0) {
21772                                pw.println(prefix + "No configured app linkages.");
21773                                pw.println();
21774                            }
21775                        }
21776                    }
21777                }
21778            }
21779
21780            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21781                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21782                if (packageName == null && permissionNames == null) {
21783                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21784                        if (iperm == 0) {
21785                            if (dumpState.onTitlePrinted())
21786                                pw.println();
21787                            pw.println("AppOp Permissions:");
21788                        }
21789                        pw.print("  AppOp Permission ");
21790                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21791                        pw.println(":");
21792                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21793                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21794                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21795                        }
21796                    }
21797                }
21798            }
21799
21800            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21801                boolean printedSomething = false;
21802                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21803                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21804                        continue;
21805                    }
21806                    if (!printedSomething) {
21807                        if (dumpState.onTitlePrinted())
21808                            pw.println();
21809                        pw.println("Registered ContentProviders:");
21810                        printedSomething = true;
21811                    }
21812                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21813                    pw.print("    "); pw.println(p.toString());
21814                }
21815                printedSomething = false;
21816                for (Map.Entry<String, PackageParser.Provider> entry :
21817                        mProvidersByAuthority.entrySet()) {
21818                    PackageParser.Provider p = entry.getValue();
21819                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21820                        continue;
21821                    }
21822                    if (!printedSomething) {
21823                        if (dumpState.onTitlePrinted())
21824                            pw.println();
21825                        pw.println("ContentProvider Authorities:");
21826                        printedSomething = true;
21827                    }
21828                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21829                    pw.print("    "); pw.println(p.toString());
21830                    if (p.info != null && p.info.applicationInfo != null) {
21831                        final String appInfo = p.info.applicationInfo.toString();
21832                        pw.print("      applicationInfo="); pw.println(appInfo);
21833                    }
21834                }
21835            }
21836
21837            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21838                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21839            }
21840
21841            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21842                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21843            }
21844
21845            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21846                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21847            }
21848
21849            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21850                if (dumpState.onTitlePrinted()) pw.println();
21851                pw.println("Package Changes:");
21852                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21853                final int K = mChangedPackages.size();
21854                for (int i = 0; i < K; i++) {
21855                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21856                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21857                    final int N = changes.size();
21858                    if (N == 0) {
21859                        pw.print("    "); pw.println("No packages changed");
21860                    } else {
21861                        for (int j = 0; j < N; j++) {
21862                            final String pkgName = changes.valueAt(j);
21863                            final int sequenceNumber = changes.keyAt(j);
21864                            pw.print("    ");
21865                            pw.print("seq=");
21866                            pw.print(sequenceNumber);
21867                            pw.print(", package=");
21868                            pw.println(pkgName);
21869                        }
21870                    }
21871                }
21872            }
21873
21874            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21875                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21876            }
21877
21878            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21879                // XXX should handle packageName != null by dumping only install data that
21880                // the given package is involved with.
21881                if (dumpState.onTitlePrinted()) pw.println();
21882
21883                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21884                ipw.println();
21885                ipw.println("Frozen packages:");
21886                ipw.increaseIndent();
21887                if (mFrozenPackages.size() == 0) {
21888                    ipw.println("(none)");
21889                } else {
21890                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21891                        ipw.println(mFrozenPackages.valueAt(i));
21892                    }
21893                }
21894                ipw.decreaseIndent();
21895            }
21896
21897            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21898                if (dumpState.onTitlePrinted()) pw.println();
21899
21900                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21901                ipw.println();
21902                ipw.println("Loaded volumes:");
21903                ipw.increaseIndent();
21904                if (mLoadedVolumes.size() == 0) {
21905                    ipw.println("(none)");
21906                } else {
21907                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21908                        ipw.println(mLoadedVolumes.valueAt(i));
21909                    }
21910                }
21911                ipw.decreaseIndent();
21912            }
21913
21914            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21915                if (dumpState.onTitlePrinted()) pw.println();
21916                dumpDexoptStateLPr(pw, packageName);
21917            }
21918
21919            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21920                if (dumpState.onTitlePrinted()) pw.println();
21921                dumpCompilerStatsLPr(pw, packageName);
21922            }
21923
21924            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21925                if (dumpState.onTitlePrinted()) pw.println();
21926                mSettings.dumpReadMessagesLPr(pw, dumpState);
21927
21928                pw.println();
21929                pw.println("Package warning messages:");
21930                BufferedReader in = null;
21931                String line = null;
21932                try {
21933                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21934                    while ((line = in.readLine()) != null) {
21935                        if (line.contains("ignored: updated version")) continue;
21936                        pw.println(line);
21937                    }
21938                } catch (IOException ignored) {
21939                } finally {
21940                    IoUtils.closeQuietly(in);
21941                }
21942            }
21943
21944            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21945                BufferedReader in = null;
21946                String line = null;
21947                try {
21948                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21949                    while ((line = in.readLine()) != null) {
21950                        if (line.contains("ignored: updated version")) continue;
21951                        pw.print("msg,");
21952                        pw.println(line);
21953                    }
21954                } catch (IOException ignored) {
21955                } finally {
21956                    IoUtils.closeQuietly(in);
21957                }
21958            }
21959        }
21960
21961        // PackageInstaller should be called outside of mPackages lock
21962        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21963            // XXX should handle packageName != null by dumping only install data that
21964            // the given package is involved with.
21965            if (dumpState.onTitlePrinted()) pw.println();
21966            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21967        }
21968    }
21969
21970    private void dumpProto(FileDescriptor fd) {
21971        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21972
21973        synchronized (mPackages) {
21974            final long requiredVerifierPackageToken =
21975                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21976            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21977            proto.write(
21978                    PackageServiceDumpProto.PackageShortProto.UID,
21979                    getPackageUid(
21980                            mRequiredVerifierPackage,
21981                            MATCH_DEBUG_TRIAGED_MISSING,
21982                            UserHandle.USER_SYSTEM));
21983            proto.end(requiredVerifierPackageToken);
21984
21985            if (mIntentFilterVerifierComponent != null) {
21986                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21987                final long verifierPackageToken =
21988                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21989                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21990                proto.write(
21991                        PackageServiceDumpProto.PackageShortProto.UID,
21992                        getPackageUid(
21993                                verifierPackageName,
21994                                MATCH_DEBUG_TRIAGED_MISSING,
21995                                UserHandle.USER_SYSTEM));
21996                proto.end(verifierPackageToken);
21997            }
21998
21999            dumpSharedLibrariesProto(proto);
22000            dumpFeaturesProto(proto);
22001            mSettings.dumpPackagesProto(proto);
22002            mSettings.dumpSharedUsersProto(proto);
22003            dumpMessagesProto(proto);
22004        }
22005        proto.flush();
22006    }
22007
22008    private void dumpMessagesProto(ProtoOutputStream proto) {
22009        BufferedReader in = null;
22010        String line = null;
22011        try {
22012            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22013            while ((line = in.readLine()) != null) {
22014                if (line.contains("ignored: updated version")) continue;
22015                proto.write(PackageServiceDumpProto.MESSAGES, line);
22016            }
22017        } catch (IOException ignored) {
22018        } finally {
22019            IoUtils.closeQuietly(in);
22020        }
22021    }
22022
22023    private void dumpFeaturesProto(ProtoOutputStream proto) {
22024        synchronized (mAvailableFeatures) {
22025            final int count = mAvailableFeatures.size();
22026            for (int i = 0; i < count; i++) {
22027                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22028                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22029                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22030                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22031                proto.end(featureToken);
22032            }
22033        }
22034    }
22035
22036    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22037        final int count = mSharedLibraries.size();
22038        for (int i = 0; i < count; i++) {
22039            final String libName = mSharedLibraries.keyAt(i);
22040            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22041            if (versionedLib == null) {
22042                continue;
22043            }
22044            final int versionCount = versionedLib.size();
22045            for (int j = 0; j < versionCount; j++) {
22046                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22047                final long sharedLibraryToken =
22048                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22049                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22050                final boolean isJar = (libEntry.path != null);
22051                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22052                if (isJar) {
22053                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22054                } else {
22055                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22056                }
22057                proto.end(sharedLibraryToken);
22058            }
22059        }
22060    }
22061
22062    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22063        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22064        ipw.println();
22065        ipw.println("Dexopt state:");
22066        ipw.increaseIndent();
22067        Collection<PackageParser.Package> packages = null;
22068        if (packageName != null) {
22069            PackageParser.Package targetPackage = mPackages.get(packageName);
22070            if (targetPackage != null) {
22071                packages = Collections.singletonList(targetPackage);
22072            } else {
22073                ipw.println("Unable to find package: " + packageName);
22074                return;
22075            }
22076        } else {
22077            packages = mPackages.values();
22078        }
22079
22080        for (PackageParser.Package pkg : packages) {
22081            ipw.println("[" + pkg.packageName + "]");
22082            ipw.increaseIndent();
22083            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22084                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22085            ipw.decreaseIndent();
22086        }
22087    }
22088
22089    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22090        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22091        ipw.println();
22092        ipw.println("Compiler stats:");
22093        ipw.increaseIndent();
22094        Collection<PackageParser.Package> packages = null;
22095        if (packageName != null) {
22096            PackageParser.Package targetPackage = mPackages.get(packageName);
22097            if (targetPackage != null) {
22098                packages = Collections.singletonList(targetPackage);
22099            } else {
22100                ipw.println("Unable to find package: " + packageName);
22101                return;
22102            }
22103        } else {
22104            packages = mPackages.values();
22105        }
22106
22107        for (PackageParser.Package pkg : packages) {
22108            ipw.println("[" + pkg.packageName + "]");
22109            ipw.increaseIndent();
22110
22111            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22112            if (stats == null) {
22113                ipw.println("(No recorded stats)");
22114            } else {
22115                stats.dump(ipw);
22116            }
22117            ipw.decreaseIndent();
22118        }
22119    }
22120
22121    private String dumpDomainString(String packageName) {
22122        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22123                .getList();
22124        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22125
22126        ArraySet<String> result = new ArraySet<>();
22127        if (iviList.size() > 0) {
22128            for (IntentFilterVerificationInfo ivi : iviList) {
22129                for (String host : ivi.getDomains()) {
22130                    result.add(host);
22131                }
22132            }
22133        }
22134        if (filters != null && filters.size() > 0) {
22135            for (IntentFilter filter : filters) {
22136                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22137                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22138                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22139                    result.addAll(filter.getHostsList());
22140                }
22141            }
22142        }
22143
22144        StringBuilder sb = new StringBuilder(result.size() * 16);
22145        for (String domain : result) {
22146            if (sb.length() > 0) sb.append(" ");
22147            sb.append(domain);
22148        }
22149        return sb.toString();
22150    }
22151
22152    // ------- apps on sdcard specific code -------
22153    static final boolean DEBUG_SD_INSTALL = false;
22154
22155    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22156
22157    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22158
22159    private boolean mMediaMounted = false;
22160
22161    static String getEncryptKey() {
22162        try {
22163            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22164                    SD_ENCRYPTION_KEYSTORE_NAME);
22165            if (sdEncKey == null) {
22166                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22167                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22168                if (sdEncKey == null) {
22169                    Slog.e(TAG, "Failed to create encryption keys");
22170                    return null;
22171                }
22172            }
22173            return sdEncKey;
22174        } catch (NoSuchAlgorithmException nsae) {
22175            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22176            return null;
22177        } catch (IOException ioe) {
22178            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22179            return null;
22180        }
22181    }
22182
22183    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22184            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22185        final int size = infos.size();
22186        final String[] packageNames = new String[size];
22187        final int[] packageUids = new int[size];
22188        for (int i = 0; i < size; i++) {
22189            final ApplicationInfo info = infos.get(i);
22190            packageNames[i] = info.packageName;
22191            packageUids[i] = info.uid;
22192        }
22193        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22194                finishedReceiver);
22195    }
22196
22197    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22198            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22199        sendResourcesChangedBroadcast(mediaStatus, replacing,
22200                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22201    }
22202
22203    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22204            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22205        int size = pkgList.length;
22206        if (size > 0) {
22207            // Send broadcasts here
22208            Bundle extras = new Bundle();
22209            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22210            if (uidArr != null) {
22211                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22212            }
22213            if (replacing) {
22214                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22215            }
22216            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22217                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22218            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22219        }
22220    }
22221
22222    private void loadPrivatePackages(final VolumeInfo vol) {
22223        mHandler.post(new Runnable() {
22224            @Override
22225            public void run() {
22226                loadPrivatePackagesInner(vol);
22227            }
22228        });
22229    }
22230
22231    private void loadPrivatePackagesInner(VolumeInfo vol) {
22232        final String volumeUuid = vol.fsUuid;
22233        if (TextUtils.isEmpty(volumeUuid)) {
22234            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22235            return;
22236        }
22237
22238        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22239        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22240        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22241
22242        final VersionInfo ver;
22243        final List<PackageSetting> packages;
22244        synchronized (mPackages) {
22245            ver = mSettings.findOrCreateVersion(volumeUuid);
22246            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22247        }
22248
22249        for (PackageSetting ps : packages) {
22250            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22251            synchronized (mInstallLock) {
22252                final PackageParser.Package pkg;
22253                try {
22254                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22255                    loaded.add(pkg.applicationInfo);
22256
22257                } catch (PackageManagerException e) {
22258                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22259                }
22260
22261                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22262                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22263                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22264                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22265                }
22266            }
22267        }
22268
22269        // Reconcile app data for all started/unlocked users
22270        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22271        final UserManager um = mContext.getSystemService(UserManager.class);
22272        UserManagerInternal umInternal = getUserManagerInternal();
22273        for (UserInfo user : um.getUsers()) {
22274            final int flags;
22275            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22276                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22277            } else if (umInternal.isUserRunning(user.id)) {
22278                flags = StorageManager.FLAG_STORAGE_DE;
22279            } else {
22280                continue;
22281            }
22282
22283            try {
22284                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22285                synchronized (mInstallLock) {
22286                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22287                }
22288            } catch (IllegalStateException e) {
22289                // Device was probably ejected, and we'll process that event momentarily
22290                Slog.w(TAG, "Failed to prepare storage: " + e);
22291            }
22292        }
22293
22294        synchronized (mPackages) {
22295            int updateFlags = UPDATE_PERMISSIONS_ALL;
22296            if (ver.sdkVersion != mSdkVersion) {
22297                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22298                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22299                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22300            }
22301            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22302
22303            // Yay, everything is now upgraded
22304            ver.forceCurrent();
22305
22306            mSettings.writeLPr();
22307        }
22308
22309        for (PackageFreezer freezer : freezers) {
22310            freezer.close();
22311        }
22312
22313        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22314        sendResourcesChangedBroadcast(true, false, loaded, null);
22315        mLoadedVolumes.add(vol.getId());
22316    }
22317
22318    private void unloadPrivatePackages(final VolumeInfo vol) {
22319        mHandler.post(new Runnable() {
22320            @Override
22321            public void run() {
22322                unloadPrivatePackagesInner(vol);
22323            }
22324        });
22325    }
22326
22327    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22328        final String volumeUuid = vol.fsUuid;
22329        if (TextUtils.isEmpty(volumeUuid)) {
22330            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22331            return;
22332        }
22333
22334        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22335        synchronized (mInstallLock) {
22336        synchronized (mPackages) {
22337            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22338            for (PackageSetting ps : packages) {
22339                if (ps.pkg == null) continue;
22340
22341                final ApplicationInfo info = ps.pkg.applicationInfo;
22342                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22343                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22344
22345                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22346                        "unloadPrivatePackagesInner")) {
22347                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22348                            false, null)) {
22349                        unloaded.add(info);
22350                    } else {
22351                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22352                    }
22353                }
22354
22355                // Try very hard to release any references to this package
22356                // so we don't risk the system server being killed due to
22357                // open FDs
22358                AttributeCache.instance().removePackage(ps.name);
22359            }
22360
22361            mSettings.writeLPr();
22362        }
22363        }
22364
22365        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22366        sendResourcesChangedBroadcast(false, false, unloaded, null);
22367        mLoadedVolumes.remove(vol.getId());
22368
22369        // Try very hard to release any references to this path so we don't risk
22370        // the system server being killed due to open FDs
22371        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22372
22373        for (int i = 0; i < 3; i++) {
22374            System.gc();
22375            System.runFinalization();
22376        }
22377    }
22378
22379    private void assertPackageKnown(String volumeUuid, String packageName)
22380            throws PackageManagerException {
22381        synchronized (mPackages) {
22382            // Normalize package name to handle renamed packages
22383            packageName = normalizePackageNameLPr(packageName);
22384
22385            final PackageSetting ps = mSettings.mPackages.get(packageName);
22386            if (ps == null) {
22387                throw new PackageManagerException("Package " + packageName + " is unknown");
22388            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22389                throw new PackageManagerException(
22390                        "Package " + packageName + " found on unknown volume " + volumeUuid
22391                                + "; expected volume " + ps.volumeUuid);
22392            }
22393        }
22394    }
22395
22396    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22397            throws PackageManagerException {
22398        synchronized (mPackages) {
22399            // Normalize package name to handle renamed packages
22400            packageName = normalizePackageNameLPr(packageName);
22401
22402            final PackageSetting ps = mSettings.mPackages.get(packageName);
22403            if (ps == null) {
22404                throw new PackageManagerException("Package " + packageName + " is unknown");
22405            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22406                throw new PackageManagerException(
22407                        "Package " + packageName + " found on unknown volume " + volumeUuid
22408                                + "; expected volume " + ps.volumeUuid);
22409            } else if (!ps.getInstalled(userId)) {
22410                throw new PackageManagerException(
22411                        "Package " + packageName + " not installed for user " + userId);
22412            }
22413        }
22414    }
22415
22416    private List<String> collectAbsoluteCodePaths() {
22417        synchronized (mPackages) {
22418            List<String> codePaths = new ArrayList<>();
22419            final int packageCount = mSettings.mPackages.size();
22420            for (int i = 0; i < packageCount; i++) {
22421                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22422                codePaths.add(ps.codePath.getAbsolutePath());
22423            }
22424            return codePaths;
22425        }
22426    }
22427
22428    /**
22429     * Examine all apps present on given mounted volume, and destroy apps that
22430     * aren't expected, either due to uninstallation or reinstallation on
22431     * another volume.
22432     */
22433    private void reconcileApps(String volumeUuid) {
22434        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22435        List<File> filesToDelete = null;
22436
22437        final File[] files = FileUtils.listFilesOrEmpty(
22438                Environment.getDataAppDirectory(volumeUuid));
22439        for (File file : files) {
22440            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22441                    && !PackageInstallerService.isStageName(file.getName());
22442            if (!isPackage) {
22443                // Ignore entries which are not packages
22444                continue;
22445            }
22446
22447            String absolutePath = file.getAbsolutePath();
22448
22449            boolean pathValid = false;
22450            final int absoluteCodePathCount = absoluteCodePaths.size();
22451            for (int i = 0; i < absoluteCodePathCount; i++) {
22452                String absoluteCodePath = absoluteCodePaths.get(i);
22453                if (absolutePath.startsWith(absoluteCodePath)) {
22454                    pathValid = true;
22455                    break;
22456                }
22457            }
22458
22459            if (!pathValid) {
22460                if (filesToDelete == null) {
22461                    filesToDelete = new ArrayList<>();
22462                }
22463                filesToDelete.add(file);
22464            }
22465        }
22466
22467        if (filesToDelete != null) {
22468            final int fileToDeleteCount = filesToDelete.size();
22469            for (int i = 0; i < fileToDeleteCount; i++) {
22470                File fileToDelete = filesToDelete.get(i);
22471                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22472                synchronized (mInstallLock) {
22473                    removeCodePathLI(fileToDelete);
22474                }
22475            }
22476        }
22477    }
22478
22479    /**
22480     * Reconcile all app data for the given user.
22481     * <p>
22482     * Verifies that directories exist and that ownership and labeling is
22483     * correct for all installed apps on all mounted volumes.
22484     */
22485    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22486        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22487        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22488            final String volumeUuid = vol.getFsUuid();
22489            synchronized (mInstallLock) {
22490                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22491            }
22492        }
22493    }
22494
22495    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22496            boolean migrateAppData) {
22497        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22498    }
22499
22500    /**
22501     * Reconcile all app data on given mounted volume.
22502     * <p>
22503     * Destroys app data that isn't expected, either due to uninstallation or
22504     * reinstallation on another volume.
22505     * <p>
22506     * Verifies that directories exist and that ownership and labeling is
22507     * correct for all installed apps.
22508     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22509     */
22510    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22511            boolean migrateAppData, boolean onlyCoreApps) {
22512        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22513                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22514        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22515
22516        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22517        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22518
22519        // First look for stale data that doesn't belong, and check if things
22520        // have changed since we did our last restorecon
22521        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22522            if (StorageManager.isFileEncryptedNativeOrEmulated()
22523                    && !StorageManager.isUserKeyUnlocked(userId)) {
22524                throw new RuntimeException(
22525                        "Yikes, someone asked us to reconcile CE storage while " + userId
22526                                + " was still locked; this would have caused massive data loss!");
22527            }
22528
22529            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22530            for (File file : files) {
22531                final String packageName = file.getName();
22532                try {
22533                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22534                } catch (PackageManagerException e) {
22535                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22536                    try {
22537                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22538                                StorageManager.FLAG_STORAGE_CE, 0);
22539                    } catch (InstallerException e2) {
22540                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22541                    }
22542                }
22543            }
22544        }
22545        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22546            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22547            for (File file : files) {
22548                final String packageName = file.getName();
22549                try {
22550                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22551                } catch (PackageManagerException e) {
22552                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22553                    try {
22554                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22555                                StorageManager.FLAG_STORAGE_DE, 0);
22556                    } catch (InstallerException e2) {
22557                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22558                    }
22559                }
22560            }
22561        }
22562
22563        // Ensure that data directories are ready to roll for all packages
22564        // installed for this volume and user
22565        final List<PackageSetting> packages;
22566        synchronized (mPackages) {
22567            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22568        }
22569        int preparedCount = 0;
22570        for (PackageSetting ps : packages) {
22571            final String packageName = ps.name;
22572            if (ps.pkg == null) {
22573                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22574                // TODO: might be due to legacy ASEC apps; we should circle back
22575                // and reconcile again once they're scanned
22576                continue;
22577            }
22578            // Skip non-core apps if requested
22579            if (onlyCoreApps && !ps.pkg.coreApp) {
22580                result.add(packageName);
22581                continue;
22582            }
22583
22584            if (ps.getInstalled(userId)) {
22585                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22586                preparedCount++;
22587            }
22588        }
22589
22590        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22591        return result;
22592    }
22593
22594    /**
22595     * Prepare app data for the given app just after it was installed or
22596     * upgraded. This method carefully only touches users that it's installed
22597     * for, and it forces a restorecon to handle any seinfo changes.
22598     * <p>
22599     * Verifies that directories exist and that ownership and labeling is
22600     * correct for all installed apps. If there is an ownership mismatch, it
22601     * will try recovering system apps by wiping data; third-party app data is
22602     * left intact.
22603     * <p>
22604     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22605     */
22606    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22607        final PackageSetting ps;
22608        synchronized (mPackages) {
22609            ps = mSettings.mPackages.get(pkg.packageName);
22610            mSettings.writeKernelMappingLPr(ps);
22611        }
22612
22613        final UserManager um = mContext.getSystemService(UserManager.class);
22614        UserManagerInternal umInternal = getUserManagerInternal();
22615        for (UserInfo user : um.getUsers()) {
22616            final int flags;
22617            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22618                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22619            } else if (umInternal.isUserRunning(user.id)) {
22620                flags = StorageManager.FLAG_STORAGE_DE;
22621            } else {
22622                continue;
22623            }
22624
22625            if (ps.getInstalled(user.id)) {
22626                // TODO: when user data is locked, mark that we're still dirty
22627                prepareAppDataLIF(pkg, user.id, flags);
22628            }
22629        }
22630    }
22631
22632    /**
22633     * Prepare app data for the given app.
22634     * <p>
22635     * Verifies that directories exist and that ownership and labeling is
22636     * correct for all installed apps. If there is an ownership mismatch, this
22637     * will try recovering system apps by wiping data; third-party app data is
22638     * left intact.
22639     */
22640    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22641        if (pkg == null) {
22642            Slog.wtf(TAG, "Package was null!", new Throwable());
22643            return;
22644        }
22645        prepareAppDataLeafLIF(pkg, userId, flags);
22646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22647        for (int i = 0; i < childCount; i++) {
22648            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22649        }
22650    }
22651
22652    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22653            boolean maybeMigrateAppData) {
22654        prepareAppDataLIF(pkg, userId, flags);
22655
22656        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22657            // We may have just shuffled around app data directories, so
22658            // prepare them one more time
22659            prepareAppDataLIF(pkg, userId, flags);
22660        }
22661    }
22662
22663    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22664        if (DEBUG_APP_DATA) {
22665            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22666                    + Integer.toHexString(flags));
22667        }
22668
22669        final String volumeUuid = pkg.volumeUuid;
22670        final String packageName = pkg.packageName;
22671        final ApplicationInfo app = pkg.applicationInfo;
22672        final int appId = UserHandle.getAppId(app.uid);
22673
22674        Preconditions.checkNotNull(app.seInfo);
22675
22676        long ceDataInode = -1;
22677        try {
22678            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22679                    appId, app.seInfo, app.targetSdkVersion);
22680        } catch (InstallerException e) {
22681            if (app.isSystemApp()) {
22682                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22683                        + ", but trying to recover: " + e);
22684                destroyAppDataLeafLIF(pkg, userId, flags);
22685                try {
22686                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22687                            appId, app.seInfo, app.targetSdkVersion);
22688                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22689                } catch (InstallerException e2) {
22690                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22691                }
22692            } else {
22693                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22694            }
22695        }
22696
22697        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22698            // TODO: mark this structure as dirty so we persist it!
22699            synchronized (mPackages) {
22700                final PackageSetting ps = mSettings.mPackages.get(packageName);
22701                if (ps != null) {
22702                    ps.setCeDataInode(ceDataInode, userId);
22703                }
22704            }
22705        }
22706
22707        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22708    }
22709
22710    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22711        if (pkg == null) {
22712            Slog.wtf(TAG, "Package was null!", new Throwable());
22713            return;
22714        }
22715        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22716        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22717        for (int i = 0; i < childCount; i++) {
22718            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22719        }
22720    }
22721
22722    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22723        final String volumeUuid = pkg.volumeUuid;
22724        final String packageName = pkg.packageName;
22725        final ApplicationInfo app = pkg.applicationInfo;
22726
22727        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22728            // Create a native library symlink only if we have native libraries
22729            // and if the native libraries are 32 bit libraries. We do not provide
22730            // this symlink for 64 bit libraries.
22731            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22732                final String nativeLibPath = app.nativeLibraryDir;
22733                try {
22734                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22735                            nativeLibPath, userId);
22736                } catch (InstallerException e) {
22737                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22738                }
22739            }
22740        }
22741    }
22742
22743    /**
22744     * For system apps on non-FBE devices, this method migrates any existing
22745     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22746     * requested by the app.
22747     */
22748    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22749        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22750                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22751            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22752                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22753            try {
22754                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22755                        storageTarget);
22756            } catch (InstallerException e) {
22757                logCriticalInfo(Log.WARN,
22758                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22759            }
22760            return true;
22761        } else {
22762            return false;
22763        }
22764    }
22765
22766    public PackageFreezer freezePackage(String packageName, String killReason) {
22767        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22768    }
22769
22770    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22771        return new PackageFreezer(packageName, userId, killReason);
22772    }
22773
22774    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22775            String killReason) {
22776        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22777    }
22778
22779    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22780            String killReason) {
22781        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22782            return new PackageFreezer();
22783        } else {
22784            return freezePackage(packageName, userId, killReason);
22785        }
22786    }
22787
22788    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22789            String killReason) {
22790        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22791    }
22792
22793    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22794            String killReason) {
22795        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22796            return new PackageFreezer();
22797        } else {
22798            return freezePackage(packageName, userId, killReason);
22799        }
22800    }
22801
22802    /**
22803     * Class that freezes and kills the given package upon creation, and
22804     * unfreezes it upon closing. This is typically used when doing surgery on
22805     * app code/data to prevent the app from running while you're working.
22806     */
22807    private class PackageFreezer implements AutoCloseable {
22808        private final String mPackageName;
22809        private final PackageFreezer[] mChildren;
22810
22811        private final boolean mWeFroze;
22812
22813        private final AtomicBoolean mClosed = new AtomicBoolean();
22814        private final CloseGuard mCloseGuard = CloseGuard.get();
22815
22816        /**
22817         * Create and return a stub freezer that doesn't actually do anything,
22818         * typically used when someone requested
22819         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22820         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22821         */
22822        public PackageFreezer() {
22823            mPackageName = null;
22824            mChildren = null;
22825            mWeFroze = false;
22826            mCloseGuard.open("close");
22827        }
22828
22829        public PackageFreezer(String packageName, int userId, String killReason) {
22830            synchronized (mPackages) {
22831                mPackageName = packageName;
22832                mWeFroze = mFrozenPackages.add(mPackageName);
22833
22834                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22835                if (ps != null) {
22836                    killApplication(ps.name, ps.appId, userId, killReason);
22837                }
22838
22839                final PackageParser.Package p = mPackages.get(packageName);
22840                if (p != null && p.childPackages != null) {
22841                    final int N = p.childPackages.size();
22842                    mChildren = new PackageFreezer[N];
22843                    for (int i = 0; i < N; i++) {
22844                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22845                                userId, killReason);
22846                    }
22847                } else {
22848                    mChildren = null;
22849                }
22850            }
22851            mCloseGuard.open("close");
22852        }
22853
22854        @Override
22855        protected void finalize() throws Throwable {
22856            try {
22857                if (mCloseGuard != null) {
22858                    mCloseGuard.warnIfOpen();
22859                }
22860
22861                close();
22862            } finally {
22863                super.finalize();
22864            }
22865        }
22866
22867        @Override
22868        public void close() {
22869            mCloseGuard.close();
22870            if (mClosed.compareAndSet(false, true)) {
22871                synchronized (mPackages) {
22872                    if (mWeFroze) {
22873                        mFrozenPackages.remove(mPackageName);
22874                    }
22875
22876                    if (mChildren != null) {
22877                        for (PackageFreezer freezer : mChildren) {
22878                            freezer.close();
22879                        }
22880                    }
22881                }
22882            }
22883        }
22884    }
22885
22886    /**
22887     * Verify that given package is currently frozen.
22888     */
22889    private void checkPackageFrozen(String packageName) {
22890        synchronized (mPackages) {
22891            if (!mFrozenPackages.contains(packageName)) {
22892                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22893            }
22894        }
22895    }
22896
22897    @Override
22898    public int movePackage(final String packageName, final String volumeUuid) {
22899        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22900
22901        final int callingUid = Binder.getCallingUid();
22902        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22903        final int moveId = mNextMoveId.getAndIncrement();
22904        mHandler.post(new Runnable() {
22905            @Override
22906            public void run() {
22907                try {
22908                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22909                } catch (PackageManagerException e) {
22910                    Slog.w(TAG, "Failed to move " + packageName, e);
22911                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22912                }
22913            }
22914        });
22915        return moveId;
22916    }
22917
22918    private void movePackageInternal(final String packageName, final String volumeUuid,
22919            final int moveId, final int callingUid, UserHandle user)
22920                    throws PackageManagerException {
22921        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22922        final PackageManager pm = mContext.getPackageManager();
22923
22924        final boolean currentAsec;
22925        final String currentVolumeUuid;
22926        final File codeFile;
22927        final String installerPackageName;
22928        final String packageAbiOverride;
22929        final int appId;
22930        final String seinfo;
22931        final String label;
22932        final int targetSdkVersion;
22933        final PackageFreezer freezer;
22934        final int[] installedUserIds;
22935
22936        // reader
22937        synchronized (mPackages) {
22938            final PackageParser.Package pkg = mPackages.get(packageName);
22939            final PackageSetting ps = mSettings.mPackages.get(packageName);
22940            if (pkg == null
22941                    || ps == null
22942                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22943                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22944            }
22945            if (pkg.applicationInfo.isSystemApp()) {
22946                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22947                        "Cannot move system application");
22948            }
22949
22950            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22951            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22952                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22953            if (isInternalStorage && !allow3rdPartyOnInternal) {
22954                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22955                        "3rd party apps are not allowed on internal storage");
22956            }
22957
22958            if (pkg.applicationInfo.isExternalAsec()) {
22959                currentAsec = true;
22960                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22961            } else if (pkg.applicationInfo.isForwardLocked()) {
22962                currentAsec = true;
22963                currentVolumeUuid = "forward_locked";
22964            } else {
22965                currentAsec = false;
22966                currentVolumeUuid = ps.volumeUuid;
22967
22968                final File probe = new File(pkg.codePath);
22969                final File probeOat = new File(probe, "oat");
22970                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22971                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22972                            "Move only supported for modern cluster style installs");
22973                }
22974            }
22975
22976            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22977                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22978                        "Package already moved to " + volumeUuid);
22979            }
22980            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22981                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22982                        "Device admin cannot be moved");
22983            }
22984
22985            if (mFrozenPackages.contains(packageName)) {
22986                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22987                        "Failed to move already frozen package");
22988            }
22989
22990            codeFile = new File(pkg.codePath);
22991            installerPackageName = ps.installerPackageName;
22992            packageAbiOverride = ps.cpuAbiOverrideString;
22993            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22994            seinfo = pkg.applicationInfo.seInfo;
22995            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22996            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22997            freezer = freezePackage(packageName, "movePackageInternal");
22998            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22999        }
23000
23001        final Bundle extras = new Bundle();
23002        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23003        extras.putString(Intent.EXTRA_TITLE, label);
23004        mMoveCallbacks.notifyCreated(moveId, extras);
23005
23006        int installFlags;
23007        final boolean moveCompleteApp;
23008        final File measurePath;
23009
23010        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23011            installFlags = INSTALL_INTERNAL;
23012            moveCompleteApp = !currentAsec;
23013            measurePath = Environment.getDataAppDirectory(volumeUuid);
23014        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23015            installFlags = INSTALL_EXTERNAL;
23016            moveCompleteApp = false;
23017            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23018        } else {
23019            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23020            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23021                    || !volume.isMountedWritable()) {
23022                freezer.close();
23023                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23024                        "Move location not mounted private volume");
23025            }
23026
23027            Preconditions.checkState(!currentAsec);
23028
23029            installFlags = INSTALL_INTERNAL;
23030            moveCompleteApp = true;
23031            measurePath = Environment.getDataAppDirectory(volumeUuid);
23032        }
23033
23034        // If we're moving app data around, we need all the users unlocked
23035        if (moveCompleteApp) {
23036            for (int userId : installedUserIds) {
23037                if (StorageManager.isFileEncryptedNativeOrEmulated()
23038                        && !StorageManager.isUserKeyUnlocked(userId)) {
23039                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23040                            "User " + userId + " must be unlocked");
23041                }
23042            }
23043        }
23044
23045        final PackageStats stats = new PackageStats(null, -1);
23046        synchronized (mInstaller) {
23047            for (int userId : installedUserIds) {
23048                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23049                    freezer.close();
23050                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23051                            "Failed to measure package size");
23052                }
23053            }
23054        }
23055
23056        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23057                + stats.dataSize);
23058
23059        final long startFreeBytes = measurePath.getUsableSpace();
23060        final long sizeBytes;
23061        if (moveCompleteApp) {
23062            sizeBytes = stats.codeSize + stats.dataSize;
23063        } else {
23064            sizeBytes = stats.codeSize;
23065        }
23066
23067        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23068            freezer.close();
23069            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23070                    "Not enough free space to move");
23071        }
23072
23073        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23074
23075        final CountDownLatch installedLatch = new CountDownLatch(1);
23076        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23077            @Override
23078            public void onUserActionRequired(Intent intent) throws RemoteException {
23079                throw new IllegalStateException();
23080            }
23081
23082            @Override
23083            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23084                    Bundle extras) throws RemoteException {
23085                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23086                        + PackageManager.installStatusToString(returnCode, msg));
23087
23088                installedLatch.countDown();
23089                freezer.close();
23090
23091                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23092                switch (status) {
23093                    case PackageInstaller.STATUS_SUCCESS:
23094                        mMoveCallbacks.notifyStatusChanged(moveId,
23095                                PackageManager.MOVE_SUCCEEDED);
23096                        break;
23097                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23098                        mMoveCallbacks.notifyStatusChanged(moveId,
23099                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23100                        break;
23101                    default:
23102                        mMoveCallbacks.notifyStatusChanged(moveId,
23103                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23104                        break;
23105                }
23106            }
23107        };
23108
23109        final MoveInfo move;
23110        if (moveCompleteApp) {
23111            // Kick off a thread to report progress estimates
23112            new Thread() {
23113                @Override
23114                public void run() {
23115                    while (true) {
23116                        try {
23117                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23118                                break;
23119                            }
23120                        } catch (InterruptedException ignored) {
23121                        }
23122
23123                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23124                        final int progress = 10 + (int) MathUtils.constrain(
23125                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23126                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23127                    }
23128                }
23129            }.start();
23130
23131            final String dataAppName = codeFile.getName();
23132            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23133                    dataAppName, appId, seinfo, targetSdkVersion);
23134        } else {
23135            move = null;
23136        }
23137
23138        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23139
23140        final Message msg = mHandler.obtainMessage(INIT_COPY);
23141        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23142        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23143                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23144                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23145                PackageManager.INSTALL_REASON_UNKNOWN);
23146        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23147        msg.obj = params;
23148
23149        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23150                System.identityHashCode(msg.obj));
23151        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23152                System.identityHashCode(msg.obj));
23153
23154        mHandler.sendMessage(msg);
23155    }
23156
23157    @Override
23158    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23159        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23160
23161        final int realMoveId = mNextMoveId.getAndIncrement();
23162        final Bundle extras = new Bundle();
23163        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23164        mMoveCallbacks.notifyCreated(realMoveId, extras);
23165
23166        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23167            @Override
23168            public void onCreated(int moveId, Bundle extras) {
23169                // Ignored
23170            }
23171
23172            @Override
23173            public void onStatusChanged(int moveId, int status, long estMillis) {
23174                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23175            }
23176        };
23177
23178        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23179        storage.setPrimaryStorageUuid(volumeUuid, callback);
23180        return realMoveId;
23181    }
23182
23183    @Override
23184    public int getMoveStatus(int moveId) {
23185        mContext.enforceCallingOrSelfPermission(
23186                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23187        return mMoveCallbacks.mLastStatus.get(moveId);
23188    }
23189
23190    @Override
23191    public void registerMoveCallback(IPackageMoveObserver callback) {
23192        mContext.enforceCallingOrSelfPermission(
23193                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23194        mMoveCallbacks.register(callback);
23195    }
23196
23197    @Override
23198    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23199        mContext.enforceCallingOrSelfPermission(
23200                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23201        mMoveCallbacks.unregister(callback);
23202    }
23203
23204    @Override
23205    public boolean setInstallLocation(int loc) {
23206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23207                null);
23208        if (getInstallLocation() == loc) {
23209            return true;
23210        }
23211        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23212                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23213            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23214                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23215            return true;
23216        }
23217        return false;
23218   }
23219
23220    @Override
23221    public int getInstallLocation() {
23222        // allow instant app access
23223        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23224                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23225                PackageHelper.APP_INSTALL_AUTO);
23226    }
23227
23228    /** Called by UserManagerService */
23229    void cleanUpUser(UserManagerService userManager, int userHandle) {
23230        synchronized (mPackages) {
23231            mDirtyUsers.remove(userHandle);
23232            mUserNeedsBadging.delete(userHandle);
23233            mSettings.removeUserLPw(userHandle);
23234            mPendingBroadcasts.remove(userHandle);
23235            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23236            removeUnusedPackagesLPw(userManager, userHandle);
23237        }
23238    }
23239
23240    /**
23241     * We're removing userHandle and would like to remove any downloaded packages
23242     * that are no longer in use by any other user.
23243     * @param userHandle the user being removed
23244     */
23245    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23246        final boolean DEBUG_CLEAN_APKS = false;
23247        int [] users = userManager.getUserIds();
23248        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23249        while (psit.hasNext()) {
23250            PackageSetting ps = psit.next();
23251            if (ps.pkg == null) {
23252                continue;
23253            }
23254            final String packageName = ps.pkg.packageName;
23255            // Skip over if system app
23256            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23257                continue;
23258            }
23259            if (DEBUG_CLEAN_APKS) {
23260                Slog.i(TAG, "Checking package " + packageName);
23261            }
23262            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23263            if (keep) {
23264                if (DEBUG_CLEAN_APKS) {
23265                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23266                }
23267            } else {
23268                for (int i = 0; i < users.length; i++) {
23269                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23270                        keep = true;
23271                        if (DEBUG_CLEAN_APKS) {
23272                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23273                                    + users[i]);
23274                        }
23275                        break;
23276                    }
23277                }
23278            }
23279            if (!keep) {
23280                if (DEBUG_CLEAN_APKS) {
23281                    Slog.i(TAG, "  Removing package " + packageName);
23282                }
23283                mHandler.post(new Runnable() {
23284                    public void run() {
23285                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23286                                userHandle, 0);
23287                    } //end run
23288                });
23289            }
23290        }
23291    }
23292
23293    /** Called by UserManagerService */
23294    void createNewUser(int userId, String[] disallowedPackages) {
23295        synchronized (mInstallLock) {
23296            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23297        }
23298        synchronized (mPackages) {
23299            scheduleWritePackageRestrictionsLocked(userId);
23300            scheduleWritePackageListLocked(userId);
23301            applyFactoryDefaultBrowserLPw(userId);
23302            primeDomainVerificationsLPw(userId);
23303        }
23304    }
23305
23306    void onNewUserCreated(final int userId) {
23307        synchronized(mPackages) {
23308            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23309        }
23310        // If permission review for legacy apps is required, we represent
23311        // dagerous permissions for such apps as always granted runtime
23312        // permissions to keep per user flag state whether review is needed.
23313        // Hence, if a new user is added we have to propagate dangerous
23314        // permission grants for these legacy apps.
23315        if (mPermissionReviewRequired) {
23316            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23317                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23318        }
23319    }
23320
23321    @Override
23322    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23323        mContext.enforceCallingOrSelfPermission(
23324                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23325                "Only package verification agents can read the verifier device identity");
23326
23327        synchronized (mPackages) {
23328            return mSettings.getVerifierDeviceIdentityLPw();
23329        }
23330    }
23331
23332    @Override
23333    public void setPermissionEnforced(String permission, boolean enforced) {
23334        // TODO: Now that we no longer change GID for storage, this should to away.
23335        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23336                "setPermissionEnforced");
23337        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23338            synchronized (mPackages) {
23339                if (mSettings.mReadExternalStorageEnforced == null
23340                        || mSettings.mReadExternalStorageEnforced != enforced) {
23341                    mSettings.mReadExternalStorageEnforced =
23342                            enforced ? Boolean.TRUE : Boolean.FALSE;
23343                    mSettings.writeLPr();
23344                }
23345            }
23346            // kill any non-foreground processes so we restart them and
23347            // grant/revoke the GID.
23348            final IActivityManager am = ActivityManager.getService();
23349            if (am != null) {
23350                final long token = Binder.clearCallingIdentity();
23351                try {
23352                    am.killProcessesBelowForeground("setPermissionEnforcement");
23353                } catch (RemoteException e) {
23354                } finally {
23355                    Binder.restoreCallingIdentity(token);
23356                }
23357            }
23358        } else {
23359            throw new IllegalArgumentException("No selective enforcement for " + permission);
23360        }
23361    }
23362
23363    @Override
23364    @Deprecated
23365    public boolean isPermissionEnforced(String permission) {
23366        // allow instant applications
23367        return true;
23368    }
23369
23370    @Override
23371    public boolean isStorageLow() {
23372        // allow instant applications
23373        final long token = Binder.clearCallingIdentity();
23374        try {
23375            final DeviceStorageMonitorInternal
23376                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23377            if (dsm != null) {
23378                return dsm.isMemoryLow();
23379            } else {
23380                return false;
23381            }
23382        } finally {
23383            Binder.restoreCallingIdentity(token);
23384        }
23385    }
23386
23387    @Override
23388    public IPackageInstaller getPackageInstaller() {
23389        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23390            return null;
23391        }
23392        return mInstallerService;
23393    }
23394
23395    private boolean userNeedsBadging(int userId) {
23396        int index = mUserNeedsBadging.indexOfKey(userId);
23397        if (index < 0) {
23398            final UserInfo userInfo;
23399            final long token = Binder.clearCallingIdentity();
23400            try {
23401                userInfo = sUserManager.getUserInfo(userId);
23402            } finally {
23403                Binder.restoreCallingIdentity(token);
23404            }
23405            final boolean b;
23406            if (userInfo != null && userInfo.isManagedProfile()) {
23407                b = true;
23408            } else {
23409                b = false;
23410            }
23411            mUserNeedsBadging.put(userId, b);
23412            return b;
23413        }
23414        return mUserNeedsBadging.valueAt(index);
23415    }
23416
23417    @Override
23418    public KeySet getKeySetByAlias(String packageName, String alias) {
23419        if (packageName == null || alias == null) {
23420            return null;
23421        }
23422        synchronized(mPackages) {
23423            final PackageParser.Package pkg = mPackages.get(packageName);
23424            if (pkg == null) {
23425                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23426                throw new IllegalArgumentException("Unknown package: " + packageName);
23427            }
23428            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23429            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23430                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23431                throw new IllegalArgumentException("Unknown package: " + packageName);
23432            }
23433            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23434            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23435        }
23436    }
23437
23438    @Override
23439    public KeySet getSigningKeySet(String packageName) {
23440        if (packageName == null) {
23441            return null;
23442        }
23443        synchronized(mPackages) {
23444            final int callingUid = Binder.getCallingUid();
23445            final int callingUserId = UserHandle.getUserId(callingUid);
23446            final PackageParser.Package pkg = mPackages.get(packageName);
23447            if (pkg == null) {
23448                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23449                throw new IllegalArgumentException("Unknown package: " + packageName);
23450            }
23451            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23452            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23453                // filter and pretend the package doesn't exist
23454                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23455                        + ", uid:" + callingUid);
23456                throw new IllegalArgumentException("Unknown package: " + packageName);
23457            }
23458            if (pkg.applicationInfo.uid != callingUid
23459                    && Process.SYSTEM_UID != callingUid) {
23460                throw new SecurityException("May not access signing KeySet of other apps.");
23461            }
23462            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23463            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23464        }
23465    }
23466
23467    @Override
23468    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23469        final int callingUid = Binder.getCallingUid();
23470        if (getInstantAppPackageName(callingUid) != null) {
23471            return false;
23472        }
23473        if (packageName == null || ks == null) {
23474            return false;
23475        }
23476        synchronized(mPackages) {
23477            final PackageParser.Package pkg = mPackages.get(packageName);
23478            if (pkg == null
23479                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23480                            UserHandle.getUserId(callingUid))) {
23481                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23482                throw new IllegalArgumentException("Unknown package: " + packageName);
23483            }
23484            IBinder ksh = ks.getToken();
23485            if (ksh instanceof KeySetHandle) {
23486                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23487                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23488            }
23489            return false;
23490        }
23491    }
23492
23493    @Override
23494    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23495        final int callingUid = Binder.getCallingUid();
23496        if (getInstantAppPackageName(callingUid) != null) {
23497            return false;
23498        }
23499        if (packageName == null || ks == null) {
23500            return false;
23501        }
23502        synchronized(mPackages) {
23503            final PackageParser.Package pkg = mPackages.get(packageName);
23504            if (pkg == null
23505                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23506                            UserHandle.getUserId(callingUid))) {
23507                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23508                throw new IllegalArgumentException("Unknown package: " + packageName);
23509            }
23510            IBinder ksh = ks.getToken();
23511            if (ksh instanceof KeySetHandle) {
23512                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23513                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23514            }
23515            return false;
23516        }
23517    }
23518
23519    private void deletePackageIfUnusedLPr(final String packageName) {
23520        PackageSetting ps = mSettings.mPackages.get(packageName);
23521        if (ps == null) {
23522            return;
23523        }
23524        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23525            // TODO Implement atomic delete if package is unused
23526            // It is currently possible that the package will be deleted even if it is installed
23527            // after this method returns.
23528            mHandler.post(new Runnable() {
23529                public void run() {
23530                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23531                            0, PackageManager.DELETE_ALL_USERS);
23532                }
23533            });
23534        }
23535    }
23536
23537    /**
23538     * Check and throw if the given before/after packages would be considered a
23539     * downgrade.
23540     */
23541    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23542            throws PackageManagerException {
23543        if (after.versionCode < before.mVersionCode) {
23544            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23545                    "Update version code " + after.versionCode + " is older than current "
23546                    + before.mVersionCode);
23547        } else if (after.versionCode == before.mVersionCode) {
23548            if (after.baseRevisionCode < before.baseRevisionCode) {
23549                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23550                        "Update base revision code " + after.baseRevisionCode
23551                        + " is older than current " + before.baseRevisionCode);
23552            }
23553
23554            if (!ArrayUtils.isEmpty(after.splitNames)) {
23555                for (int i = 0; i < after.splitNames.length; i++) {
23556                    final String splitName = after.splitNames[i];
23557                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23558                    if (j != -1) {
23559                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23560                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23561                                    "Update split " + splitName + " revision code "
23562                                    + after.splitRevisionCodes[i] + " is older than current "
23563                                    + before.splitRevisionCodes[j]);
23564                        }
23565                    }
23566                }
23567            }
23568        }
23569    }
23570
23571    private static class MoveCallbacks extends Handler {
23572        private static final int MSG_CREATED = 1;
23573        private static final int MSG_STATUS_CHANGED = 2;
23574
23575        private final RemoteCallbackList<IPackageMoveObserver>
23576                mCallbacks = new RemoteCallbackList<>();
23577
23578        private final SparseIntArray mLastStatus = new SparseIntArray();
23579
23580        public MoveCallbacks(Looper looper) {
23581            super(looper);
23582        }
23583
23584        public void register(IPackageMoveObserver callback) {
23585            mCallbacks.register(callback);
23586        }
23587
23588        public void unregister(IPackageMoveObserver callback) {
23589            mCallbacks.unregister(callback);
23590        }
23591
23592        @Override
23593        public void handleMessage(Message msg) {
23594            final SomeArgs args = (SomeArgs) msg.obj;
23595            final int n = mCallbacks.beginBroadcast();
23596            for (int i = 0; i < n; i++) {
23597                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23598                try {
23599                    invokeCallback(callback, msg.what, args);
23600                } catch (RemoteException ignored) {
23601                }
23602            }
23603            mCallbacks.finishBroadcast();
23604            args.recycle();
23605        }
23606
23607        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23608                throws RemoteException {
23609            switch (what) {
23610                case MSG_CREATED: {
23611                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23612                    break;
23613                }
23614                case MSG_STATUS_CHANGED: {
23615                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23616                    break;
23617                }
23618            }
23619        }
23620
23621        private void notifyCreated(int moveId, Bundle extras) {
23622            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23623
23624            final SomeArgs args = SomeArgs.obtain();
23625            args.argi1 = moveId;
23626            args.arg2 = extras;
23627            obtainMessage(MSG_CREATED, args).sendToTarget();
23628        }
23629
23630        private void notifyStatusChanged(int moveId, int status) {
23631            notifyStatusChanged(moveId, status, -1);
23632        }
23633
23634        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23635            Slog.v(TAG, "Move " + moveId + " status " + status);
23636
23637            final SomeArgs args = SomeArgs.obtain();
23638            args.argi1 = moveId;
23639            args.argi2 = status;
23640            args.arg3 = estMillis;
23641            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23642
23643            synchronized (mLastStatus) {
23644                mLastStatus.put(moveId, status);
23645            }
23646        }
23647    }
23648
23649    private final static class OnPermissionChangeListeners extends Handler {
23650        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23651
23652        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23653                new RemoteCallbackList<>();
23654
23655        public OnPermissionChangeListeners(Looper looper) {
23656            super(looper);
23657        }
23658
23659        @Override
23660        public void handleMessage(Message msg) {
23661            switch (msg.what) {
23662                case MSG_ON_PERMISSIONS_CHANGED: {
23663                    final int uid = msg.arg1;
23664                    handleOnPermissionsChanged(uid);
23665                } break;
23666            }
23667        }
23668
23669        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23670            mPermissionListeners.register(listener);
23671
23672        }
23673
23674        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23675            mPermissionListeners.unregister(listener);
23676        }
23677
23678        public void onPermissionsChanged(int uid) {
23679            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23680                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23681            }
23682        }
23683
23684        private void handleOnPermissionsChanged(int uid) {
23685            final int count = mPermissionListeners.beginBroadcast();
23686            try {
23687                for (int i = 0; i < count; i++) {
23688                    IOnPermissionsChangeListener callback = mPermissionListeners
23689                            .getBroadcastItem(i);
23690                    try {
23691                        callback.onPermissionsChanged(uid);
23692                    } catch (RemoteException e) {
23693                        Log.e(TAG, "Permission listener is dead", e);
23694                    }
23695                }
23696            } finally {
23697                mPermissionListeners.finishBroadcast();
23698            }
23699        }
23700    }
23701
23702    private class PackageManagerNative extends IPackageManagerNative.Stub {
23703        @Override
23704        public String[] getNamesForUids(int[] uids) throws RemoteException {
23705            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23706            // massage results so they can be parsed by the native binder
23707            for (int i = results.length - 1; i >= 0; --i) {
23708                if (results[i] == null) {
23709                    results[i] = "";
23710                }
23711            }
23712            return results;
23713        }
23714
23715        // NB: this differentiates between preloads and sideloads
23716        @Override
23717        public String getInstallerForPackage(String packageName) throws RemoteException {
23718            final String installerName = getInstallerPackageName(packageName);
23719            if (!TextUtils.isEmpty(installerName)) {
23720                return installerName;
23721            }
23722            // differentiate between preload and sideload
23723            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23724            ApplicationInfo appInfo = getApplicationInfo(packageName,
23725                                    /*flags*/ 0,
23726                                    /*userId*/ callingUser);
23727            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23728                return "preload";
23729            }
23730            return "";
23731        }
23732
23733        @Override
23734        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23735            try {
23736                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23737                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23738                if (pInfo != null) {
23739                    return pInfo.versionCode;
23740                }
23741            } catch (Exception e) {
23742            }
23743            return 0;
23744        }
23745    }
23746
23747    private class PackageManagerInternalImpl extends PackageManagerInternal {
23748        @Override
23749        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23750                int flagValues, int userId) {
23751            PackageManagerService.this.updatePermissionFlags(
23752                    permName, packageName, flagMask, flagValues, userId);
23753        }
23754
23755        @Override
23756        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23757            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23758        }
23759
23760        @Override
23761        public Object enforcePermissionTreeTEMP(String permName, int callingUid) {
23762            synchronized (mPackages) {
23763                return BasePermission.enforcePermissionTreeLP(
23764                        mSettings.mPermissionTrees, permName, callingUid);
23765            }
23766        }
23767        @Override
23768        public boolean isInstantApp(String packageName, int userId) {
23769            return PackageManagerService.this.isInstantApp(packageName, userId);
23770        }
23771
23772        @Override
23773        public String getInstantAppPackageName(int uid) {
23774            return PackageManagerService.this.getInstantAppPackageName(uid);
23775        }
23776
23777        @Override
23778        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23779            synchronized (mPackages) {
23780                return PackageManagerService.this.filterAppAccessLPr(
23781                        (PackageSetting) pkg.mExtras, callingUid, userId);
23782            }
23783        }
23784
23785        @Override
23786        public PackageParser.Package getPackage(String packageName) {
23787            synchronized (mPackages) {
23788                packageName = resolveInternalPackageNameLPr(
23789                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23790                return mPackages.get(packageName);
23791            }
23792        }
23793
23794        @Override
23795        public PackageParser.Package getDisabledPackage(String packageName) {
23796            synchronized (mPackages) {
23797                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23798                return (ps != null) ? ps.pkg : null;
23799            }
23800        }
23801
23802        @Override
23803        public String getKnownPackageName(int knownPackage, int userId) {
23804            switch(knownPackage) {
23805                case PackageManagerInternal.PACKAGE_BROWSER:
23806                    return getDefaultBrowserPackageName(userId);
23807                case PackageManagerInternal.PACKAGE_INSTALLER:
23808                    return mRequiredInstallerPackage;
23809                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23810                    return mSetupWizardPackage;
23811                case PackageManagerInternal.PACKAGE_SYSTEM:
23812                    return "android";
23813                case PackageManagerInternal.PACKAGE_VERIFIER:
23814                    return mRequiredVerifierPackage;
23815            }
23816            return null;
23817        }
23818
23819        @Override
23820        public boolean isResolveActivityComponent(ComponentInfo component) {
23821            return mResolveActivity.packageName.equals(component.packageName)
23822                    && mResolveActivity.name.equals(component.name);
23823        }
23824
23825        @Override
23826        public void setLocationPackagesProvider(PackagesProvider provider) {
23827            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23828        }
23829
23830        @Override
23831        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23832            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23833        }
23834
23835        @Override
23836        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23837            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23838        }
23839
23840        @Override
23841        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23842            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23843        }
23844
23845        @Override
23846        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23847            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23848        }
23849
23850        @Override
23851        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23852            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23853        }
23854
23855        @Override
23856        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23857            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23858        }
23859
23860        @Override
23861        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23862            synchronized (mPackages) {
23863                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23864            }
23865            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23866        }
23867
23868        @Override
23869        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23870            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23871                    packageName, userId);
23872        }
23873
23874        @Override
23875        public void setKeepUninstalledPackages(final List<String> packageList) {
23876            Preconditions.checkNotNull(packageList);
23877            List<String> removedFromList = null;
23878            synchronized (mPackages) {
23879                if (mKeepUninstalledPackages != null) {
23880                    final int packagesCount = mKeepUninstalledPackages.size();
23881                    for (int i = 0; i < packagesCount; i++) {
23882                        String oldPackage = mKeepUninstalledPackages.get(i);
23883                        if (packageList != null && packageList.contains(oldPackage)) {
23884                            continue;
23885                        }
23886                        if (removedFromList == null) {
23887                            removedFromList = new ArrayList<>();
23888                        }
23889                        removedFromList.add(oldPackage);
23890                    }
23891                }
23892                mKeepUninstalledPackages = new ArrayList<>(packageList);
23893                if (removedFromList != null) {
23894                    final int removedCount = removedFromList.size();
23895                    for (int i = 0; i < removedCount; i++) {
23896                        deletePackageIfUnusedLPr(removedFromList.get(i));
23897                    }
23898                }
23899            }
23900        }
23901
23902        @Override
23903        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23904            synchronized (mPackages) {
23905                // If we do not support permission review, done.
23906                if (!mPermissionReviewRequired) {
23907                    return false;
23908                }
23909
23910                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23911                if (packageSetting == null) {
23912                    return false;
23913                }
23914
23915                // Permission review applies only to apps not supporting the new permission model.
23916                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23917                    return false;
23918                }
23919
23920                // Legacy apps have the permission and get user consent on launch.
23921                PermissionsState permissionsState = packageSetting.getPermissionsState();
23922                return permissionsState.isPermissionReviewRequired(userId);
23923            }
23924        }
23925
23926        @Override
23927        public PackageInfo getPackageInfo(
23928                String packageName, int flags, int filterCallingUid, int userId) {
23929            return PackageManagerService.this
23930                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23931                            flags, filterCallingUid, userId);
23932        }
23933
23934        @Override
23935        public ApplicationInfo getApplicationInfo(
23936                String packageName, int flags, int filterCallingUid, int userId) {
23937            return PackageManagerService.this
23938                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23939        }
23940
23941        @Override
23942        public ActivityInfo getActivityInfo(
23943                ComponentName component, int flags, int filterCallingUid, int userId) {
23944            return PackageManagerService.this
23945                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23946        }
23947
23948        @Override
23949        public List<ResolveInfo> queryIntentActivities(
23950                Intent intent, int flags, int filterCallingUid, int userId) {
23951            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23952            return PackageManagerService.this
23953                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23954                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23955        }
23956
23957        @Override
23958        public List<ResolveInfo> queryIntentServices(
23959                Intent intent, int flags, int callingUid, int userId) {
23960            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23961            return PackageManagerService.this
23962                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23963                            false);
23964        }
23965
23966        @Override
23967        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23968                int userId) {
23969            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23970        }
23971
23972        @Override
23973        public void setDeviceAndProfileOwnerPackages(
23974                int deviceOwnerUserId, String deviceOwnerPackage,
23975                SparseArray<String> profileOwnerPackages) {
23976            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23977                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23978        }
23979
23980        @Override
23981        public boolean isPackageDataProtected(int userId, String packageName) {
23982            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23983        }
23984
23985        @Override
23986        public boolean isPackageEphemeral(int userId, String packageName) {
23987            synchronized (mPackages) {
23988                final PackageSetting ps = mSettings.mPackages.get(packageName);
23989                return ps != null ? ps.getInstantApp(userId) : false;
23990            }
23991        }
23992
23993        @Override
23994        public boolean wasPackageEverLaunched(String packageName, int userId) {
23995            synchronized (mPackages) {
23996                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23997            }
23998        }
23999
24000        @Override
24001        public void grantRuntimePermission(String packageName, String permName, int userId,
24002                boolean overridePolicy) {
24003            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24004                    permName, packageName, overridePolicy, getCallingUid(), userId,
24005                    mPermissionCallback);
24006        }
24007
24008        @Override
24009        public void revokeRuntimePermission(String packageName, String permName, int userId,
24010                boolean overridePolicy) {
24011            mPermissionManager.revokeRuntimePermission(
24012                    permName, packageName, overridePolicy, getCallingUid(), userId,
24013                    mPermissionCallback);
24014        }
24015
24016        @Override
24017        public String getNameForUid(int uid) {
24018            return PackageManagerService.this.getNameForUid(uid);
24019        }
24020
24021        @Override
24022        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24023                Intent origIntent, String resolvedType, String callingPackage,
24024                Bundle verificationBundle, int userId) {
24025            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24026                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24027                    userId);
24028        }
24029
24030        @Override
24031        public void grantEphemeralAccess(int userId, Intent intent,
24032                int targetAppId, int ephemeralAppId) {
24033            synchronized (mPackages) {
24034                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24035                        targetAppId, ephemeralAppId);
24036            }
24037        }
24038
24039        @Override
24040        public boolean isInstantAppInstallerComponent(ComponentName component) {
24041            synchronized (mPackages) {
24042                return mInstantAppInstallerActivity != null
24043                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24044            }
24045        }
24046
24047        @Override
24048        public void pruneInstantApps() {
24049            mInstantAppRegistry.pruneInstantApps();
24050        }
24051
24052        @Override
24053        public String getSetupWizardPackageName() {
24054            return mSetupWizardPackage;
24055        }
24056
24057        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24058            if (policy != null) {
24059                mExternalSourcesPolicy = policy;
24060            }
24061        }
24062
24063        @Override
24064        public boolean isPackagePersistent(String packageName) {
24065            synchronized (mPackages) {
24066                PackageParser.Package pkg = mPackages.get(packageName);
24067                return pkg != null
24068                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24069                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24070                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24071                        : false;
24072            }
24073        }
24074
24075        @Override
24076        public List<PackageInfo> getOverlayPackages(int userId) {
24077            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24078            synchronized (mPackages) {
24079                for (PackageParser.Package p : mPackages.values()) {
24080                    if (p.mOverlayTarget != null) {
24081                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24082                        if (pkg != null) {
24083                            overlayPackages.add(pkg);
24084                        }
24085                    }
24086                }
24087            }
24088            return overlayPackages;
24089        }
24090
24091        @Override
24092        public List<String> getTargetPackageNames(int userId) {
24093            List<String> targetPackages = new ArrayList<>();
24094            synchronized (mPackages) {
24095                for (PackageParser.Package p : mPackages.values()) {
24096                    if (p.mOverlayTarget == null) {
24097                        targetPackages.add(p.packageName);
24098                    }
24099                }
24100            }
24101            return targetPackages;
24102        }
24103
24104        @Override
24105        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24106                @Nullable List<String> overlayPackageNames) {
24107            synchronized (mPackages) {
24108                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24109                    Slog.e(TAG, "failed to find package " + targetPackageName);
24110                    return false;
24111                }
24112                ArrayList<String> overlayPaths = null;
24113                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24114                    final int N = overlayPackageNames.size();
24115                    overlayPaths = new ArrayList<>(N);
24116                    for (int i = 0; i < N; i++) {
24117                        final String packageName = overlayPackageNames.get(i);
24118                        final PackageParser.Package pkg = mPackages.get(packageName);
24119                        if (pkg == null) {
24120                            Slog.e(TAG, "failed to find package " + packageName);
24121                            return false;
24122                        }
24123                        overlayPaths.add(pkg.baseCodePath);
24124                    }
24125                }
24126
24127                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24128                ps.setOverlayPaths(overlayPaths, userId);
24129                return true;
24130            }
24131        }
24132
24133        @Override
24134        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24135                int flags, int userId, boolean resolveForStart) {
24136            return resolveIntentInternal(
24137                    intent, resolvedType, flags, userId, resolveForStart);
24138        }
24139
24140        @Override
24141        public ResolveInfo resolveService(Intent intent, String resolvedType,
24142                int flags, int userId, int callingUid) {
24143            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24144        }
24145
24146        @Override
24147        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24148            return PackageManagerService.this.resolveContentProviderInternal(
24149                    name, flags, userId);
24150        }
24151
24152        @Override
24153        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24154            synchronized (mPackages) {
24155                mIsolatedOwners.put(isolatedUid, ownerUid);
24156            }
24157        }
24158
24159        @Override
24160        public void removeIsolatedUid(int isolatedUid) {
24161            synchronized (mPackages) {
24162                mIsolatedOwners.delete(isolatedUid);
24163            }
24164        }
24165
24166        @Override
24167        public int getUidTargetSdkVersion(int uid) {
24168            synchronized (mPackages) {
24169                return getUidTargetSdkVersionLockedLPr(uid);
24170            }
24171        }
24172
24173        @Override
24174        public boolean canAccessInstantApps(int callingUid, int userId) {
24175            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24176        }
24177
24178        @Override
24179        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24180            synchronized (mPackages) {
24181                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24182            }
24183        }
24184
24185        @Override
24186        public void notifyPackageUse(String packageName, int reason) {
24187            synchronized (mPackages) {
24188                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24189            }
24190        }
24191    }
24192
24193    @Override
24194    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24195        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24196        synchronized (mPackages) {
24197            final long identity = Binder.clearCallingIdentity();
24198            try {
24199                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24200                        packageNames, userId);
24201            } finally {
24202                Binder.restoreCallingIdentity(identity);
24203            }
24204        }
24205    }
24206
24207    @Override
24208    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24209        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24210        synchronized (mPackages) {
24211            final long identity = Binder.clearCallingIdentity();
24212            try {
24213                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24214                        packageNames, userId);
24215            } finally {
24216                Binder.restoreCallingIdentity(identity);
24217            }
24218        }
24219    }
24220
24221    private static void enforceSystemOrPhoneCaller(String tag) {
24222        int callingUid = Binder.getCallingUid();
24223        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24224            throw new SecurityException(
24225                    "Cannot call " + tag + " from UID " + callingUid);
24226        }
24227    }
24228
24229    boolean isHistoricalPackageUsageAvailable() {
24230        return mPackageUsage.isHistoricalPackageUsageAvailable();
24231    }
24232
24233    /**
24234     * Return a <b>copy</b> of the collection of packages known to the package manager.
24235     * @return A copy of the values of mPackages.
24236     */
24237    Collection<PackageParser.Package> getPackages() {
24238        synchronized (mPackages) {
24239            return new ArrayList<>(mPackages.values());
24240        }
24241    }
24242
24243    /**
24244     * Logs process start information (including base APK hash) to the security log.
24245     * @hide
24246     */
24247    @Override
24248    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24249            String apkFile, int pid) {
24250        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24251            return;
24252        }
24253        if (!SecurityLog.isLoggingEnabled()) {
24254            return;
24255        }
24256        Bundle data = new Bundle();
24257        data.putLong("startTimestamp", System.currentTimeMillis());
24258        data.putString("processName", processName);
24259        data.putInt("uid", uid);
24260        data.putString("seinfo", seinfo);
24261        data.putString("apkFile", apkFile);
24262        data.putInt("pid", pid);
24263        Message msg = mProcessLoggingHandler.obtainMessage(
24264                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24265        msg.setData(data);
24266        mProcessLoggingHandler.sendMessage(msg);
24267    }
24268
24269    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24270        return mCompilerStats.getPackageStats(pkgName);
24271    }
24272
24273    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24274        return getOrCreateCompilerPackageStats(pkg.packageName);
24275    }
24276
24277    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24278        return mCompilerStats.getOrCreatePackageStats(pkgName);
24279    }
24280
24281    public void deleteCompilerPackageStats(String pkgName) {
24282        mCompilerStats.deletePackageStats(pkgName);
24283    }
24284
24285    @Override
24286    public int getInstallReason(String packageName, int userId) {
24287        final int callingUid = Binder.getCallingUid();
24288        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24289                true /* requireFullPermission */, false /* checkShell */,
24290                "get install reason");
24291        synchronized (mPackages) {
24292            final PackageSetting ps = mSettings.mPackages.get(packageName);
24293            if (filterAppAccessLPr(ps, callingUid, userId)) {
24294                return PackageManager.INSTALL_REASON_UNKNOWN;
24295            }
24296            if (ps != null) {
24297                return ps.getInstallReason(userId);
24298            }
24299        }
24300        return PackageManager.INSTALL_REASON_UNKNOWN;
24301    }
24302
24303    @Override
24304    public boolean canRequestPackageInstalls(String packageName, int userId) {
24305        return canRequestPackageInstallsInternal(packageName, 0, userId,
24306                true /* throwIfPermNotDeclared*/);
24307    }
24308
24309    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24310            boolean throwIfPermNotDeclared) {
24311        int callingUid = Binder.getCallingUid();
24312        int uid = getPackageUid(packageName, 0, userId);
24313        if (callingUid != uid && callingUid != Process.ROOT_UID
24314                && callingUid != Process.SYSTEM_UID) {
24315            throw new SecurityException(
24316                    "Caller uid " + callingUid + " does not own package " + packageName);
24317        }
24318        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24319        if (info == null) {
24320            return false;
24321        }
24322        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24323            return false;
24324        }
24325        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24326        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24327        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24328            if (throwIfPermNotDeclared) {
24329                throw new SecurityException("Need to declare " + appOpPermission
24330                        + " to call this api");
24331            } else {
24332                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24333                return false;
24334            }
24335        }
24336        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24337            return false;
24338        }
24339        if (mExternalSourcesPolicy != null) {
24340            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24341            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24342                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24343            }
24344        }
24345        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24346    }
24347
24348    @Override
24349    public ComponentName getInstantAppResolverSettingsComponent() {
24350        return mInstantAppResolverSettingsComponent;
24351    }
24352
24353    @Override
24354    public ComponentName getInstantAppInstallerComponent() {
24355        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24356            return null;
24357        }
24358        return mInstantAppInstallerActivity == null
24359                ? null : mInstantAppInstallerActivity.getComponentName();
24360    }
24361
24362    @Override
24363    public String getInstantAppAndroidId(String packageName, int userId) {
24364        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24365                "getInstantAppAndroidId");
24366        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24367                true /* requireFullPermission */, false /* checkShell */,
24368                "getInstantAppAndroidId");
24369        // Make sure the target is an Instant App.
24370        if (!isInstantApp(packageName, userId)) {
24371            return null;
24372        }
24373        synchronized (mPackages) {
24374            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24375        }
24376    }
24377
24378    boolean canHaveOatDir(String packageName) {
24379        synchronized (mPackages) {
24380            PackageParser.Package p = mPackages.get(packageName);
24381            if (p == null) {
24382                return false;
24383            }
24384            return p.canHaveOatDir();
24385        }
24386    }
24387
24388    private String getOatDir(PackageParser.Package pkg) {
24389        if (!pkg.canHaveOatDir()) {
24390            return null;
24391        }
24392        File codePath = new File(pkg.codePath);
24393        if (codePath.isDirectory()) {
24394            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24395        }
24396        return null;
24397    }
24398
24399    void deleteOatArtifactsOfPackage(String packageName) {
24400        final String[] instructionSets;
24401        final List<String> codePaths;
24402        final String oatDir;
24403        final PackageParser.Package pkg;
24404        synchronized (mPackages) {
24405            pkg = mPackages.get(packageName);
24406        }
24407        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24408        codePaths = pkg.getAllCodePaths();
24409        oatDir = getOatDir(pkg);
24410
24411        for (String codePath : codePaths) {
24412            for (String isa : instructionSets) {
24413                try {
24414                    mInstaller.deleteOdex(codePath, isa, oatDir);
24415                } catch (InstallerException e) {
24416                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24417                }
24418            }
24419        }
24420    }
24421
24422    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24423        Set<String> unusedPackages = new HashSet<>();
24424        long currentTimeInMillis = System.currentTimeMillis();
24425        synchronized (mPackages) {
24426            for (PackageParser.Package pkg : mPackages.values()) {
24427                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24428                if (ps == null) {
24429                    continue;
24430                }
24431                PackageDexUsage.PackageUseInfo packageUseInfo =
24432                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24433                if (PackageManagerServiceUtils
24434                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24435                                downgradeTimeThresholdMillis, packageUseInfo,
24436                                pkg.getLatestPackageUseTimeInMills(),
24437                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24438                    unusedPackages.add(pkg.packageName);
24439                }
24440            }
24441        }
24442        return unusedPackages;
24443    }
24444}
24445
24446interface PackageSender {
24447    void sendPackageBroadcast(final String action, final String pkg,
24448        final Bundle extras, final int flags, final String targetPkg,
24449        final IIntentReceiver finishedReceiver, final int[] userIds);
24450    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24451        boolean includeStopped, int appId, int... userIds);
24452}
24453