PackageManagerService.java revision 3bc947266638b8d2c2e10a80d1e8eb9348b6dd8a
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.LinkedHashSet;
348import java.util.List;
349import java.util.Map;
350import java.util.Objects;
351import java.util.Set;
352import java.util.concurrent.CountDownLatch;
353import java.util.concurrent.Future;
354import java.util.concurrent.TimeUnit;
355import java.util.concurrent.atomic.AtomicBoolean;
356import java.util.concurrent.atomic.AtomicInteger;
357import java.util.zip.GZIPInputStream;
358
359/**
360 * Keep track of all those APKs everywhere.
361 * <p>
362 * Internally there are two important locks:
363 * <ul>
364 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
365 * and other related state. It is a fine-grained lock that should only be held
366 * momentarily, as it's one of the most contended locks in the system.
367 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
368 * operations typically involve heavy lifting of application data on disk. Since
369 * {@code installd} is single-threaded, and it's operations can often be slow,
370 * this lock should never be acquired while already holding {@link #mPackages}.
371 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
372 * holding {@link #mInstallLock}.
373 * </ul>
374 * Many internal methods rely on the caller to hold the appropriate locks, and
375 * this contract is expressed through method name suffixes:
376 * <ul>
377 * <li>fooLI(): the caller must hold {@link #mInstallLock}
378 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
379 * being modified must be frozen
380 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
381 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
382 * </ul>
383 * <p>
384 * Because this class is very central to the platform's security; please run all
385 * CTS and unit tests whenever making modifications:
386 *
387 * <pre>
388 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
389 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
390 * </pre>
391 */
392public class PackageManagerService extends IPackageManager.Stub
393        implements PackageSender {
394    static final String TAG = "PackageManager";
395    public static final boolean DEBUG_SETTINGS = false;
396    static final boolean DEBUG_PREFERRED = false;
397    static final boolean DEBUG_UPGRADE = false;
398    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
399    private static final boolean DEBUG_BACKUP = false;
400    private static final boolean DEBUG_INSTALL = false;
401    public static final boolean DEBUG_REMOVE = false;
402    private static final boolean DEBUG_BROADCASTS = false;
403    private static final boolean DEBUG_SHOW_INFO = false;
404    private static final boolean DEBUG_PACKAGE_INFO = false;
405    private static final boolean DEBUG_INTENT_MATCHING = false;
406    public static final boolean DEBUG_PACKAGE_SCANNING = false;
407    private static final boolean DEBUG_VERIFY = false;
408    private static final boolean DEBUG_FILTERS = false;
409    public static final boolean DEBUG_PERMISSIONS = false;
410    private static final boolean DEBUG_SHARED_LIBRARIES = false;
411    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
412
413    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
414    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
415    // user, but by default initialize to this.
416    public static final boolean DEBUG_DEXOPT = false;
417
418    private static final boolean DEBUG_ABI_SELECTION = false;
419    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
420    private static final boolean DEBUG_TRIAGED_MISSING = false;
421    private static final boolean DEBUG_APP_DATA = false;
422
423    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
424    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
425
426    private static final boolean HIDE_EPHEMERAL_APIS = false;
427
428    private static final boolean ENABLE_FREE_CACHE_V2 =
429            SystemProperties.getBoolean("fw.free_cache_v2", true);
430
431    private static final int RADIO_UID = Process.PHONE_UID;
432    private static final int LOG_UID = Process.LOG_UID;
433    private static final int NFC_UID = Process.NFC_UID;
434    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
435    private static final int SHELL_UID = Process.SHELL_UID;
436
437    // Suffix used during package installation when copying/moving
438    // package apks to install directory.
439    private static final String INSTALL_PACKAGE_SUFFIX = "-";
440
441    static final int SCAN_NO_DEX = 1<<1;
442    static final int SCAN_FORCE_DEX = 1<<2;
443    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
444    static final int SCAN_NEW_INSTALL = 1<<4;
445    static final int SCAN_UPDATE_TIME = 1<<5;
446    static final int SCAN_BOOTING = 1<<6;
447    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
448    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
449    static final int SCAN_REPLACING = 1<<9;
450    static final int SCAN_REQUIRE_KNOWN = 1<<10;
451    static final int SCAN_MOVE = 1<<11;
452    static final int SCAN_INITIAL = 1<<12;
453    static final int SCAN_CHECK_ONLY = 1<<13;
454    static final int SCAN_DONT_KILL_APP = 1<<14;
455    static final int SCAN_IGNORE_FROZEN = 1<<15;
456    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
457    static final int SCAN_AS_INSTANT_APP = 1<<17;
458    static final int SCAN_AS_FULL_APP = 1<<18;
459    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
460    /** Should not be with the scan flags */
461    static final int FLAGS_REMOVE_CHATTY = 1<<31;
462
463    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
464    /** Extension of the compressed packages */
465    private final static String COMPRESSED_EXTENSION = ".gz";
466    /** Suffix of stub packages on the system partition */
467    private final static String STUB_SUFFIX = "-Stub";
468
469    private static final int[] EMPTY_INT_ARRAY = new int[0];
470
471    private static final int TYPE_UNKNOWN = 0;
472    private static final int TYPE_ACTIVITY = 1;
473    private static final int TYPE_RECEIVER = 2;
474    private static final int TYPE_SERVICE = 3;
475    private static final int TYPE_PROVIDER = 4;
476    @IntDef(prefix = { "TYPE_" }, value = {
477            TYPE_UNKNOWN,
478            TYPE_ACTIVITY,
479            TYPE_RECEIVER,
480            TYPE_SERVICE,
481            TYPE_PROVIDER,
482    })
483    @Retention(RetentionPolicy.SOURCE)
484    public @interface ComponentType {}
485
486    /**
487     * Timeout (in milliseconds) after which the watchdog should declare that
488     * our handler thread is wedged.  The usual default for such things is one
489     * minute but we sometimes do very lengthy I/O operations on this thread,
490     * such as installing multi-gigabyte applications, so ours needs to be longer.
491     */
492    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
493
494    /**
495     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
496     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
497     * settings entry if available, otherwise we use the hardcoded default.  If it's been
498     * more than this long since the last fstrim, we force one during the boot sequence.
499     *
500     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
501     * one gets run at the next available charging+idle time.  This final mandatory
502     * no-fstrim check kicks in only of the other scheduling criteria is never met.
503     */
504    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
505
506    /**
507     * Whether verification is enabled by default.
508     */
509    private static final boolean DEFAULT_VERIFY_ENABLE = true;
510
511    /**
512     * The default maximum time to wait for the verification agent to return in
513     * milliseconds.
514     */
515    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
516
517    /**
518     * The default response for package verification timeout.
519     *
520     * This can be either PackageManager.VERIFICATION_ALLOW or
521     * PackageManager.VERIFICATION_REJECT.
522     */
523    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
524
525    static final String PLATFORM_PACKAGE_NAME = "android";
526
527    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
528
529    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
530            DEFAULT_CONTAINER_PACKAGE,
531            "com.android.defcontainer.DefaultContainerService");
532
533    private static final String KILL_APP_REASON_GIDS_CHANGED =
534            "permission grant or revoke changed gids";
535
536    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
537            "permissions revoked";
538
539    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
540
541    private static final String PACKAGE_SCHEME = "package";
542
543    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
544
545    /** Permission grant: not grant the permission. */
546    private static final int GRANT_DENIED = 1;
547
548    /** Permission grant: grant the permission as an install permission. */
549    private static final int GRANT_INSTALL = 2;
550
551    /** Permission grant: grant the permission as a runtime one. */
552    private static final int GRANT_RUNTIME = 3;
553
554    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
555    private static final int GRANT_UPGRADE = 4;
556
557    /** Canonical intent used to identify what counts as a "web browser" app */
558    private static final Intent sBrowserIntent;
559    static {
560        sBrowserIntent = new Intent();
561        sBrowserIntent.setAction(Intent.ACTION_VIEW);
562        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
563        sBrowserIntent.setData(Uri.parse("http:"));
564    }
565
566    /**
567     * The set of all protected actions [i.e. those actions for which a high priority
568     * intent filter is disallowed].
569     */
570    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
571    static {
572        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
574        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
575        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
576    }
577
578    // Compilation reasons.
579    public static final int REASON_FIRST_BOOT = 0;
580    public static final int REASON_BOOT = 1;
581    public static final int REASON_INSTALL = 2;
582    public static final int REASON_BACKGROUND_DEXOPT = 3;
583    public static final int REASON_AB_OTA = 4;
584    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
585    public static final int REASON_SHARED = 6;
586
587    public static final int REASON_LAST = REASON_SHARED;
588
589    /** All dangerous permission names in the same order as the events in MetricsEvent */
590    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
591            Manifest.permission.READ_CALENDAR,
592            Manifest.permission.WRITE_CALENDAR,
593            Manifest.permission.CAMERA,
594            Manifest.permission.READ_CONTACTS,
595            Manifest.permission.WRITE_CONTACTS,
596            Manifest.permission.GET_ACCOUNTS,
597            Manifest.permission.ACCESS_FINE_LOCATION,
598            Manifest.permission.ACCESS_COARSE_LOCATION,
599            Manifest.permission.RECORD_AUDIO,
600            Manifest.permission.READ_PHONE_STATE,
601            Manifest.permission.CALL_PHONE,
602            Manifest.permission.READ_CALL_LOG,
603            Manifest.permission.WRITE_CALL_LOG,
604            Manifest.permission.ADD_VOICEMAIL,
605            Manifest.permission.USE_SIP,
606            Manifest.permission.PROCESS_OUTGOING_CALLS,
607            Manifest.permission.READ_CELL_BROADCASTS,
608            Manifest.permission.BODY_SENSORS,
609            Manifest.permission.SEND_SMS,
610            Manifest.permission.RECEIVE_SMS,
611            Manifest.permission.READ_SMS,
612            Manifest.permission.RECEIVE_WAP_PUSH,
613            Manifest.permission.RECEIVE_MMS,
614            Manifest.permission.READ_EXTERNAL_STORAGE,
615            Manifest.permission.WRITE_EXTERNAL_STORAGE,
616            Manifest.permission.READ_PHONE_NUMBERS,
617            Manifest.permission.ANSWER_PHONE_CALLS);
618
619
620    /**
621     * Version number for the package parser cache. Increment this whenever the format or
622     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
623     */
624    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
625
626    /**
627     * Whether the package parser cache is enabled.
628     */
629    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
630
631    final ServiceThread mHandlerThread;
632
633    final PackageHandler mHandler;
634
635    private final ProcessLoggingHandler mProcessLoggingHandler;
636
637    /**
638     * Messages for {@link #mHandler} that need to wait for system ready before
639     * being dispatched.
640     */
641    private ArrayList<Message> mPostSystemReadyMessages;
642
643    final int mSdkVersion = Build.VERSION.SDK_INT;
644
645    final Context mContext;
646    final boolean mFactoryTest;
647    final boolean mOnlyCore;
648    final DisplayMetrics mMetrics;
649    final int mDefParseFlags;
650    final String[] mSeparateProcesses;
651    final boolean mIsUpgrade;
652    final boolean mIsPreNUpgrade;
653    final boolean mIsPreNMR1Upgrade;
654
655    // Have we told the Activity Manager to whitelist the default container service by uid yet?
656    @GuardedBy("mPackages")
657    boolean mDefaultContainerWhitelisted = false;
658
659    @GuardedBy("mPackages")
660    private boolean mDexOptDialogShown;
661
662    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
663    // LOCK HELD.  Can be called with mInstallLock held.
664    @GuardedBy("mInstallLock")
665    final Installer mInstaller;
666
667    /** Directory where installed third-party apps stored */
668    final File mAppInstallDir;
669
670    /**
671     * Directory to which applications installed internally have their
672     * 32 bit native libraries copied.
673     */
674    private File mAppLib32InstallDir;
675
676    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
677    // apps.
678    final File mDrmAppPrivateInstallDir;
679
680    // ----------------------------------------------------------------
681
682    // Lock for state used when installing and doing other long running
683    // operations.  Methods that must be called with this lock held have
684    // the suffix "LI".
685    final Object mInstallLock = new Object();
686
687    // ----------------------------------------------------------------
688
689    // Keys are String (package name), values are Package.  This also serves
690    // as the lock for the global state.  Methods that must be called with
691    // this lock held have the prefix "LP".
692    @GuardedBy("mPackages")
693    final ArrayMap<String, PackageParser.Package> mPackages =
694            new ArrayMap<String, PackageParser.Package>();
695
696    final ArrayMap<String, Set<String>> mKnownCodebase =
697            new ArrayMap<String, Set<String>>();
698
699    // Keys are isolated uids and values are the uid of the application
700    // that created the isolated proccess.
701    @GuardedBy("mPackages")
702    final SparseIntArray mIsolatedOwners = new SparseIntArray();
703
704    /**
705     * Tracks new system packages [received in an OTA] that we expect to
706     * find updated user-installed versions. Keys are package name, values
707     * are package location.
708     */
709    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
710    /**
711     * Tracks high priority intent filters for protected actions. During boot, certain
712     * filter actions are protected and should never be allowed to have a high priority
713     * intent filter for them. However, there is one, and only one exception -- the
714     * setup wizard. It must be able to define a high priority intent filter for these
715     * actions to ensure there are no escapes from the wizard. We need to delay processing
716     * of these during boot as we need to look at all of the system packages in order
717     * to know which component is the setup wizard.
718     */
719    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
720    /**
721     * Whether or not processing protected filters should be deferred.
722     */
723    private boolean mDeferProtectedFilters = true;
724
725    /**
726     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
727     */
728    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
729    /**
730     * Whether or not system app permissions should be promoted from install to runtime.
731     */
732    boolean mPromoteSystemApps;
733
734    @GuardedBy("mPackages")
735    final Settings mSettings;
736
737    /**
738     * Set of package names that are currently "frozen", which means active
739     * surgery is being done on the code/data for that package. The platform
740     * will refuse to launch frozen packages to avoid race conditions.
741     *
742     * @see PackageFreezer
743     */
744    @GuardedBy("mPackages")
745    final ArraySet<String> mFrozenPackages = new ArraySet<>();
746
747    final ProtectedPackages mProtectedPackages;
748
749    @GuardedBy("mLoadedVolumes")
750    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
751
752    boolean mFirstBoot;
753
754    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
755
756    @GuardedBy("mAvailableFeatures")
757    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
758
759    // If mac_permissions.xml was found for seinfo labeling.
760    boolean mFoundPolicyFile;
761
762    private final InstantAppRegistry mInstantAppRegistry;
763
764    @GuardedBy("mPackages")
765    int mChangedPackagesSequenceNumber;
766    /**
767     * List of changed [installed, removed or updated] packages.
768     * mapping from user id -> sequence number -> package name
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
772    /**
773     * The sequence number of the last change to a package.
774     * mapping from user id -> package name -> sequence number
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
778
779    class PackageParserCallback implements PackageParser.Callback {
780        @Override public final boolean hasFeature(String feature) {
781            return PackageManagerService.this.hasSystemFeature(feature, 0);
782        }
783
784        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
785                Collection<PackageParser.Package> allPackages, String targetPackageName) {
786            List<PackageParser.Package> overlayPackages = null;
787            for (PackageParser.Package p : allPackages) {
788                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
789                    if (overlayPackages == null) {
790                        overlayPackages = new ArrayList<PackageParser.Package>();
791                    }
792                    overlayPackages.add(p);
793                }
794            }
795            if (overlayPackages != null) {
796                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
797                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
798                        return p1.mOverlayPriority - p2.mOverlayPriority;
799                    }
800                };
801                Collections.sort(overlayPackages, cmp);
802            }
803            return overlayPackages;
804        }
805
806        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
807                String targetPackageName, String targetPath) {
808            if ("android".equals(targetPackageName)) {
809                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
810                // native AssetManager.
811                return null;
812            }
813            List<PackageParser.Package> overlayPackages =
814                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            synchronized (mPackages) {
851                return getStaticOverlayPathsLocked(
852                        mPackages.values(), targetPackageName, targetPath);
853            }
854        }
855
856        @Override public final String[] getOverlayApks(String targetPackageName) {
857            return getStaticOverlayPaths(targetPackageName, null);
858        }
859
860        @Override public final String[] getOverlayPaths(String targetPackageName,
861                String targetPath) {
862            return getStaticOverlayPaths(targetPackageName, targetPath);
863        }
864    }
865
866    class ParallelPackageParserCallback extends PackageParserCallback {
867        List<PackageParser.Package> mOverlayPackages = null;
868
869        void findStaticOverlayPackages() {
870            synchronized (mPackages) {
871                for (PackageParser.Package p : mPackages.values()) {
872                    if (p.mIsStaticOverlay) {
873                        if (mOverlayPackages == null) {
874                            mOverlayPackages = new ArrayList<PackageParser.Package>();
875                        }
876                        mOverlayPackages.add(p);
877                    }
878                }
879            }
880        }
881
882        @Override
883        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
884            // We can trust mOverlayPackages without holding mPackages because package uninstall
885            // can't happen while running parallel parsing.
886            // Moreover holding mPackages on each parsing thread causes dead-lock.
887            return mOverlayPackages == null ? null :
888                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
889        }
890    }
891
892    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
893    final ParallelPackageParserCallback mParallelPackageParserCallback =
894            new ParallelPackageParserCallback();
895
896    public static final class SharedLibraryEntry {
897        public final @Nullable String path;
898        public final @Nullable String apk;
899        public final @NonNull SharedLibraryInfo info;
900
901        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
902                String declaringPackageName, int declaringPackageVersionCode) {
903            path = _path;
904            apk = _apk;
905            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
906                    declaringPackageName, declaringPackageVersionCode), null);
907        }
908    }
909
910    // Currently known shared libraries.
911    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
913            new ArrayMap<>();
914
915    // All available activities, for your resolving pleasure.
916    final ActivityIntentResolver mActivities =
917            new ActivityIntentResolver();
918
919    // All available receivers, for your resolving pleasure.
920    final ActivityIntentResolver mReceivers =
921            new ActivityIntentResolver();
922
923    // All available services, for your resolving pleasure.
924    final ServiceIntentResolver mServices = new ServiceIntentResolver();
925
926    // All available providers, for your resolving pleasure.
927    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
928
929    // Mapping from provider base names (first directory in content URI codePath)
930    // to the provider information.
931    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
932            new ArrayMap<String, PackageParser.Provider>();
933
934    // Mapping from instrumentation class names to info about them.
935    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
936            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
937
938    // Packages whose data we have transfered into another package, thus
939    // should no longer exist.
940    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
941
942    // Broadcast actions that are only available to the system.
943    @GuardedBy("mProtectedBroadcasts")
944    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
945
946    /** List of packages waiting for verification. */
947    final SparseArray<PackageVerificationState> mPendingVerification
948            = new SparseArray<PackageVerificationState>();
949
950    final PackageInstallerService mInstallerService;
951
952    private final PackageDexOptimizer mPackageDexOptimizer;
953    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
954    // is used by other apps).
955    private final DexManager mDexManager;
956
957    private AtomicInteger mNextMoveId = new AtomicInteger();
958    private final MoveCallbacks mMoveCallbacks;
959
960    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
961
962    // Cache of users who need badging.
963    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
964
965    /** Token for keys in mPendingVerification. */
966    private int mPendingVerificationToken = 0;
967
968    volatile boolean mSystemReady;
969    volatile boolean mSafeMode;
970    volatile boolean mHasSystemUidErrors;
971    private volatile boolean mEphemeralAppsDisabled;
972
973    ApplicationInfo mAndroidApplication;
974    final ActivityInfo mResolveActivity = new ActivityInfo();
975    final ResolveInfo mResolveInfo = new ResolveInfo();
976    ComponentName mResolveComponentName;
977    PackageParser.Package mPlatformPackage;
978    ComponentName mCustomResolverComponentName;
979
980    boolean mResolverReplaced = false;
981
982    private final @Nullable ComponentName mIntentFilterVerifierComponent;
983    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
984
985    private int mIntentFilterVerificationToken = 0;
986
987    /** The service connection to the ephemeral resolver */
988    final EphemeralResolverConnection mInstantAppResolverConnection;
989    /** Component used to show resolver settings for Instant Apps */
990    final ComponentName mInstantAppResolverSettingsComponent;
991
992    /** Activity used to install instant applications */
993    ActivityInfo mInstantAppInstallerActivity;
994    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
995
996    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
997            = new SparseArray<IntentFilterVerificationState>();
998
999    // TODO remove this and go through mPermissonManager directly
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001    private final PermissionManagerInternal mPermissionManager;
1002
1003    // List of packages names to keep cached, even if they are uninstalled for all users
1004    private List<String> mKeepUninstalledPackages;
1005
1006    private UserManagerInternal mUserManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private ArraySet<String> mPrivappPermissionsViolations;
1013
1014    private Future<?> mPrepareAppDataFuture;
1015
1016    private static class IFVerificationParams {
1017        PackageParser.Package pkg;
1018        boolean replacing;
1019        int userId;
1020        int verifierUid;
1021
1022        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1023                int _userId, int _verifierUid) {
1024            pkg = _pkg;
1025            replacing = _replacing;
1026            userId = _userId;
1027            replacing = _replacing;
1028            verifierUid = _verifierUid;
1029        }
1030    }
1031
1032    private interface IntentFilterVerifier<T extends IntentFilter> {
1033        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1034                                               T filter, String packageName);
1035        void startVerifications(int userId);
1036        void receiveVerificationResponse(int verificationId);
1037    }
1038
1039    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1040        private Context mContext;
1041        private ComponentName mIntentFilterVerifierComponent;
1042        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1043
1044        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1045            mContext = context;
1046            mIntentFilterVerifierComponent = verifierComponent;
1047        }
1048
1049        private String getDefaultScheme() {
1050            return IntentFilter.SCHEME_HTTPS;
1051        }
1052
1053        @Override
1054        public void startVerifications(int userId) {
1055            // Launch verifications requests
1056            int count = mCurrentIntentFilterVerifications.size();
1057            for (int n=0; n<count; n++) {
1058                int verificationId = mCurrentIntentFilterVerifications.get(n);
1059                final IntentFilterVerificationState ivs =
1060                        mIntentFilterVerificationStates.get(verificationId);
1061
1062                String packageName = ivs.getPackageName();
1063
1064                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1065                final int filterCount = filters.size();
1066                ArraySet<String> domainsSet = new ArraySet<>();
1067                for (int m=0; m<filterCount; m++) {
1068                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1069                    domainsSet.addAll(filter.getHostsList());
1070                }
1071                synchronized (mPackages) {
1072                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1073                            packageName, domainsSet) != null) {
1074                        scheduleWriteSettingsLocked();
1075                    }
1076                }
1077                sendVerificationRequest(verificationId, ivs);
1078            }
1079            mCurrentIntentFilterVerifications.clear();
1080        }
1081
1082        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1083            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1086                    verificationId);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1089                    getDefaultScheme());
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1092                    ivs.getHostsString());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1095                    ivs.getPackageName());
1096            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1097            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1098
1099            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1100            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1101                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1102                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1103
1104            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1105            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1106                    "Sending IntentFilter verification broadcast");
1107        }
1108
1109        public void receiveVerificationResponse(int verificationId) {
1110            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1111
1112            final boolean verified = ivs.isVerified();
1113
1114            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1115            final int count = filters.size();
1116            if (DEBUG_DOMAIN_VERIFICATION) {
1117                Slog.i(TAG, "Received verification response " + verificationId
1118                        + " for " + count + " filters, verified=" + verified);
1119            }
1120            for (int n=0; n<count; n++) {
1121                PackageParser.ActivityIntentInfo filter = filters.get(n);
1122                filter.setVerified(verified);
1123
1124                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1125                        + " verified with result:" + verified + " and hosts:"
1126                        + ivs.getHostsString());
1127            }
1128
1129            mIntentFilterVerificationStates.remove(verificationId);
1130
1131            final String packageName = ivs.getPackageName();
1132            IntentFilterVerificationInfo ivi = null;
1133
1134            synchronized (mPackages) {
1135                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1136            }
1137            if (ivi == null) {
1138                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1139                        + verificationId + " packageName:" + packageName);
1140                return;
1141            }
1142            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1143                    "Updating IntentFilterVerificationInfo for package " + packageName
1144                            +" verificationId:" + verificationId);
1145
1146            synchronized (mPackages) {
1147                if (verified) {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1149                } else {
1150                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1151                }
1152                scheduleWriteSettingsLocked();
1153
1154                final int userId = ivs.getUserId();
1155                if (userId != UserHandle.USER_ALL) {
1156                    final int userStatus =
1157                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1158
1159                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1160                    boolean needUpdate = false;
1161
1162                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1163                    // already been set by the User thru the Disambiguation dialog
1164                    switch (userStatus) {
1165                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1166                            if (verified) {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1168                            } else {
1169                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1170                            }
1171                            needUpdate = true;
1172                            break;
1173
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                                needUpdate = true;
1178                            }
1179                            break;
1180
1181                        default:
1182                            // Nothing to do
1183                    }
1184
1185                    if (needUpdate) {
1186                        mSettings.updateIntentFilterVerificationStatusLPw(
1187                                packageName, updatedStatus, userId);
1188                        scheduleWritePackageRestrictionsLocked(userId);
1189                    }
1190                }
1191            }
1192        }
1193
1194        @Override
1195        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1196                    ActivityIntentInfo filter, String packageName) {
1197            if (!hasValidDomains(filter)) {
1198                return false;
1199            }
1200            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1201            if (ivs == null) {
1202                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1203                        packageName);
1204            }
1205            if (DEBUG_DOMAIN_VERIFICATION) {
1206                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1207            }
1208            ivs.addFilter(filter);
1209            return true;
1210        }
1211
1212        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1213                int userId, int verificationId, String packageName) {
1214            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1215                    verifierUid, userId, packageName);
1216            ivs.setPendingState();
1217            synchronized (mPackages) {
1218                mIntentFilterVerificationStates.append(verificationId, ivs);
1219                mCurrentIntentFilterVerifications.add(verificationId);
1220            }
1221            return ivs;
1222        }
1223    }
1224
1225    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1226        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1227                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1228                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1229    }
1230
1231    // Set of pending broadcasts for aggregating enable/disable of components.
1232    static class PendingPackageBroadcasts {
1233        // for each user id, a map of <package name -> components within that package>
1234        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1235
1236        public PendingPackageBroadcasts() {
1237            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1238        }
1239
1240        public ArrayList<String> get(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            return packages.get(packageName);
1243        }
1244
1245        public void put(int userId, String packageName, ArrayList<String> components) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            packages.put(packageName, components);
1248        }
1249
1250        public void remove(int userId, String packageName) {
1251            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1252            if (packages != null) {
1253                packages.remove(packageName);
1254            }
1255        }
1256
1257        public void remove(int userId) {
1258            mUidMap.remove(userId);
1259        }
1260
1261        public int userIdCount() {
1262            return mUidMap.size();
1263        }
1264
1265        public int userIdAt(int n) {
1266            return mUidMap.keyAt(n);
1267        }
1268
1269        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1270            return mUidMap.get(userId);
1271        }
1272
1273        public int size() {
1274            // total number of pending broadcast entries across all userIds
1275            int num = 0;
1276            for (int i = 0; i< mUidMap.size(); i++) {
1277                num += mUidMap.valueAt(i).size();
1278            }
1279            return num;
1280        }
1281
1282        public void clear() {
1283            mUidMap.clear();
1284        }
1285
1286        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1287            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1288            if (map == null) {
1289                map = new ArrayMap<String, ArrayList<String>>();
1290                mUidMap.put(userId, map);
1291            }
1292            return map;
1293        }
1294    }
1295    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1296
1297    // Service Connection to remote media container service to copy
1298    // package uri's from external media onto secure containers
1299    // or internal storage.
1300    private IMediaContainerService mContainerService = null;
1301
1302    static final int SEND_PENDING_BROADCAST = 1;
1303    static final int MCS_BOUND = 3;
1304    static final int END_COPY = 4;
1305    static final int INIT_COPY = 5;
1306    static final int MCS_UNBIND = 6;
1307    static final int START_CLEANING_PACKAGE = 7;
1308    static final int FIND_INSTALL_LOC = 8;
1309    static final int POST_INSTALL = 9;
1310    static final int MCS_RECONNECT = 10;
1311    static final int MCS_GIVE_UP = 11;
1312    static final int WRITE_SETTINGS = 13;
1313    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1314    static final int PACKAGE_VERIFIED = 15;
1315    static final int CHECK_PENDING_VERIFICATION = 16;
1316    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1317    static final int INTENT_FILTER_VERIFIED = 18;
1318    static final int WRITE_PACKAGE_LIST = 19;
1319    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1320
1321    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1322
1323    // Delay time in millisecs
1324    static final int BROADCAST_DELAY = 10 * 1000;
1325
1326    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1327            2 * 60 * 60 * 1000L; /* two hours */
1328
1329    static UserManagerService sUserManager;
1330
1331    // Stores a list of users whose package restrictions file needs to be updated
1332    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1333
1334    final private DefaultContainerConnection mDefContainerConn =
1335            new DefaultContainerConnection();
1336    class DefaultContainerConnection implements ServiceConnection {
1337        public void onServiceConnected(ComponentName name, IBinder service) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1339            final IMediaContainerService imcs = IMediaContainerService.Stub
1340                    .asInterface(Binder.allowBlocking(service));
1341            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1342        }
1343
1344        public void onServiceDisconnected(ComponentName name) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1346        }
1347    }
1348
1349    // Recordkeeping of restore-after-install operations that are currently in flight
1350    // between the Package Manager and the Backup Manager
1351    static class PostInstallData {
1352        public InstallArgs args;
1353        public PackageInstalledInfo res;
1354
1355        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1356            args = _a;
1357            res = _r;
1358        }
1359    }
1360
1361    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1362    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1363
1364    // XML tags for backup/restore of various bits of state
1365    private static final String TAG_PREFERRED_BACKUP = "pa";
1366    private static final String TAG_DEFAULT_APPS = "da";
1367    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1368
1369    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1370    private static final String TAG_ALL_GRANTS = "rt-grants";
1371    private static final String TAG_GRANT = "grant";
1372    private static final String ATTR_PACKAGE_NAME = "pkg";
1373
1374    private static final String TAG_PERMISSION = "perm";
1375    private static final String ATTR_PERMISSION_NAME = "name";
1376    private static final String ATTR_IS_GRANTED = "g";
1377    private static final String ATTR_USER_SET = "set";
1378    private static final String ATTR_USER_FIXED = "fixed";
1379    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1380
1381    // System/policy permission grants are not backed up
1382    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_POLICY_FIXED
1384            | FLAG_PERMISSION_SYSTEM_FIXED
1385            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1386
1387    // And we back up these user-adjusted states
1388    private static final int USER_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_USER_SET
1390            | FLAG_PERMISSION_USER_FIXED
1391            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1392
1393    final @Nullable String mRequiredVerifierPackage;
1394    final @NonNull String mRequiredInstallerPackage;
1395    final @NonNull String mRequiredUninstallerPackage;
1396    final @Nullable String mSetupWizardPackage;
1397    final @Nullable String mStorageManagerPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    final boolean mPermissionReviewRequired;
1402
1403    private final PackageUsage mPackageUsage = new PackageUsage();
1404    private final CompilerStats mCompilerStats = new CompilerStats();
1405
1406    class PackageHandler extends Handler {
1407        private boolean mBound = false;
1408        final ArrayList<HandlerParams> mPendingInstalls =
1409            new ArrayList<HandlerParams>();
1410
1411        private boolean connectToService() {
1412            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1413                    " DefaultContainerService");
1414            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1417                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                mBound = true;
1420                return true;
1421            }
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423            return false;
1424        }
1425
1426        private void disconnectService() {
1427            mContainerService = null;
1428            mBound = false;
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            mContext.unbindService(mDefContainerConn);
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432        }
1433
1434        PackageHandler(Looper looper) {
1435            super(looper);
1436        }
1437
1438        public void handleMessage(Message msg) {
1439            try {
1440                doHandleMessage(msg);
1441            } finally {
1442                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443            }
1444        }
1445
1446        void doHandleMessage(Message msg) {
1447            switch (msg.what) {
1448                case INIT_COPY: {
1449                    HandlerParams params = (HandlerParams) msg.obj;
1450                    int idx = mPendingInstalls.size();
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1452                    // If a bind was already initiated we dont really
1453                    // need to do anything. The pending install
1454                    // will be processed later on.
1455                    if (!mBound) {
1456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                System.identityHashCode(mHandler));
1458                        // If this is the only one pending we might
1459                        // have to bind to the service again.
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                            params.serviceError();
1463                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                    System.identityHashCode(mHandler));
1465                            if (params.traceMethod != null) {
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1467                                        params.traceCookie);
1468                            }
1469                            return;
1470                        } else {
1471                            // Once we bind to the service, the first
1472                            // pending request will be processed.
1473                            mPendingInstalls.add(idx, params);
1474                        }
1475                    } else {
1476                        mPendingInstalls.add(idx, params);
1477                        // Already bound to the service. Just make
1478                        // sure we trigger off processing the first request.
1479                        if (idx == 0) {
1480                            mHandler.sendEmptyMessage(MCS_BOUND);
1481                        }
1482                    }
1483                    break;
1484                }
1485                case MCS_BOUND: {
1486                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1487                    if (msg.obj != null) {
1488                        mContainerService = (IMediaContainerService) msg.obj;
1489                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1490                                System.identityHashCode(mHandler));
1491                    }
1492                    if (mContainerService == null) {
1493                        if (!mBound) {
1494                            // Something seriously wrong since we are not bound and we are not
1495                            // waiting for connection. Bail out.
1496                            Slog.e(TAG, "Cannot bind to media container service");
1497                            for (HandlerParams params : mPendingInstalls) {
1498                                // Indicate service bind error
1499                                params.serviceError();
1500                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                        System.identityHashCode(params));
1502                                if (params.traceMethod != null) {
1503                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1504                                            params.traceMethod, params.traceCookie);
1505                                }
1506                                return;
1507                            }
1508                            mPendingInstalls.clear();
1509                        } else {
1510                            Slog.w(TAG, "Waiting to connect to media container service");
1511                        }
1512                    } else if (mPendingInstalls.size() > 0) {
1513                        HandlerParams params = mPendingInstalls.get(0);
1514                        if (params != null) {
1515                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1516                                    System.identityHashCode(params));
1517                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1518                            if (params.startCopy()) {
1519                                // We are done...  look for more work or to
1520                                // go idle.
1521                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                        "Checking for more work or unbind...");
1523                                // Delete pending install
1524                                if (mPendingInstalls.size() > 0) {
1525                                    mPendingInstalls.remove(0);
1526                                }
1527                                if (mPendingInstalls.size() == 0) {
1528                                    if (mBound) {
1529                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                                "Posting delayed MCS_UNBIND");
1531                                        removeMessages(MCS_UNBIND);
1532                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1533                                        // Unbind after a little delay, to avoid
1534                                        // continual thrashing.
1535                                        sendMessageDelayed(ubmsg, 10000);
1536                                    }
1537                                } else {
1538                                    // There are more pending requests in queue.
1539                                    // Just post MCS_BOUND message to trigger processing
1540                                    // of next pending install.
1541                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                            "Posting MCS_BOUND for next work");
1543                                    mHandler.sendEmptyMessage(MCS_BOUND);
1544                                }
1545                            }
1546                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1547                        }
1548                    } else {
1549                        // Should never happen ideally.
1550                        Slog.w(TAG, "Empty queue");
1551                    }
1552                    break;
1553                }
1554                case MCS_RECONNECT: {
1555                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1556                    if (mPendingInstalls.size() > 0) {
1557                        if (mBound) {
1558                            disconnectService();
1559                        }
1560                        if (!connectToService()) {
1561                            Slog.e(TAG, "Failed to bind to media container service");
1562                            for (HandlerParams params : mPendingInstalls) {
1563                                // Indicate service bind error
1564                                params.serviceError();
1565                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                                        System.identityHashCode(params));
1567                            }
1568                            mPendingInstalls.clear();
1569                        }
1570                    }
1571                    break;
1572                }
1573                case MCS_UNBIND: {
1574                    // If there is no actual work left, then time to unbind.
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1576
1577                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1578                        if (mBound) {
1579                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1580
1581                            disconnectService();
1582                        }
1583                    } else if (mPendingInstalls.size() > 0) {
1584                        // There are more pending requests in queue.
1585                        // Just post MCS_BOUND message to trigger processing
1586                        // of next pending install.
1587                        mHandler.sendEmptyMessage(MCS_BOUND);
1588                    }
1589
1590                    break;
1591                }
1592                case MCS_GIVE_UP: {
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1594                    HandlerParams params = mPendingInstalls.remove(0);
1595                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1596                            System.identityHashCode(params));
1597                    break;
1598                }
1599                case SEND_PENDING_BROADCAST: {
1600                    String packages[];
1601                    ArrayList<String> components[];
1602                    int size = 0;
1603                    int uids[];
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        if (mPendingBroadcasts == null) {
1607                            return;
1608                        }
1609                        size = mPendingBroadcasts.size();
1610                        if (size <= 0) {
1611                            // Nothing to be done. Just return
1612                            return;
1613                        }
1614                        packages = new String[size];
1615                        components = new ArrayList[size];
1616                        uids = new int[size];
1617                        int i = 0;  // filling out the above arrays
1618
1619                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1620                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1621                            Iterator<Map.Entry<String, ArrayList<String>>> it
1622                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1623                                            .entrySet().iterator();
1624                            while (it.hasNext() && i < size) {
1625                                Map.Entry<String, ArrayList<String>> ent = it.next();
1626                                packages[i] = ent.getKey();
1627                                components[i] = ent.getValue();
1628                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1629                                uids[i] = (ps != null)
1630                                        ? UserHandle.getUid(packageUserId, ps.appId)
1631                                        : -1;
1632                                i++;
1633                            }
1634                        }
1635                        size = i;
1636                        mPendingBroadcasts.clear();
1637                    }
1638                    // Send broadcasts
1639                    for (int i = 0; i < size; i++) {
1640                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                    break;
1644                }
1645                case START_CLEANING_PACKAGE: {
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1647                    final String packageName = (String)msg.obj;
1648                    final int userId = msg.arg1;
1649                    final boolean andCode = msg.arg2 != 0;
1650                    synchronized (mPackages) {
1651                        if (userId == UserHandle.USER_ALL) {
1652                            int[] users = sUserManager.getUserIds();
1653                            for (int user : users) {
1654                                mSettings.addPackageToCleanLPw(
1655                                        new PackageCleanItem(user, packageName, andCode));
1656                            }
1657                        } else {
1658                            mSettings.addPackageToCleanLPw(
1659                                    new PackageCleanItem(userId, packageName, andCode));
1660                        }
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    startCleaningPackages();
1664                } break;
1665                case POST_INSTALL: {
1666                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1667
1668                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1669                    final boolean didRestore = (msg.arg2 != 0);
1670                    mRunningInstalls.delete(msg.arg1);
1671
1672                    if (data != null) {
1673                        InstallArgs args = data.args;
1674                        PackageInstalledInfo parentRes = data.res;
1675
1676                        final boolean grantPermissions = (args.installFlags
1677                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1678                        final boolean killApp = (args.installFlags
1679                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1680                        final boolean virtualPreload = ((args.installFlags
1681                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1682                        final String[] grantedPermissions = args.installGrantPermissions;
1683
1684                        // Handle the parent package
1685                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1686                                virtualPreload, grantedPermissions, didRestore,
1687                                args.installerPackageName, args.observer);
1688
1689                        // Handle the child packages
1690                        final int childCount = (parentRes.addedChildPackages != null)
1691                                ? parentRes.addedChildPackages.size() : 0;
1692                        for (int i = 0; i < childCount; i++) {
1693                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1694                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1695                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1696                                    args.installerPackageName, args.observer);
1697                        }
1698
1699                        // Log tracing if needed
1700                        if (args.traceMethod != null) {
1701                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1702                                    args.traceCookie);
1703                        }
1704                    } else {
1705                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1706                    }
1707
1708                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1709                } break;
1710                case WRITE_SETTINGS: {
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1712                    synchronized (mPackages) {
1713                        removeMessages(WRITE_SETTINGS);
1714                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1715                        mSettings.writeLPr();
1716                        mDirtyUsers.clear();
1717                    }
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1719                } break;
1720                case WRITE_PACKAGE_RESTRICTIONS: {
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1722                    synchronized (mPackages) {
1723                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724                        for (int userId : mDirtyUsers) {
1725                            mSettings.writePackageRestrictionsLPr(userId);
1726                        }
1727                        mDirtyUsers.clear();
1728                    }
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1730                } break;
1731                case WRITE_PACKAGE_LIST: {
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1733                    synchronized (mPackages) {
1734                        removeMessages(WRITE_PACKAGE_LIST);
1735                        mSettings.writePackageListLPr(msg.arg1);
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case CHECK_PENDING_VERIFICATION: {
1740                    final int verificationId = msg.arg1;
1741                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1742
1743                    if ((state != null) && !state.timeoutExtended()) {
1744                        final InstallArgs args = state.getInstallArgs();
1745                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1746
1747                        Slog.i(TAG, "Verification timed out for " + originUri);
1748                        mPendingVerification.remove(verificationId);
1749
1750                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1751
1752                        final UserHandle user = args.getUser();
1753                        if (getDefaultVerificationResponse(user)
1754                                == PackageManager.VERIFICATION_ALLOW) {
1755                            Slog.i(TAG, "Continuing with installation of " + originUri);
1756                            state.setVerifierResponse(Binder.getCallingUid(),
1757                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1758                            broadcastPackageVerified(verificationId, originUri,
1759                                    PackageManager.VERIFICATION_ALLOW, user);
1760                            try {
1761                                ret = args.copyApk(mContainerService, true);
1762                            } catch (RemoteException e) {
1763                                Slog.e(TAG, "Could not contact the ContainerService");
1764                            }
1765                        } else {
1766                            broadcastPackageVerified(verificationId, originUri,
1767                                    PackageManager.VERIFICATION_REJECT, user);
1768                        }
1769
1770                        Trace.asyncTraceEnd(
1771                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1772
1773                        processPendingInstall(args, ret);
1774                        mHandler.sendEmptyMessage(MCS_UNBIND);
1775                    }
1776                    break;
1777                }
1778                case PACKAGE_VERIFIED: {
1779                    final int verificationId = msg.arg1;
1780
1781                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1782                    if (state == null) {
1783                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1784                        break;
1785                    }
1786
1787                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1788
1789                    state.setVerifierResponse(response.callerUid, response.code);
1790
1791                    if (state.isVerificationComplete()) {
1792                        mPendingVerification.remove(verificationId);
1793
1794                        final InstallArgs args = state.getInstallArgs();
1795                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1796
1797                        int ret;
1798                        if (state.isInstallAllowed()) {
1799                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1800                            broadcastPackageVerified(verificationId, originUri,
1801                                    response.code, state.getInstallArgs().getUser());
1802                            try {
1803                                ret = args.copyApk(mContainerService, true);
1804                            } catch (RemoteException e) {
1805                                Slog.e(TAG, "Could not contact the ContainerService");
1806                            }
1807                        } else {
1808                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1809                        }
1810
1811                        Trace.asyncTraceEnd(
1812                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1813
1814                        processPendingInstall(args, ret);
1815                        mHandler.sendEmptyMessage(MCS_UNBIND);
1816                    }
1817
1818                    break;
1819                }
1820                case START_INTENT_FILTER_VERIFICATIONS: {
1821                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1822                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1823                            params.replacing, params.pkg);
1824                    break;
1825                }
1826                case INTENT_FILTER_VERIFIED: {
1827                    final int verificationId = msg.arg1;
1828
1829                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1830                            verificationId);
1831                    if (state == null) {
1832                        Slog.w(TAG, "Invalid IntentFilter verification token "
1833                                + verificationId + " received");
1834                        break;
1835                    }
1836
1837                    final int userId = state.getUserId();
1838
1839                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1840                            "Processing IntentFilter verification with token:"
1841                            + verificationId + " and userId:" + userId);
1842
1843                    final IntentFilterVerificationResponse response =
1844                            (IntentFilterVerificationResponse) msg.obj;
1845
1846                    state.setVerifierResponse(response.callerUid, response.code);
1847
1848                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849                            "IntentFilter verification with token:" + verificationId
1850                            + " and userId:" + userId
1851                            + " is settings verifier response with response code:"
1852                            + response.code);
1853
1854                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1856                                + response.getFailedDomainsString());
1857                    }
1858
1859                    if (state.isVerificationComplete()) {
1860                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1861                    } else {
1862                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                                "IntentFilter verification with token:" + verificationId
1864                                + " was not said to be complete");
1865                    }
1866
1867                    break;
1868                }
1869                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1870                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1871                            mInstantAppResolverConnection,
1872                            (InstantAppRequest) msg.obj,
1873                            mInstantAppInstallerActivity,
1874                            mHandler);
1875                }
1876            }
1877        }
1878    }
1879
1880    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1881        @Override
1882        public void onGidsChanged(int appId, int userId) {
1883            mHandler.post(new Runnable() {
1884                @Override
1885                public void run() {
1886                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1887                }
1888            });
1889        }
1890        @Override
1891        public void onPermissionGranted(int uid, int userId) {
1892            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1893
1894            // Not critical; if this is lost, the application has to request again.
1895            synchronized (mPackages) {
1896                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1897            }
1898        }
1899        @Override
1900        public void onInstallPermissionGranted() {
1901            synchronized (mPackages) {
1902                scheduleWriteSettingsLocked();
1903            }
1904        }
1905        @Override
1906        public void onPermissionRevoked(int uid, int userId) {
1907            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1908
1909            synchronized (mPackages) {
1910                // Critical; after this call the application should never have the permission
1911                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1912            }
1913
1914            final int appId = UserHandle.getAppId(uid);
1915            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1916        }
1917        @Override
1918        public void onInstallPermissionRevoked() {
1919            synchronized (mPackages) {
1920                scheduleWriteSettingsLocked();
1921            }
1922        }
1923        @Override
1924        public void onPermissionUpdated(int userId) {
1925            synchronized (mPackages) {
1926                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1927            }
1928        }
1929        @Override
1930        public void onInstallPermissionUpdated() {
1931            synchronized (mPackages) {
1932                scheduleWriteSettingsLocked();
1933            }
1934        }
1935        @Override
1936        public void onPermissionRemoved() {
1937            synchronized (mPackages) {
1938                mSettings.writeLPr();
1939            }
1940        }
1941    };
1942
1943    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1944            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1945            boolean launchedForRestore, String installerPackage,
1946            IPackageInstallObserver2 installObserver) {
1947        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1948            // Send the removed broadcasts
1949            if (res.removedInfo != null) {
1950                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1951            }
1952
1953            // Now that we successfully installed the package, grant runtime
1954            // permissions if requested before broadcasting the install. Also
1955            // for legacy apps in permission review mode we clear the permission
1956            // review flag which is used to emulate runtime permissions for
1957            // legacy apps.
1958            if (grantPermissions) {
1959                final int callingUid = Binder.getCallingUid();
1960                mPermissionManager.grantRequestedRuntimePermissions(
1961                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1962                        mPermissionCallback);
1963            }
1964
1965            final boolean update = res.removedInfo != null
1966                    && res.removedInfo.removedPackage != null;
1967            final String installerPackageName =
1968                    res.installerPackageName != null
1969                            ? res.installerPackageName
1970                            : res.removedInfo != null
1971                                    ? res.removedInfo.installerPackageName
1972                                    : null;
1973
1974            // If this is the first time we have child packages for a disabled privileged
1975            // app that had no children, we grant requested runtime permissions to the new
1976            // children if the parent on the system image had them already granted.
1977            if (res.pkg.parentPackage != null) {
1978                final int callingUid = Binder.getCallingUid();
1979                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1980                        res.pkg, callingUid, mPermissionCallback);
1981            }
1982
1983            synchronized (mPackages) {
1984                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1985            }
1986
1987            final String packageName = res.pkg.applicationInfo.packageName;
1988
1989            // Determine the set of users who are adding this package for
1990            // the first time vs. those who are seeing an update.
1991            int[] firstUsers = EMPTY_INT_ARRAY;
1992            int[] updateUsers = EMPTY_INT_ARRAY;
1993            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1994            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1995            for (int newUser : res.newUsers) {
1996                if (ps.getInstantApp(newUser)) {
1997                    continue;
1998                }
1999                if (allNewUsers) {
2000                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2001                    continue;
2002                }
2003                boolean isNew = true;
2004                for (int origUser : res.origUsers) {
2005                    if (origUser == newUser) {
2006                        isNew = false;
2007                        break;
2008                    }
2009                }
2010                if (isNew) {
2011                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2012                } else {
2013                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2014                }
2015            }
2016
2017            // Send installed broadcasts if the package is not a static shared lib.
2018            if (res.pkg.staticSharedLibName == null) {
2019                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2020
2021                // Send added for users that see the package for the first time
2022                // sendPackageAddedForNewUsers also deals with system apps
2023                int appId = UserHandle.getAppId(res.uid);
2024                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2025                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2026                        virtualPreload /*startReceiver*/, appId, firstUsers);
2027
2028                // Send added for users that don't see the package for the first time
2029                Bundle extras = new Bundle(1);
2030                extras.putInt(Intent.EXTRA_UID, res.uid);
2031                if (update) {
2032                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2033                }
2034                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2035                        extras, 0 /*flags*/,
2036                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2037                if (installerPackageName != null) {
2038                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2039                            extras, 0 /*flags*/,
2040                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2041                }
2042
2043                // Send replaced for users that don't see the package for the first time
2044                if (update) {
2045                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2046                            packageName, extras, 0 /*flags*/,
2047                            null /*targetPackage*/, null /*finishedReceiver*/,
2048                            updateUsers);
2049                    if (installerPackageName != null) {
2050                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2051                                extras, 0 /*flags*/,
2052                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2053                    }
2054                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2055                            null /*package*/, null /*extras*/, 0 /*flags*/,
2056                            packageName /*targetPackage*/,
2057                            null /*finishedReceiver*/, updateUsers);
2058                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2059                    // First-install and we did a restore, so we're responsible for the
2060                    // first-launch broadcast.
2061                    if (DEBUG_BACKUP) {
2062                        Slog.i(TAG, "Post-restore of " + packageName
2063                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2064                    }
2065                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2066                }
2067
2068                // Send broadcast package appeared if forward locked/external for all users
2069                // treat asec-hosted packages like removable media on upgrade
2070                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2071                    if (DEBUG_INSTALL) {
2072                        Slog.i(TAG, "upgrading pkg " + res.pkg
2073                                + " is ASEC-hosted -> AVAILABLE");
2074                    }
2075                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2076                    ArrayList<String> pkgList = new ArrayList<>(1);
2077                    pkgList.add(packageName);
2078                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2079                }
2080            }
2081
2082            // Work that needs to happen on first install within each user
2083            if (firstUsers != null && firstUsers.length > 0) {
2084                synchronized (mPackages) {
2085                    for (int userId : firstUsers) {
2086                        // If this app is a browser and it's newly-installed for some
2087                        // users, clear any default-browser state in those users. The
2088                        // app's nature doesn't depend on the user, so we can just check
2089                        // its browser nature in any user and generalize.
2090                        if (packageIsBrowser(packageName, userId)) {
2091                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2092                        }
2093
2094                        // We may also need to apply pending (restored) runtime
2095                        // permission grants within these users.
2096                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2097                    }
2098                }
2099            }
2100
2101            // Log current value of "unknown sources" setting
2102            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2103                    getUnknownSourcesSettings());
2104
2105            // Remove the replaced package's older resources safely now
2106            // We delete after a gc for applications  on sdcard.
2107            if (res.removedInfo != null && res.removedInfo.args != null) {
2108                Runtime.getRuntime().gc();
2109                synchronized (mInstallLock) {
2110                    res.removedInfo.args.doPostDeleteLI(true);
2111                }
2112            } else {
2113                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2114                // and not block here.
2115                VMRuntime.getRuntime().requestConcurrentGC();
2116            }
2117
2118            // Notify DexManager that the package was installed for new users.
2119            // The updated users should already be indexed and the package code paths
2120            // should not change.
2121            // Don't notify the manager for ephemeral apps as they are not expected to
2122            // survive long enough to benefit of background optimizations.
2123            for (int userId : firstUsers) {
2124                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2125                // There's a race currently where some install events may interleave with an uninstall.
2126                // This can lead to package info being null (b/36642664).
2127                if (info != null) {
2128                    mDexManager.notifyPackageInstalled(info, userId);
2129                }
2130            }
2131        }
2132
2133        // If someone is watching installs - notify them
2134        if (installObserver != null) {
2135            try {
2136                Bundle extras = extrasForInstallResult(res);
2137                installObserver.onPackageInstalled(res.name, res.returnCode,
2138                        res.returnMsg, extras);
2139            } catch (RemoteException e) {
2140                Slog.i(TAG, "Observer no longer exists.");
2141            }
2142        }
2143    }
2144
2145    private StorageEventListener mStorageListener = new StorageEventListener() {
2146        @Override
2147        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2148            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2149                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2150                    final String volumeUuid = vol.getFsUuid();
2151
2152                    // Clean up any users or apps that were removed or recreated
2153                    // while this volume was missing
2154                    sUserManager.reconcileUsers(volumeUuid);
2155                    reconcileApps(volumeUuid);
2156
2157                    // Clean up any install sessions that expired or were
2158                    // cancelled while this volume was missing
2159                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2160
2161                    loadPrivatePackages(vol);
2162
2163                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2164                    unloadPrivatePackages(vol);
2165                }
2166            }
2167        }
2168
2169        @Override
2170        public void onVolumeForgotten(String fsUuid) {
2171            if (TextUtils.isEmpty(fsUuid)) {
2172                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2173                return;
2174            }
2175
2176            // Remove any apps installed on the forgotten volume
2177            synchronized (mPackages) {
2178                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2179                for (PackageSetting ps : packages) {
2180                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2181                    deletePackageVersioned(new VersionedPackage(ps.name,
2182                            PackageManager.VERSION_CODE_HIGHEST),
2183                            new LegacyPackageDeleteObserver(null).getBinder(),
2184                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2185                    // Try very hard to release any references to this package
2186                    // so we don't risk the system server being killed due to
2187                    // open FDs
2188                    AttributeCache.instance().removePackage(ps.name);
2189                }
2190
2191                mSettings.onVolumeForgotten(fsUuid);
2192                mSettings.writeLPr();
2193            }
2194        }
2195    };
2196
2197    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2198        Bundle extras = null;
2199        switch (res.returnCode) {
2200            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2201                extras = new Bundle();
2202                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2203                        res.origPermission);
2204                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2205                        res.origPackage);
2206                break;
2207            }
2208            case PackageManager.INSTALL_SUCCEEDED: {
2209                extras = new Bundle();
2210                extras.putBoolean(Intent.EXTRA_REPLACING,
2211                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2212                break;
2213            }
2214        }
2215        return extras;
2216    }
2217
2218    void scheduleWriteSettingsLocked() {
2219        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2220            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2221        }
2222    }
2223
2224    void scheduleWritePackageListLocked(int userId) {
2225        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2226            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2227            msg.arg1 = userId;
2228            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2229        }
2230    }
2231
2232    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2233        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2234        scheduleWritePackageRestrictionsLocked(userId);
2235    }
2236
2237    void scheduleWritePackageRestrictionsLocked(int userId) {
2238        final int[] userIds = (userId == UserHandle.USER_ALL)
2239                ? sUserManager.getUserIds() : new int[]{userId};
2240        for (int nextUserId : userIds) {
2241            if (!sUserManager.exists(nextUserId)) return;
2242            mDirtyUsers.add(nextUserId);
2243            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2244                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2245            }
2246        }
2247    }
2248
2249    public static PackageManagerService main(Context context, Installer installer,
2250            boolean factoryTest, boolean onlyCore) {
2251        // Self-check for initial settings.
2252        PackageManagerServiceCompilerMapping.checkProperties();
2253
2254        PackageManagerService m = new PackageManagerService(context, installer,
2255                factoryTest, onlyCore);
2256        m.enableSystemUserPackages();
2257        ServiceManager.addService("package", m);
2258        final PackageManagerNative pmn = m.new PackageManagerNative();
2259        ServiceManager.addService("package_native", pmn);
2260        return m;
2261    }
2262
2263    private void enableSystemUserPackages() {
2264        if (!UserManager.isSplitSystemUser()) {
2265            return;
2266        }
2267        // For system user, enable apps based on the following conditions:
2268        // - app is whitelisted or belong to one of these groups:
2269        //   -- system app which has no launcher icons
2270        //   -- system app which has INTERACT_ACROSS_USERS permission
2271        //   -- system IME app
2272        // - app is not in the blacklist
2273        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2274        Set<String> enableApps = new ArraySet<>();
2275        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2276                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2277                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2278        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2279        enableApps.addAll(wlApps);
2280        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2281                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2282        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2283        enableApps.removeAll(blApps);
2284        Log.i(TAG, "Applications installed for system user: " + enableApps);
2285        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2286                UserHandle.SYSTEM);
2287        final int allAppsSize = allAps.size();
2288        synchronized (mPackages) {
2289            for (int i = 0; i < allAppsSize; i++) {
2290                String pName = allAps.get(i);
2291                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2292                // Should not happen, but we shouldn't be failing if it does
2293                if (pkgSetting == null) {
2294                    continue;
2295                }
2296                boolean install = enableApps.contains(pName);
2297                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2298                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2299                            + " for system user");
2300                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2301                }
2302            }
2303            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2304        }
2305    }
2306
2307    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2308        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2309                Context.DISPLAY_SERVICE);
2310        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2311    }
2312
2313    /**
2314     * Requests that files preopted on a secondary system partition be copied to the data partition
2315     * if possible.  Note that the actual copying of the files is accomplished by init for security
2316     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2317     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2318     */
2319    private static void requestCopyPreoptedFiles() {
2320        final int WAIT_TIME_MS = 100;
2321        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2322        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2323            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2324            // We will wait for up to 100 seconds.
2325            final long timeStart = SystemClock.uptimeMillis();
2326            final long timeEnd = timeStart + 100 * 1000;
2327            long timeNow = timeStart;
2328            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2329                try {
2330                    Thread.sleep(WAIT_TIME_MS);
2331                } catch (InterruptedException e) {
2332                    // Do nothing
2333                }
2334                timeNow = SystemClock.uptimeMillis();
2335                if (timeNow > timeEnd) {
2336                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2337                    Slog.wtf(TAG, "cppreopt did not finish!");
2338                    break;
2339                }
2340            }
2341
2342            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2343        }
2344    }
2345
2346    public PackageManagerService(Context context, Installer installer,
2347            boolean factoryTest, boolean onlyCore) {
2348        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2349        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2350        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2351                SystemClock.uptimeMillis());
2352
2353        if (mSdkVersion <= 0) {
2354            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2355        }
2356
2357        mContext = context;
2358
2359        mPermissionReviewRequired = context.getResources().getBoolean(
2360                R.bool.config_permissionReviewRequired);
2361
2362        mFactoryTest = factoryTest;
2363        mOnlyCore = onlyCore;
2364        mMetrics = new DisplayMetrics();
2365        mInstaller = installer;
2366
2367        // Create sub-components that provide services / data. Order here is important.
2368        synchronized (mInstallLock) {
2369        synchronized (mPackages) {
2370            // Expose private service for system components to use.
2371            LocalServices.addService(
2372                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2373            sUserManager = new UserManagerService(context, this,
2374                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2375            mPermissionManager = PermissionManagerService.create(context,
2376                    new DefaultPermissionGrantedCallback() {
2377                        @Override
2378                        public void onDefaultRuntimePermissionsGranted(int userId) {
2379                            synchronized(mPackages) {
2380                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2381                            }
2382                        }
2383                    }, mPackages /*externalLock*/);
2384            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2385            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2386        }
2387        }
2388        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2393                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2394        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400
2401        String separateProcesses = SystemProperties.get("debug.separate_processes");
2402        if (separateProcesses != null && separateProcesses.length() > 0) {
2403            if ("*".equals(separateProcesses)) {
2404                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2405                mSeparateProcesses = null;
2406                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2407            } else {
2408                mDefParseFlags = 0;
2409                mSeparateProcesses = separateProcesses.split(",");
2410                Slog.w(TAG, "Running with debug.separate_processes: "
2411                        + separateProcesses);
2412            }
2413        } else {
2414            mDefParseFlags = 0;
2415            mSeparateProcesses = null;
2416        }
2417
2418        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2419                "*dexopt*");
2420        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2421        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2422
2423        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2424                FgThread.get().getLooper());
2425
2426        getDefaultDisplayMetrics(context, mMetrics);
2427
2428        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2429        SystemConfig systemConfig = SystemConfig.getInstance();
2430        mAvailableFeatures = systemConfig.getAvailableFeatures();
2431        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2432
2433        mProtectedPackages = new ProtectedPackages(mContext);
2434
2435        synchronized (mInstallLock) {
2436        // writer
2437        synchronized (mPackages) {
2438            mHandlerThread = new ServiceThread(TAG,
2439                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2440            mHandlerThread.start();
2441            mHandler = new PackageHandler(mHandlerThread.getLooper());
2442            mProcessLoggingHandler = new ProcessLoggingHandler();
2443            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2444            mInstantAppRegistry = new InstantAppRegistry(this);
2445
2446            File dataDir = Environment.getDataDirectory();
2447            mAppInstallDir = new File(dataDir, "app");
2448            mAppLib32InstallDir = new File(dataDir, "app-lib");
2449            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2450
2451            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2452            final int builtInLibCount = libConfig.size();
2453            for (int i = 0; i < builtInLibCount; i++) {
2454                String name = libConfig.keyAt(i);
2455                String path = libConfig.valueAt(i);
2456                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2457                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2458            }
2459
2460            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2461
2462            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2463            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2464            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2465
2466            // Clean up orphaned packages for which the code path doesn't exist
2467            // and they are an update to a system app - caused by bug/32321269
2468            final int packageSettingCount = mSettings.mPackages.size();
2469            for (int i = packageSettingCount - 1; i >= 0; i--) {
2470                PackageSetting ps = mSettings.mPackages.valueAt(i);
2471                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2472                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2473                    mSettings.mPackages.removeAt(i);
2474                    mSettings.enableSystemPackageLPw(ps.name);
2475                }
2476            }
2477
2478            if (mFirstBoot) {
2479                requestCopyPreoptedFiles();
2480            }
2481
2482            String customResolverActivity = Resources.getSystem().getString(
2483                    R.string.config_customResolverActivity);
2484            if (TextUtils.isEmpty(customResolverActivity)) {
2485                customResolverActivity = null;
2486            } else {
2487                mCustomResolverComponentName = ComponentName.unflattenFromString(
2488                        customResolverActivity);
2489            }
2490
2491            long startTime = SystemClock.uptimeMillis();
2492
2493            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2494                    startTime);
2495
2496            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2497            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2498
2499            if (bootClassPath == null) {
2500                Slog.w(TAG, "No BOOTCLASSPATH found!");
2501            }
2502
2503            if (systemServerClassPath == null) {
2504                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2505            }
2506
2507            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2508
2509            final VersionInfo ver = mSettings.getInternalVersion();
2510            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2511            if (mIsUpgrade) {
2512                logCriticalInfo(Log.INFO,
2513                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2514            }
2515
2516            // when upgrading from pre-M, promote system app permissions from install to runtime
2517            mPromoteSystemApps =
2518                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2519
2520            // When upgrading from pre-N, we need to handle package extraction like first boot,
2521            // as there is no profiling data available.
2522            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2523
2524            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2525
2526            // save off the names of pre-existing system packages prior to scanning; we don't
2527            // want to automatically grant runtime permissions for new system apps
2528            if (mPromoteSystemApps) {
2529                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2530                while (pkgSettingIter.hasNext()) {
2531                    PackageSetting ps = pkgSettingIter.next();
2532                    if (isSystemApp(ps)) {
2533                        mExistingSystemPackages.add(ps.name);
2534                    }
2535                }
2536            }
2537
2538            mCacheDir = preparePackageParserCache(mIsUpgrade);
2539
2540            // Set flag to monitor and not change apk file paths when
2541            // scanning install directories.
2542            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2543
2544            if (mIsUpgrade || mFirstBoot) {
2545                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2546            }
2547
2548            // Collect vendor overlay packages. (Do this before scanning any apps.)
2549            // For security and version matching reason, only consider
2550            // overlay packages if they reside in the right directory.
2551            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2552                    | PackageParser.PARSE_IS_SYSTEM
2553                    | PackageParser.PARSE_IS_SYSTEM_DIR
2554                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2555
2556            mParallelPackageParserCallback.findStaticOverlayPackages();
2557
2558            // Find base frameworks (resource packages without code).
2559            scanDirTracedLI(frameworkDir, mDefParseFlags
2560                    | PackageParser.PARSE_IS_SYSTEM
2561                    | PackageParser.PARSE_IS_SYSTEM_DIR
2562                    | PackageParser.PARSE_IS_PRIVILEGED,
2563                    scanFlags | SCAN_NO_DEX, 0);
2564
2565            // Collected privileged system packages.
2566            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2567            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2568                    | PackageParser.PARSE_IS_SYSTEM
2569                    | PackageParser.PARSE_IS_SYSTEM_DIR
2570                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2571
2572            // Collect ordinary system packages.
2573            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2574            scanDirTracedLI(systemAppDir, mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM
2576                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2577
2578            // Collect all vendor packages.
2579            File vendorAppDir = new File("/vendor/app");
2580            try {
2581                vendorAppDir = vendorAppDir.getCanonicalFile();
2582            } catch (IOException e) {
2583                // failed to look up canonical path, continue with original one
2584            }
2585            scanDirTracedLI(vendorAppDir, mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2588
2589            // Collect all OEM packages.
2590            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2591            scanDirTracedLI(oemAppDir, mDefParseFlags
2592                    | PackageParser.PARSE_IS_SYSTEM
2593                    | PackageParser.PARSE_IS_SYSTEM_DIR
2594                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2595
2596            // Prune any system packages that no longer exist.
2597            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2598            // Stub packages must either be replaced with full versions in the /data
2599            // partition or be disabled.
2600            final List<String> stubSystemApps = new ArrayList<>();
2601            if (!mOnlyCore) {
2602                // do this first before mucking with mPackages for the "expecting better" case
2603                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2604                while (pkgIterator.hasNext()) {
2605                    final PackageParser.Package pkg = pkgIterator.next();
2606                    if (pkg.isStub) {
2607                        stubSystemApps.add(pkg.packageName);
2608                    }
2609                }
2610
2611                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2612                while (psit.hasNext()) {
2613                    PackageSetting ps = psit.next();
2614
2615                    /*
2616                     * If this is not a system app, it can't be a
2617                     * disable system app.
2618                     */
2619                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2620                        continue;
2621                    }
2622
2623                    /*
2624                     * If the package is scanned, it's not erased.
2625                     */
2626                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2627                    if (scannedPkg != null) {
2628                        /*
2629                         * If the system app is both scanned and in the
2630                         * disabled packages list, then it must have been
2631                         * added via OTA. Remove it from the currently
2632                         * scanned package so the previously user-installed
2633                         * application can be scanned.
2634                         */
2635                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2636                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2637                                    + ps.name + "; removing system app.  Last known codePath="
2638                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2639                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2640                                    + scannedPkg.mVersionCode);
2641                            removePackageLI(scannedPkg, true);
2642                            mExpectingBetter.put(ps.name, ps.codePath);
2643                        }
2644
2645                        continue;
2646                    }
2647
2648                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2649                        psit.remove();
2650                        logCriticalInfo(Log.WARN, "System package " + ps.name
2651                                + " no longer exists; it's data will be wiped");
2652                        // Actual deletion of code and data will be handled by later
2653                        // reconciliation step
2654                    } else {
2655                        // we still have a disabled system package, but, it still might have
2656                        // been removed. check the code path still exists and check there's
2657                        // still a package. the latter can happen if an OTA keeps the same
2658                        // code path, but, changes the package name.
2659                        final PackageSetting disabledPs =
2660                                mSettings.getDisabledSystemPkgLPr(ps.name);
2661                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2662                                || disabledPs.pkg == null) {
2663                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2664                        }
2665                    }
2666                }
2667            }
2668
2669            //look for any incomplete package installations
2670            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2671            for (int i = 0; i < deletePkgsList.size(); i++) {
2672                // Actual deletion of code and data will be handled by later
2673                // reconciliation step
2674                final String packageName = deletePkgsList.get(i).name;
2675                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2676                synchronized (mPackages) {
2677                    mSettings.removePackageLPw(packageName);
2678                }
2679            }
2680
2681            //delete tmp files
2682            deleteTempPackageFiles();
2683
2684            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2685
2686            // Remove any shared userIDs that have no associated packages
2687            mSettings.pruneSharedUsersLPw();
2688            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2689            final int systemPackagesCount = mPackages.size();
2690            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2691                    + " ms, packageCount: " + systemPackagesCount
2692                    + " , timePerPackage: "
2693                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2694                    + " , cached: " + cachedSystemApps);
2695            if (mIsUpgrade && systemPackagesCount > 0) {
2696                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2697                        ((int) systemScanTime) / systemPackagesCount);
2698            }
2699            if (!mOnlyCore) {
2700                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2701                        SystemClock.uptimeMillis());
2702                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2703
2704                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2705                        | PackageParser.PARSE_FORWARD_LOCK,
2706                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                // Remove disable package settings for updated system apps that were
2709                // removed via an OTA. If the update is no longer present, remove the
2710                // app completely. Otherwise, revoke their system privileges.
2711                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2712                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2713                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2714
2715                    final String msg;
2716                    if (deletedPkg == null) {
2717                        // should have found an update, but, we didn't; remove everything
2718                        msg = "Updated system package " + deletedAppName
2719                                + " no longer exists; removing its data";
2720                        // Actual deletion of code and data will be handled by later
2721                        // reconciliation step
2722                    } else {
2723                        // found an update; revoke system privileges
2724                        msg = "Updated system package + " + deletedAppName
2725                                + " no longer exists; revoking system privileges";
2726
2727                        // Don't do anything if a stub is removed from the system image. If
2728                        // we were to remove the uncompressed version from the /data partition,
2729                        // this is where it'd be done.
2730
2731                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2732                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2733                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2734                    }
2735                    logCriticalInfo(Log.WARN, msg);
2736                }
2737
2738                /*
2739                 * Make sure all system apps that we expected to appear on
2740                 * the userdata partition actually showed up. If they never
2741                 * appeared, crawl back and revive the system version.
2742                 */
2743                for (int i = 0; i < mExpectingBetter.size(); i++) {
2744                    final String packageName = mExpectingBetter.keyAt(i);
2745                    if (!mPackages.containsKey(packageName)) {
2746                        final File scanFile = mExpectingBetter.valueAt(i);
2747
2748                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2749                                + " but never showed up; reverting to system");
2750
2751                        int reparseFlags = mDefParseFlags;
2752                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2753                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2754                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2755                                    | PackageParser.PARSE_IS_PRIVILEGED;
2756                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2759                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2765                                    | PackageParser.PARSE_IS_OEM;
2766                        } else {
2767                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2768                            continue;
2769                        }
2770
2771                        mSettings.enableSystemPackageLPw(packageName);
2772
2773                        try {
2774                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2775                        } catch (PackageManagerException e) {
2776                            Slog.e(TAG, "Failed to parse original system package: "
2777                                    + e.getMessage());
2778                        }
2779                    }
2780                }
2781
2782                // Uncompress and install any stubbed system applications.
2783                // This must be done last to ensure all stubs are replaced or disabled.
2784                decompressSystemApplications(stubSystemApps, scanFlags);
2785
2786                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2787                                - cachedSystemApps;
2788
2789                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2790                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2791                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2792                        + " ms, packageCount: " + dataPackagesCount
2793                        + " , timePerPackage: "
2794                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2795                        + " , cached: " + cachedNonSystemApps);
2796                if (mIsUpgrade && dataPackagesCount > 0) {
2797                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2798                            ((int) dataScanTime) / dataPackagesCount);
2799                }
2800            }
2801            mExpectingBetter.clear();
2802
2803            // Resolve the storage manager.
2804            mStorageManagerPackage = getStorageManagerPackageName();
2805
2806            // Resolve protected action filters. Only the setup wizard is allowed to
2807            // have a high priority filter for these actions.
2808            mSetupWizardPackage = getSetupWizardPackageName();
2809            if (mProtectedFilters.size() > 0) {
2810                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2811                    Slog.i(TAG, "No setup wizard;"
2812                        + " All protected intents capped to priority 0");
2813                }
2814                for (ActivityIntentInfo filter : mProtectedFilters) {
2815                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2816                        if (DEBUG_FILTERS) {
2817                            Slog.i(TAG, "Found setup wizard;"
2818                                + " allow priority " + filter.getPriority() + ";"
2819                                + " package: " + filter.activity.info.packageName
2820                                + " activity: " + filter.activity.className
2821                                + " priority: " + filter.getPriority());
2822                        }
2823                        // skip setup wizard; allow it to keep the high priority filter
2824                        continue;
2825                    }
2826                    if (DEBUG_FILTERS) {
2827                        Slog.i(TAG, "Protected action; cap priority to 0;"
2828                                + " package: " + filter.activity.info.packageName
2829                                + " activity: " + filter.activity.className
2830                                + " origPrio: " + filter.getPriority());
2831                    }
2832                    filter.setPriority(0);
2833                }
2834            }
2835            mDeferProtectedFilters = false;
2836            mProtectedFilters.clear();
2837
2838            // Now that we know all of the shared libraries, update all clients to have
2839            // the correct library paths.
2840            updateAllSharedLibrariesLPw(null);
2841
2842            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2843                // NOTE: We ignore potential failures here during a system scan (like
2844                // the rest of the commands above) because there's precious little we
2845                // can do about it. A settings error is reported, though.
2846                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2847            }
2848
2849            // Now that we know all the packages we are keeping,
2850            // read and update their last usage times.
2851            mPackageUsage.read(mPackages);
2852            mCompilerStats.read();
2853
2854            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2855                    SystemClock.uptimeMillis());
2856            Slog.i(TAG, "Time to scan packages: "
2857                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2858                    + " seconds");
2859
2860            // If the platform SDK has changed since the last time we booted,
2861            // we need to re-grant app permission to catch any new ones that
2862            // appear.  This is really a hack, and means that apps can in some
2863            // cases get permissions that the user didn't initially explicitly
2864            // allow...  it would be nice to have some better way to handle
2865            // this situation.
2866            int updateFlags = UPDATE_PERMISSIONS_ALL;
2867            if (ver.sdkVersion != mSdkVersion) {
2868                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2869                        + mSdkVersion + "; regranting permissions for internal storage");
2870                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2871            }
2872            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2873            ver.sdkVersion = mSdkVersion;
2874
2875            // If this is the first boot or an update from pre-M, and it is a normal
2876            // boot, then we need to initialize the default preferred apps across
2877            // all defined users.
2878            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2879                for (UserInfo user : sUserManager.getUsers(true)) {
2880                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2881                    applyFactoryDefaultBrowserLPw(user.id);
2882                    primeDomainVerificationsLPw(user.id);
2883                }
2884            }
2885
2886            // Prepare storage for system user really early during boot,
2887            // since core system apps like SettingsProvider and SystemUI
2888            // can't wait for user to start
2889            final int storageFlags;
2890            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2891                storageFlags = StorageManager.FLAG_STORAGE_DE;
2892            } else {
2893                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2894            }
2895            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2896                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2897                    true /* onlyCoreApps */);
2898            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2899                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2900                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2901                traceLog.traceBegin("AppDataFixup");
2902                try {
2903                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2904                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2905                } catch (InstallerException e) {
2906                    Slog.w(TAG, "Trouble fixing GIDs", e);
2907                }
2908                traceLog.traceEnd();
2909
2910                traceLog.traceBegin("AppDataPrepare");
2911                if (deferPackages == null || deferPackages.isEmpty()) {
2912                    return;
2913                }
2914                int count = 0;
2915                for (String pkgName : deferPackages) {
2916                    PackageParser.Package pkg = null;
2917                    synchronized (mPackages) {
2918                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2919                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2920                            pkg = ps.pkg;
2921                        }
2922                    }
2923                    if (pkg != null) {
2924                        synchronized (mInstallLock) {
2925                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2926                                    true /* maybeMigrateAppData */);
2927                        }
2928                        count++;
2929                    }
2930                }
2931                traceLog.traceEnd();
2932                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2933            }, "prepareAppData");
2934
2935            // If this is first boot after an OTA, and a normal boot, then
2936            // we need to clear code cache directories.
2937            // Note that we do *not* clear the application profiles. These remain valid
2938            // across OTAs and are used to drive profile verification (post OTA) and
2939            // profile compilation (without waiting to collect a fresh set of profiles).
2940            if (mIsUpgrade && !onlyCore) {
2941                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2942                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2943                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2944                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2945                        // No apps are running this early, so no need to freeze
2946                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2947                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2948                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2949                    }
2950                }
2951                ver.fingerprint = Build.FINGERPRINT;
2952            }
2953
2954            checkDefaultBrowser();
2955
2956            // clear only after permissions and other defaults have been updated
2957            mExistingSystemPackages.clear();
2958            mPromoteSystemApps = false;
2959
2960            // All the changes are done during package scanning.
2961            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2962
2963            // can downgrade to reader
2964            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2965            mSettings.writeLPr();
2966            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2967            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2968                    SystemClock.uptimeMillis());
2969
2970            if (!mOnlyCore) {
2971                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2972                mRequiredInstallerPackage = getRequiredInstallerLPr();
2973                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2974                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2975                if (mIntentFilterVerifierComponent != null) {
2976                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2977                            mIntentFilterVerifierComponent);
2978                } else {
2979                    mIntentFilterVerifier = null;
2980                }
2981                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2982                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2983                        SharedLibraryInfo.VERSION_UNDEFINED);
2984                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2985                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2986                        SharedLibraryInfo.VERSION_UNDEFINED);
2987            } else {
2988                mRequiredVerifierPackage = null;
2989                mRequiredInstallerPackage = null;
2990                mRequiredUninstallerPackage = null;
2991                mIntentFilterVerifierComponent = null;
2992                mIntentFilterVerifier = null;
2993                mServicesSystemSharedLibraryPackageName = null;
2994                mSharedSystemSharedLibraryPackageName = null;
2995            }
2996
2997            mInstallerService = new PackageInstallerService(context, this);
2998            final Pair<ComponentName, String> instantAppResolverComponent =
2999                    getInstantAppResolverLPr();
3000            if (instantAppResolverComponent != null) {
3001                if (DEBUG_EPHEMERAL) {
3002                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3003                }
3004                mInstantAppResolverConnection = new EphemeralResolverConnection(
3005                        mContext, instantAppResolverComponent.first,
3006                        instantAppResolverComponent.second);
3007                mInstantAppResolverSettingsComponent =
3008                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3009            } else {
3010                mInstantAppResolverConnection = null;
3011                mInstantAppResolverSettingsComponent = null;
3012            }
3013            updateInstantAppInstallerLocked(null);
3014
3015            // Read and update the usage of dex files.
3016            // Do this at the end of PM init so that all the packages have their
3017            // data directory reconciled.
3018            // At this point we know the code paths of the packages, so we can validate
3019            // the disk file and build the internal cache.
3020            // The usage file is expected to be small so loading and verifying it
3021            // should take a fairly small time compare to the other activities (e.g. package
3022            // scanning).
3023            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3024            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3025            for (int userId : currentUserIds) {
3026                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3027            }
3028            mDexManager.load(userPackages);
3029            if (mIsUpgrade) {
3030                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3031                        (int) (SystemClock.uptimeMillis() - startTime));
3032            }
3033        } // synchronized (mPackages)
3034        } // synchronized (mInstallLock)
3035
3036        // Now after opening every single application zip, make sure they
3037        // are all flushed.  Not really needed, but keeps things nice and
3038        // tidy.
3039        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3040        Runtime.getRuntime().gc();
3041        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3042
3043        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3044        FallbackCategoryProvider.loadFallbacks();
3045        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3046
3047        // The initial scanning above does many calls into installd while
3048        // holding the mPackages lock, but we're mostly interested in yelling
3049        // once we have a booted system.
3050        mInstaller.setWarnIfHeld(mPackages);
3051
3052        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3053    }
3054
3055    /**
3056     * Uncompress and install stub applications.
3057     * <p>In order to save space on the system partition, some applications are shipped in a
3058     * compressed form. In addition the compressed bits for the full application, the
3059     * system image contains a tiny stub comprised of only the Android manifest.
3060     * <p>During the first boot, attempt to uncompress and install the full application. If
3061     * the application can't be installed for any reason, disable the stub and prevent
3062     * uncompressing the full application during future boots.
3063     * <p>In order to forcefully attempt an installation of a full application, go to app
3064     * settings and enable the application.
3065     */
3066    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3067        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3068            final String pkgName = stubSystemApps.get(i);
3069            // skip if the system package is already disabled
3070            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3071                stubSystemApps.remove(i);
3072                continue;
3073            }
3074            // skip if the package isn't installed (?!); this should never happen
3075            final PackageParser.Package pkg = mPackages.get(pkgName);
3076            if (pkg == null) {
3077                stubSystemApps.remove(i);
3078                continue;
3079            }
3080            // skip if the package has been disabled by the user
3081            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3082            if (ps != null) {
3083                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3084                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3085                    stubSystemApps.remove(i);
3086                    continue;
3087                }
3088            }
3089
3090            if (DEBUG_COMPRESSION) {
3091                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3092            }
3093
3094            // uncompress the binary to its eventual destination on /data
3095            final File scanFile = decompressPackage(pkg);
3096            if (scanFile == null) {
3097                continue;
3098            }
3099
3100            // install the package to replace the stub on /system
3101            try {
3102                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3103                removePackageLI(pkg, true /*chatty*/);
3104                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3105                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3106                        UserHandle.USER_SYSTEM, "android");
3107                stubSystemApps.remove(i);
3108                continue;
3109            } catch (PackageManagerException e) {
3110                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3111            }
3112
3113            // any failed attempt to install the package will be cleaned up later
3114        }
3115
3116        // disable any stub still left; these failed to install the full application
3117        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3118            final String pkgName = stubSystemApps.get(i);
3119            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3120            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3121                    UserHandle.USER_SYSTEM, "android");
3122            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3123        }
3124    }
3125
3126    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3127        if (DEBUG_COMPRESSION) {
3128            Slog.i(TAG, "Decompress file"
3129                    + "; src: " + srcFile.getAbsolutePath()
3130                    + ", dst: " + dstFile.getAbsolutePath());
3131        }
3132        try (
3133                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3134                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3135        ) {
3136            Streams.copy(fileIn, fileOut);
3137            Os.chmod(dstFile.getAbsolutePath(), 0644);
3138            return PackageManager.INSTALL_SUCCEEDED;
3139        } catch (IOException e) {
3140            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3141                    + "; src: " + srcFile.getAbsolutePath()
3142                    + ", dst: " + dstFile.getAbsolutePath());
3143        }
3144        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3145    }
3146
3147    private File[] getCompressedFiles(String codePath) {
3148        final File stubCodePath = new File(codePath);
3149        final String stubName = stubCodePath.getName();
3150
3151        // The layout of a compressed package on a given partition is as follows :
3152        //
3153        // Compressed artifacts:
3154        //
3155        // /partition/ModuleName/foo.gz
3156        // /partation/ModuleName/bar.gz
3157        //
3158        // Stub artifact:
3159        //
3160        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3161        //
3162        // In other words, stub is on the same partition as the compressed artifacts
3163        // and in a directory that's suffixed with "-Stub".
3164        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3165        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3166            return null;
3167        }
3168
3169        final File stubParentDir = stubCodePath.getParentFile();
3170        if (stubParentDir == null) {
3171            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3172            return null;
3173        }
3174
3175        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3176        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3177            @Override
3178            public boolean accept(File dir, String name) {
3179                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3180            }
3181        });
3182
3183        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3184            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3185        }
3186
3187        return files;
3188    }
3189
3190    private boolean compressedFileExists(String codePath) {
3191        final File[] compressedFiles = getCompressedFiles(codePath);
3192        return compressedFiles != null && compressedFiles.length > 0;
3193    }
3194
3195    /**
3196     * Decompresses the given package on the system image onto
3197     * the /data partition.
3198     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3199     */
3200    private File decompressPackage(PackageParser.Package pkg) {
3201        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3202        if (compressedFiles == null || compressedFiles.length == 0) {
3203            if (DEBUG_COMPRESSION) {
3204                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3205            }
3206            return null;
3207        }
3208        final File dstCodePath =
3209                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3210        int ret = PackageManager.INSTALL_SUCCEEDED;
3211        try {
3212            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3213            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3214            for (File srcFile : compressedFiles) {
3215                final String srcFileName = srcFile.getName();
3216                final String dstFileName = srcFileName.substring(
3217                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3218                final File dstFile = new File(dstCodePath, dstFileName);
3219                ret = decompressFile(srcFile, dstFile);
3220                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3221                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3222                            + "; pkg: " + pkg.packageName
3223                            + ", file: " + dstFileName);
3224                    break;
3225                }
3226            }
3227        } catch (ErrnoException e) {
3228            logCriticalInfo(Log.ERROR, "Failed to decompress"
3229                    + "; pkg: " + pkg.packageName
3230                    + ", err: " + e.errno);
3231        }
3232        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3233            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3234            NativeLibraryHelper.Handle handle = null;
3235            try {
3236                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3237                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3238                        null /*abiOverride*/);
3239            } catch (IOException e) {
3240                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3241                        + "; pkg: " + pkg.packageName);
3242                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3243            } finally {
3244                IoUtils.closeQuietly(handle);
3245            }
3246        }
3247        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3248            if (dstCodePath == null || !dstCodePath.exists()) {
3249                return null;
3250            }
3251            removeCodePathLI(dstCodePath);
3252            return null;
3253        }
3254
3255        return dstCodePath;
3256    }
3257
3258    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3259        // we're only interested in updating the installer appliction when 1) it's not
3260        // already set or 2) the modified package is the installer
3261        if (mInstantAppInstallerActivity != null
3262                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3263                        .equals(modifiedPackage)) {
3264            return;
3265        }
3266        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3267    }
3268
3269    private static File preparePackageParserCache(boolean isUpgrade) {
3270        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3271            return null;
3272        }
3273
3274        // Disable package parsing on eng builds to allow for faster incremental development.
3275        if (Build.IS_ENG) {
3276            return null;
3277        }
3278
3279        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3280            Slog.i(TAG, "Disabling package parser cache due to system property.");
3281            return null;
3282        }
3283
3284        // The base directory for the package parser cache lives under /data/system/.
3285        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3286                "package_cache");
3287        if (cacheBaseDir == null) {
3288            return null;
3289        }
3290
3291        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3292        // This also serves to "GC" unused entries when the package cache version changes (which
3293        // can only happen during upgrades).
3294        if (isUpgrade) {
3295            FileUtils.deleteContents(cacheBaseDir);
3296        }
3297
3298
3299        // Return the versioned package cache directory. This is something like
3300        // "/data/system/package_cache/1"
3301        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3302
3303        // The following is a workaround to aid development on non-numbered userdebug
3304        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3305        // the system partition is newer.
3306        //
3307        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3308        // that starts with "eng." to signify that this is an engineering build and not
3309        // destined for release.
3310        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3311            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3312
3313            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3314            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3315            // in general and should not be used for production changes. In this specific case,
3316            // we know that they will work.
3317            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3318            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3319                FileUtils.deleteContents(cacheBaseDir);
3320                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3321            }
3322        }
3323
3324        return cacheDir;
3325    }
3326
3327    @Override
3328    public boolean isFirstBoot() {
3329        // allow instant applications
3330        return mFirstBoot;
3331    }
3332
3333    @Override
3334    public boolean isOnlyCoreApps() {
3335        // allow instant applications
3336        return mOnlyCore;
3337    }
3338
3339    @Override
3340    public boolean isUpgrade() {
3341        // allow instant applications
3342        // The system property allows testing ota flow when upgraded to the same image.
3343        return mIsUpgrade || SystemProperties.getBoolean(
3344                "persist.pm.mock-upgrade", false /* default */);
3345    }
3346
3347    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3348        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3349
3350        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3351                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3352                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3353        if (matches.size() == 1) {
3354            return matches.get(0).getComponentInfo().packageName;
3355        } else if (matches.size() == 0) {
3356            Log.e(TAG, "There should probably be a verifier, but, none were found");
3357            return null;
3358        }
3359        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3360    }
3361
3362    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3363        synchronized (mPackages) {
3364            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3365            if (libraryEntry == null) {
3366                throw new IllegalStateException("Missing required shared library:" + name);
3367            }
3368            return libraryEntry.apk;
3369        }
3370    }
3371
3372    private @NonNull String getRequiredInstallerLPr() {
3373        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3374        intent.addCategory(Intent.CATEGORY_DEFAULT);
3375        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3376
3377        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3378                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3379                UserHandle.USER_SYSTEM);
3380        if (matches.size() == 1) {
3381            ResolveInfo resolveInfo = matches.get(0);
3382            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3383                throw new RuntimeException("The installer must be a privileged app");
3384            }
3385            return matches.get(0).getComponentInfo().packageName;
3386        } else {
3387            throw new RuntimeException("There must be exactly one installer; found " + matches);
3388        }
3389    }
3390
3391    private @NonNull String getRequiredUninstallerLPr() {
3392        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3393        intent.addCategory(Intent.CATEGORY_DEFAULT);
3394        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3395
3396        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3397                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3398                UserHandle.USER_SYSTEM);
3399        if (resolveInfo == null ||
3400                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3401            throw new RuntimeException("There must be exactly one uninstaller; found "
3402                    + resolveInfo);
3403        }
3404        return resolveInfo.getComponentInfo().packageName;
3405    }
3406
3407    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3408        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3409
3410        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3411                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3412                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3413        ResolveInfo best = null;
3414        final int N = matches.size();
3415        for (int i = 0; i < N; i++) {
3416            final ResolveInfo cur = matches.get(i);
3417            final String packageName = cur.getComponentInfo().packageName;
3418            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3419                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3420                continue;
3421            }
3422
3423            if (best == null || cur.priority > best.priority) {
3424                best = cur;
3425            }
3426        }
3427
3428        if (best != null) {
3429            return best.getComponentInfo().getComponentName();
3430        }
3431        Slog.w(TAG, "Intent filter verifier not found");
3432        return null;
3433    }
3434
3435    @Override
3436    public @Nullable ComponentName getInstantAppResolverComponent() {
3437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3438            return null;
3439        }
3440        synchronized (mPackages) {
3441            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3442            if (instantAppResolver == null) {
3443                return null;
3444            }
3445            return instantAppResolver.first;
3446        }
3447    }
3448
3449    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3450        final String[] packageArray =
3451                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3452        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3453            if (DEBUG_EPHEMERAL) {
3454                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3455            }
3456            return null;
3457        }
3458
3459        final int callingUid = Binder.getCallingUid();
3460        final int resolveFlags =
3461                MATCH_DIRECT_BOOT_AWARE
3462                | MATCH_DIRECT_BOOT_UNAWARE
3463                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3464        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3465        final Intent resolverIntent = new Intent(actionName);
3466        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3467                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3468        // temporarily look for the old action
3469        if (resolvers.size() == 0) {
3470            if (DEBUG_EPHEMERAL) {
3471                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3472            }
3473            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3474            resolverIntent.setAction(actionName);
3475            resolvers = queryIntentServicesInternal(resolverIntent, null,
3476                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3477        }
3478        final int N = resolvers.size();
3479        if (N == 0) {
3480            if (DEBUG_EPHEMERAL) {
3481                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3482            }
3483            return null;
3484        }
3485
3486        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3487        for (int i = 0; i < N; i++) {
3488            final ResolveInfo info = resolvers.get(i);
3489
3490            if (info.serviceInfo == null) {
3491                continue;
3492            }
3493
3494            final String packageName = info.serviceInfo.packageName;
3495            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3496                if (DEBUG_EPHEMERAL) {
3497                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3498                            + " pkg: " + packageName + ", info:" + info);
3499                }
3500                continue;
3501            }
3502
3503            if (DEBUG_EPHEMERAL) {
3504                Slog.v(TAG, "Ephemeral resolver found;"
3505                        + " pkg: " + packageName + ", info:" + info);
3506            }
3507            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3508        }
3509        if (DEBUG_EPHEMERAL) {
3510            Slog.v(TAG, "Ephemeral resolver NOT found");
3511        }
3512        return null;
3513    }
3514
3515    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3516        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3517        intent.addCategory(Intent.CATEGORY_DEFAULT);
3518        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3519
3520        final int resolveFlags =
3521                MATCH_DIRECT_BOOT_AWARE
3522                | MATCH_DIRECT_BOOT_UNAWARE
3523                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3524        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3525                resolveFlags, UserHandle.USER_SYSTEM);
3526        // temporarily look for the old action
3527        if (matches.isEmpty()) {
3528            if (DEBUG_EPHEMERAL) {
3529                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3530            }
3531            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3532            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3533                    resolveFlags, UserHandle.USER_SYSTEM);
3534        }
3535        Iterator<ResolveInfo> iter = matches.iterator();
3536        while (iter.hasNext()) {
3537            final ResolveInfo rInfo = iter.next();
3538            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3539            if (ps != null) {
3540                final PermissionsState permissionsState = ps.getPermissionsState();
3541                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3542                    continue;
3543                }
3544            }
3545            iter.remove();
3546        }
3547        if (matches.size() == 0) {
3548            return null;
3549        } else if (matches.size() == 1) {
3550            return (ActivityInfo) matches.get(0).getComponentInfo();
3551        } else {
3552            throw new RuntimeException(
3553                    "There must be at most one ephemeral installer; found " + matches);
3554        }
3555    }
3556
3557    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3558            @NonNull ComponentName resolver) {
3559        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3560                .addCategory(Intent.CATEGORY_DEFAULT)
3561                .setPackage(resolver.getPackageName());
3562        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3563        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3564                UserHandle.USER_SYSTEM);
3565        // temporarily look for the old action
3566        if (matches.isEmpty()) {
3567            if (DEBUG_EPHEMERAL) {
3568                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3569            }
3570            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3571            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3572                    UserHandle.USER_SYSTEM);
3573        }
3574        if (matches.isEmpty()) {
3575            return null;
3576        }
3577        return matches.get(0).getComponentInfo().getComponentName();
3578    }
3579
3580    private void primeDomainVerificationsLPw(int userId) {
3581        if (DEBUG_DOMAIN_VERIFICATION) {
3582            Slog.d(TAG, "Priming domain verifications in user " + userId);
3583        }
3584
3585        SystemConfig systemConfig = SystemConfig.getInstance();
3586        ArraySet<String> packages = systemConfig.getLinkedApps();
3587
3588        for (String packageName : packages) {
3589            PackageParser.Package pkg = mPackages.get(packageName);
3590            if (pkg != null) {
3591                if (!pkg.isSystemApp()) {
3592                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3593                    continue;
3594                }
3595
3596                ArraySet<String> domains = null;
3597                for (PackageParser.Activity a : pkg.activities) {
3598                    for (ActivityIntentInfo filter : a.intents) {
3599                        if (hasValidDomains(filter)) {
3600                            if (domains == null) {
3601                                domains = new ArraySet<String>();
3602                            }
3603                            domains.addAll(filter.getHostsList());
3604                        }
3605                    }
3606                }
3607
3608                if (domains != null && domains.size() > 0) {
3609                    if (DEBUG_DOMAIN_VERIFICATION) {
3610                        Slog.v(TAG, "      + " + packageName);
3611                    }
3612                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3613                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3614                    // and then 'always' in the per-user state actually used for intent resolution.
3615                    final IntentFilterVerificationInfo ivi;
3616                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3617                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3618                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3619                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3620                } else {
3621                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3622                            + "' does not handle web links");
3623                }
3624            } else {
3625                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3626            }
3627        }
3628
3629        scheduleWritePackageRestrictionsLocked(userId);
3630        scheduleWriteSettingsLocked();
3631    }
3632
3633    private void applyFactoryDefaultBrowserLPw(int userId) {
3634        // The default browser app's package name is stored in a string resource,
3635        // with a product-specific overlay used for vendor customization.
3636        String browserPkg = mContext.getResources().getString(
3637                com.android.internal.R.string.default_browser);
3638        if (!TextUtils.isEmpty(browserPkg)) {
3639            // non-empty string => required to be a known package
3640            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3641            if (ps == null) {
3642                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3643                browserPkg = null;
3644            } else {
3645                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3646            }
3647        }
3648
3649        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3650        // default.  If there's more than one, just leave everything alone.
3651        if (browserPkg == null) {
3652            calculateDefaultBrowserLPw(userId);
3653        }
3654    }
3655
3656    private void calculateDefaultBrowserLPw(int userId) {
3657        List<String> allBrowsers = resolveAllBrowserApps(userId);
3658        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3659        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3660    }
3661
3662    private List<String> resolveAllBrowserApps(int userId) {
3663        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3664        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3665                PackageManager.MATCH_ALL, userId);
3666
3667        final int count = list.size();
3668        List<String> result = new ArrayList<String>(count);
3669        for (int i=0; i<count; i++) {
3670            ResolveInfo info = list.get(i);
3671            if (info.activityInfo == null
3672                    || !info.handleAllWebDataURI
3673                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3674                    || result.contains(info.activityInfo.packageName)) {
3675                continue;
3676            }
3677            result.add(info.activityInfo.packageName);
3678        }
3679
3680        return result;
3681    }
3682
3683    private boolean packageIsBrowser(String packageName, int userId) {
3684        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3685                PackageManager.MATCH_ALL, userId);
3686        final int N = list.size();
3687        for (int i = 0; i < N; i++) {
3688            ResolveInfo info = list.get(i);
3689            if (packageName.equals(info.activityInfo.packageName)) {
3690                return true;
3691            }
3692        }
3693        return false;
3694    }
3695
3696    private void checkDefaultBrowser() {
3697        final int myUserId = UserHandle.myUserId();
3698        final String packageName = getDefaultBrowserPackageName(myUserId);
3699        if (packageName != null) {
3700            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3701            if (info == null) {
3702                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3703                synchronized (mPackages) {
3704                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3705                }
3706            }
3707        }
3708    }
3709
3710    @Override
3711    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3712            throws RemoteException {
3713        try {
3714            return super.onTransact(code, data, reply, flags);
3715        } catch (RuntimeException e) {
3716            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3717                Slog.wtf(TAG, "Package Manager Crash", e);
3718            }
3719            throw e;
3720        }
3721    }
3722
3723    static int[] appendInts(int[] cur, int[] add) {
3724        if (add == null) return cur;
3725        if (cur == null) return add;
3726        final int N = add.length;
3727        for (int i=0; i<N; i++) {
3728            cur = appendInt(cur, add[i]);
3729        }
3730        return cur;
3731    }
3732
3733    /**
3734     * Returns whether or not a full application can see an instant application.
3735     * <p>
3736     * Currently, there are three cases in which this can occur:
3737     * <ol>
3738     * <li>The calling application is a "special" process. The special
3739     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3740     *     and {@code 0}</li>
3741     * <li>The calling application has the permission
3742     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3743     * <li>The calling application is the default launcher on the
3744     *     system partition.</li>
3745     * </ol>
3746     */
3747    private boolean canViewInstantApps(int callingUid, int userId) {
3748        if (callingUid == Process.SYSTEM_UID
3749                || callingUid == Process.SHELL_UID
3750                || callingUid == Process.ROOT_UID) {
3751            return true;
3752        }
3753        if (mContext.checkCallingOrSelfPermission(
3754                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3755            return true;
3756        }
3757        if (mContext.checkCallingOrSelfPermission(
3758                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3759            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3760            if (homeComponent != null
3761                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3762                return true;
3763            }
3764        }
3765        return false;
3766    }
3767
3768    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3769        if (!sUserManager.exists(userId)) return null;
3770        if (ps == null) {
3771            return null;
3772        }
3773        PackageParser.Package p = ps.pkg;
3774        if (p == null) {
3775            return null;
3776        }
3777        final int callingUid = Binder.getCallingUid();
3778        // Filter out ephemeral app metadata:
3779        //   * The system/shell/root can see metadata for any app
3780        //   * An installed app can see metadata for 1) other installed apps
3781        //     and 2) ephemeral apps that have explicitly interacted with it
3782        //   * Ephemeral apps can only see their own data and exposed installed apps
3783        //   * Holding a signature permission allows seeing instant apps
3784        if (filterAppAccessLPr(ps, callingUid, userId)) {
3785            return null;
3786        }
3787
3788        final PermissionsState permissionsState = ps.getPermissionsState();
3789
3790        // Compute GIDs only if requested
3791        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3792                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3793        // Compute granted permissions only if package has requested permissions
3794        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3795                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3796        final PackageUserState state = ps.readUserState(userId);
3797
3798        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3799                && ps.isSystem()) {
3800            flags |= MATCH_ANY_USER;
3801        }
3802
3803        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3804                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3805
3806        if (packageInfo == null) {
3807            return null;
3808        }
3809
3810        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3811                resolveExternalPackageNameLPr(p);
3812
3813        return packageInfo;
3814    }
3815
3816    @Override
3817    public void checkPackageStartable(String packageName, int userId) {
3818        final int callingUid = Binder.getCallingUid();
3819        if (getInstantAppPackageName(callingUid) != null) {
3820            throw new SecurityException("Instant applications don't have access to this method");
3821        }
3822        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3823        synchronized (mPackages) {
3824            final PackageSetting ps = mSettings.mPackages.get(packageName);
3825            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3826                throw new SecurityException("Package " + packageName + " was not found!");
3827            }
3828
3829            if (!ps.getInstalled(userId)) {
3830                throw new SecurityException(
3831                        "Package " + packageName + " was not installed for user " + userId + "!");
3832            }
3833
3834            if (mSafeMode && !ps.isSystem()) {
3835                throw new SecurityException("Package " + packageName + " not a system app!");
3836            }
3837
3838            if (mFrozenPackages.contains(packageName)) {
3839                throw new SecurityException("Package " + packageName + " is currently frozen!");
3840            }
3841
3842            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3843                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3844            }
3845        }
3846    }
3847
3848    @Override
3849    public boolean isPackageAvailable(String packageName, int userId) {
3850        if (!sUserManager.exists(userId)) return false;
3851        final int callingUid = Binder.getCallingUid();
3852        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3853                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3854        synchronized (mPackages) {
3855            PackageParser.Package p = mPackages.get(packageName);
3856            if (p != null) {
3857                final PackageSetting ps = (PackageSetting) p.mExtras;
3858                if (filterAppAccessLPr(ps, callingUid, userId)) {
3859                    return false;
3860                }
3861                if (ps != null) {
3862                    final PackageUserState state = ps.readUserState(userId);
3863                    if (state != null) {
3864                        return PackageParser.isAvailable(state);
3865                    }
3866                }
3867            }
3868        }
3869        return false;
3870    }
3871
3872    @Override
3873    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3874        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3875                flags, Binder.getCallingUid(), userId);
3876    }
3877
3878    @Override
3879    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3880            int flags, int userId) {
3881        return getPackageInfoInternal(versionedPackage.getPackageName(),
3882                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3883    }
3884
3885    /**
3886     * Important: The provided filterCallingUid is used exclusively to filter out packages
3887     * that can be seen based on user state. It's typically the original caller uid prior
3888     * to clearing. Because it can only be provided by trusted code, it's value can be
3889     * trusted and will be used as-is; unlike userId which will be validated by this method.
3890     */
3891    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3892            int flags, int filterCallingUid, int userId) {
3893        if (!sUserManager.exists(userId)) return null;
3894        flags = updateFlagsForPackage(flags, userId, packageName);
3895        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3896                false /* requireFullPermission */, false /* checkShell */, "get package info");
3897
3898        // reader
3899        synchronized (mPackages) {
3900            // Normalize package name to handle renamed packages and static libs
3901            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3902
3903            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3904            if (matchFactoryOnly) {
3905                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3906                if (ps != null) {
3907                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3908                        return null;
3909                    }
3910                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3911                        return null;
3912                    }
3913                    return generatePackageInfo(ps, flags, userId);
3914                }
3915            }
3916
3917            PackageParser.Package p = mPackages.get(packageName);
3918            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3919                return null;
3920            }
3921            if (DEBUG_PACKAGE_INFO)
3922                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3923            if (p != null) {
3924                final PackageSetting ps = (PackageSetting) p.mExtras;
3925                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3926                    return null;
3927                }
3928                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3929                    return null;
3930                }
3931                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3932            }
3933            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3934                final PackageSetting ps = mSettings.mPackages.get(packageName);
3935                if (ps == null) return null;
3936                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3937                    return null;
3938                }
3939                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3940                    return null;
3941                }
3942                return generatePackageInfo(ps, flags, userId);
3943            }
3944        }
3945        return null;
3946    }
3947
3948    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3949        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3950            return true;
3951        }
3952        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3953            return true;
3954        }
3955        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3956            return true;
3957        }
3958        return false;
3959    }
3960
3961    private boolean isComponentVisibleToInstantApp(
3962            @Nullable ComponentName component, @ComponentType int type) {
3963        if (type == TYPE_ACTIVITY) {
3964            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3965            return activity != null
3966                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3967                    : false;
3968        } else if (type == TYPE_RECEIVER) {
3969            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3970            return activity != null
3971                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3972                    : false;
3973        } else if (type == TYPE_SERVICE) {
3974            final PackageParser.Service service = mServices.mServices.get(component);
3975            return service != null
3976                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3977                    : false;
3978        } else if (type == TYPE_PROVIDER) {
3979            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3980            return provider != null
3981                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_UNKNOWN) {
3984            return isComponentVisibleToInstantApp(component);
3985        }
3986        return false;
3987    }
3988
3989    /**
3990     * Returns whether or not access to the application should be filtered.
3991     * <p>
3992     * Access may be limited based upon whether the calling or target applications
3993     * are instant applications.
3994     *
3995     * @see #canAccessInstantApps(int)
3996     */
3997    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3998            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3999        // if we're in an isolated process, get the real calling UID
4000        if (Process.isIsolated(callingUid)) {
4001            callingUid = mIsolatedOwners.get(callingUid);
4002        }
4003        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4004        final boolean callerIsInstantApp = instantAppPkgName != null;
4005        if (ps == null) {
4006            if (callerIsInstantApp) {
4007                // pretend the application exists, but, needs to be filtered
4008                return true;
4009            }
4010            return false;
4011        }
4012        // if the target and caller are the same application, don't filter
4013        if (isCallerSameApp(ps.name, callingUid)) {
4014            return false;
4015        }
4016        if (callerIsInstantApp) {
4017            // request for a specific component; if it hasn't been explicitly exposed, filter
4018            if (component != null) {
4019                return !isComponentVisibleToInstantApp(component, componentType);
4020            }
4021            // request for application; if no components have been explicitly exposed, filter
4022            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4023        }
4024        if (ps.getInstantApp(userId)) {
4025            // caller can see all components of all instant applications, don't filter
4026            if (canViewInstantApps(callingUid, userId)) {
4027                return false;
4028            }
4029            // request for a specific instant application component, filter
4030            if (component != null) {
4031                return true;
4032            }
4033            // request for an instant application; if the caller hasn't been granted access, filter
4034            return !mInstantAppRegistry.isInstantAccessGranted(
4035                    userId, UserHandle.getAppId(callingUid), ps.appId);
4036        }
4037        return false;
4038    }
4039
4040    /**
4041     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4042     */
4043    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4044        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4045    }
4046
4047    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4048            int flags) {
4049        // Callers can access only the libs they depend on, otherwise they need to explicitly
4050        // ask for the shared libraries given the caller is allowed to access all static libs.
4051        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4052            // System/shell/root get to see all static libs
4053            final int appId = UserHandle.getAppId(uid);
4054            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4055                    || appId == Process.ROOT_UID) {
4056                return false;
4057            }
4058        }
4059
4060        // No package means no static lib as it is always on internal storage
4061        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4062            return false;
4063        }
4064
4065        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4066                ps.pkg.staticSharedLibVersion);
4067        if (libEntry == null) {
4068            return false;
4069        }
4070
4071        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4072        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4073        if (uidPackageNames == null) {
4074            return true;
4075        }
4076
4077        for (String uidPackageName : uidPackageNames) {
4078            if (ps.name.equals(uidPackageName)) {
4079                return false;
4080            }
4081            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4082            if (uidPs != null) {
4083                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4084                        libEntry.info.getName());
4085                if (index < 0) {
4086                    continue;
4087                }
4088                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4089                    return false;
4090                }
4091            }
4092        }
4093        return true;
4094    }
4095
4096    @Override
4097    public String[] currentToCanonicalPackageNames(String[] names) {
4098        final int callingUid = Binder.getCallingUid();
4099        if (getInstantAppPackageName(callingUid) != null) {
4100            return names;
4101        }
4102        final String[] out = new String[names.length];
4103        // reader
4104        synchronized (mPackages) {
4105            final int callingUserId = UserHandle.getUserId(callingUid);
4106            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4107            for (int i=names.length-1; i>=0; i--) {
4108                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4109                boolean translateName = false;
4110                if (ps != null && ps.realName != null) {
4111                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4112                    translateName = !targetIsInstantApp
4113                            || canViewInstantApps
4114                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4115                                    UserHandle.getAppId(callingUid), ps.appId);
4116                }
4117                out[i] = translateName ? ps.realName : names[i];
4118            }
4119        }
4120        return out;
4121    }
4122
4123    @Override
4124    public String[] canonicalToCurrentPackageNames(String[] names) {
4125        final int callingUid = Binder.getCallingUid();
4126        if (getInstantAppPackageName(callingUid) != null) {
4127            return names;
4128        }
4129        final String[] out = new String[names.length];
4130        // reader
4131        synchronized (mPackages) {
4132            final int callingUserId = UserHandle.getUserId(callingUid);
4133            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4134            for (int i=names.length-1; i>=0; i--) {
4135                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4136                boolean translateName = false;
4137                if (cur != null) {
4138                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4139                    final boolean targetIsInstantApp =
4140                            ps != null && ps.getInstantApp(callingUserId);
4141                    translateName = !targetIsInstantApp
4142                            || canViewInstantApps
4143                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4144                                    UserHandle.getAppId(callingUid), ps.appId);
4145                }
4146                out[i] = translateName ? cur : names[i];
4147            }
4148        }
4149        return out;
4150    }
4151
4152    @Override
4153    public int getPackageUid(String packageName, int flags, int userId) {
4154        if (!sUserManager.exists(userId)) return -1;
4155        final int callingUid = Binder.getCallingUid();
4156        flags = updateFlagsForPackage(flags, userId, packageName);
4157        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4158                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4159
4160        // reader
4161        synchronized (mPackages) {
4162            final PackageParser.Package p = mPackages.get(packageName);
4163            if (p != null && p.isMatch(flags)) {
4164                PackageSetting ps = (PackageSetting) p.mExtras;
4165                if (filterAppAccessLPr(ps, callingUid, userId)) {
4166                    return -1;
4167                }
4168                return UserHandle.getUid(userId, p.applicationInfo.uid);
4169            }
4170            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4171                final PackageSetting ps = mSettings.mPackages.get(packageName);
4172                if (ps != null && ps.isMatch(flags)
4173                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4174                    return UserHandle.getUid(userId, ps.appId);
4175                }
4176            }
4177        }
4178
4179        return -1;
4180    }
4181
4182    @Override
4183    public int[] getPackageGids(String packageName, int flags, int userId) {
4184        if (!sUserManager.exists(userId)) return null;
4185        final int callingUid = Binder.getCallingUid();
4186        flags = updateFlagsForPackage(flags, userId, packageName);
4187        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4188                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4189
4190        // reader
4191        synchronized (mPackages) {
4192            final PackageParser.Package p = mPackages.get(packageName);
4193            if (p != null && p.isMatch(flags)) {
4194                PackageSetting ps = (PackageSetting) p.mExtras;
4195                if (filterAppAccessLPr(ps, callingUid, userId)) {
4196                    return null;
4197                }
4198                // TODO: Shouldn't this be checking for package installed state for userId and
4199                // return null?
4200                return ps.getPermissionsState().computeGids(userId);
4201            }
4202            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4203                final PackageSetting ps = mSettings.mPackages.get(packageName);
4204                if (ps != null && ps.isMatch(flags)
4205                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4206                    return ps.getPermissionsState().computeGids(userId);
4207                }
4208            }
4209        }
4210
4211        return null;
4212    }
4213
4214    @Override
4215    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4216        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4217    }
4218
4219    @Override
4220    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4221            int flags) {
4222        final List<PermissionInfo> permissionList =
4223                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4224        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4225    }
4226
4227    @Override
4228    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4229        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4230    }
4231
4232    @Override
4233    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4234        final List<PermissionGroupInfo> permissionList =
4235                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4236        return (permissionList == null)
4237                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4238    }
4239
4240    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4241            int filterCallingUid, int userId) {
4242        if (!sUserManager.exists(userId)) return null;
4243        PackageSetting ps = mSettings.mPackages.get(packageName);
4244        if (ps != null) {
4245            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4246                return null;
4247            }
4248            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4249                return null;
4250            }
4251            if (ps.pkg == null) {
4252                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4253                if (pInfo != null) {
4254                    return pInfo.applicationInfo;
4255                }
4256                return null;
4257            }
4258            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4259                    ps.readUserState(userId), userId);
4260            if (ai != null) {
4261                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4262            }
4263            return ai;
4264        }
4265        return null;
4266    }
4267
4268    @Override
4269    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4270        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4271    }
4272
4273    /**
4274     * Important: The provided filterCallingUid is used exclusively to filter out applications
4275     * that can be seen based on user state. It's typically the original caller uid prior
4276     * to clearing. Because it can only be provided by trusted code, it's value can be
4277     * trusted and will be used as-is; unlike userId which will be validated by this method.
4278     */
4279    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4280            int filterCallingUid, int userId) {
4281        if (!sUserManager.exists(userId)) return null;
4282        flags = updateFlagsForApplication(flags, userId, packageName);
4283        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4284                false /* requireFullPermission */, false /* checkShell */, "get application info");
4285
4286        // writer
4287        synchronized (mPackages) {
4288            // Normalize package name to handle renamed packages and static libs
4289            packageName = resolveInternalPackageNameLPr(packageName,
4290                    PackageManager.VERSION_CODE_HIGHEST);
4291
4292            PackageParser.Package p = mPackages.get(packageName);
4293            if (DEBUG_PACKAGE_INFO) Log.v(
4294                    TAG, "getApplicationInfo " + packageName
4295                    + ": " + p);
4296            if (p != null) {
4297                PackageSetting ps = mSettings.mPackages.get(packageName);
4298                if (ps == null) return null;
4299                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4300                    return null;
4301                }
4302                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4303                    return null;
4304                }
4305                // Note: isEnabledLP() does not apply here - always return info
4306                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4307                        p, flags, ps.readUserState(userId), userId);
4308                if (ai != null) {
4309                    ai.packageName = resolveExternalPackageNameLPr(p);
4310                }
4311                return ai;
4312            }
4313            if ("android".equals(packageName)||"system".equals(packageName)) {
4314                return mAndroidApplication;
4315            }
4316            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4317                // Already generates the external package name
4318                return generateApplicationInfoFromSettingsLPw(packageName,
4319                        flags, filterCallingUid, userId);
4320            }
4321        }
4322        return null;
4323    }
4324
4325    private String normalizePackageNameLPr(String packageName) {
4326        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4327        return normalizedPackageName != null ? normalizedPackageName : packageName;
4328    }
4329
4330    @Override
4331    public void deletePreloadsFileCache() {
4332        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4333            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4334        }
4335        File dir = Environment.getDataPreloadsFileCacheDirectory();
4336        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4337        FileUtils.deleteContents(dir);
4338    }
4339
4340    @Override
4341    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4342            final int storageFlags, final IPackageDataObserver observer) {
4343        mContext.enforceCallingOrSelfPermission(
4344                android.Manifest.permission.CLEAR_APP_CACHE, null);
4345        mHandler.post(() -> {
4346            boolean success = false;
4347            try {
4348                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4349                success = true;
4350            } catch (IOException e) {
4351                Slog.w(TAG, e);
4352            }
4353            if (observer != null) {
4354                try {
4355                    observer.onRemoveCompleted(null, success);
4356                } catch (RemoteException e) {
4357                    Slog.w(TAG, e);
4358                }
4359            }
4360        });
4361    }
4362
4363    @Override
4364    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4365            final int storageFlags, final IntentSender pi) {
4366        mContext.enforceCallingOrSelfPermission(
4367                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4368        mHandler.post(() -> {
4369            boolean success = false;
4370            try {
4371                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4372                success = true;
4373            } catch (IOException e) {
4374                Slog.w(TAG, e);
4375            }
4376            if (pi != null) {
4377                try {
4378                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4379                } catch (SendIntentException e) {
4380                    Slog.w(TAG, e);
4381                }
4382            }
4383        });
4384    }
4385
4386    /**
4387     * Blocking call to clear various types of cached data across the system
4388     * until the requested bytes are available.
4389     */
4390    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4391        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4392        final File file = storage.findPathForUuid(volumeUuid);
4393        if (file.getUsableSpace() >= bytes) return;
4394
4395        if (ENABLE_FREE_CACHE_V2) {
4396            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4397                    volumeUuid);
4398            final boolean aggressive = (storageFlags
4399                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4400            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4401
4402            // 1. Pre-flight to determine if we have any chance to succeed
4403            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4404            if (internalVolume && (aggressive || SystemProperties
4405                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4406                deletePreloadsFileCache();
4407                if (file.getUsableSpace() >= bytes) return;
4408            }
4409
4410            // 3. Consider parsed APK data (aggressive only)
4411            if (internalVolume && aggressive) {
4412                FileUtils.deleteContents(mCacheDir);
4413                if (file.getUsableSpace() >= bytes) return;
4414            }
4415
4416            // 4. Consider cached app data (above quotas)
4417            try {
4418                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4419                        Installer.FLAG_FREE_CACHE_V2);
4420            } catch (InstallerException ignored) {
4421            }
4422            if (file.getUsableSpace() >= bytes) return;
4423
4424            // 5. Consider shared libraries with refcount=0 and age>min cache period
4425            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4426                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4427                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4428                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4429                return;
4430            }
4431
4432            // 6. Consider dexopt output (aggressive only)
4433            // TODO: Implement
4434
4435            // 7. Consider installed instant apps unused longer than min cache period
4436            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4437                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4438                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4439                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4440                return;
4441            }
4442
4443            // 8. Consider cached app data (below quotas)
4444            try {
4445                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4446                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4447            } catch (InstallerException ignored) {
4448            }
4449            if (file.getUsableSpace() >= bytes) return;
4450
4451            // 9. Consider DropBox entries
4452            // TODO: Implement
4453
4454            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4455            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4456                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4457                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4458                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4459                return;
4460            }
4461        } else {
4462            try {
4463                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4464            } catch (InstallerException ignored) {
4465            }
4466            if (file.getUsableSpace() >= bytes) return;
4467        }
4468
4469        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4470    }
4471
4472    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4473            throws IOException {
4474        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4475        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4476
4477        List<VersionedPackage> packagesToDelete = null;
4478        final long now = System.currentTimeMillis();
4479
4480        synchronized (mPackages) {
4481            final int[] allUsers = sUserManager.getUserIds();
4482            final int libCount = mSharedLibraries.size();
4483            for (int i = 0; i < libCount; i++) {
4484                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4485                if (versionedLib == null) {
4486                    continue;
4487                }
4488                final int versionCount = versionedLib.size();
4489                for (int j = 0; j < versionCount; j++) {
4490                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4491                    // Skip packages that are not static shared libs.
4492                    if (!libInfo.isStatic()) {
4493                        break;
4494                    }
4495                    // Important: We skip static shared libs used for some user since
4496                    // in such a case we need to keep the APK on the device. The check for
4497                    // a lib being used for any user is performed by the uninstall call.
4498                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4499                    // Resolve the package name - we use synthetic package names internally
4500                    final String internalPackageName = resolveInternalPackageNameLPr(
4501                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4502                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4503                    // Skip unused static shared libs cached less than the min period
4504                    // to prevent pruning a lib needed by a subsequently installed package.
4505                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4506                        continue;
4507                    }
4508                    if (packagesToDelete == null) {
4509                        packagesToDelete = new ArrayList<>();
4510                    }
4511                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4512                            declaringPackage.getVersionCode()));
4513                }
4514            }
4515        }
4516
4517        if (packagesToDelete != null) {
4518            final int packageCount = packagesToDelete.size();
4519            for (int i = 0; i < packageCount; i++) {
4520                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4521                // Delete the package synchronously (will fail of the lib used for any user).
4522                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4523                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4524                                == PackageManager.DELETE_SUCCEEDED) {
4525                    if (volume.getUsableSpace() >= neededSpace) {
4526                        return true;
4527                    }
4528                }
4529            }
4530        }
4531
4532        return false;
4533    }
4534
4535    /**
4536     * Update given flags based on encryption status of current user.
4537     */
4538    private int updateFlags(int flags, int userId) {
4539        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4540                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4541            // Caller expressed an explicit opinion about what encryption
4542            // aware/unaware components they want to see, so fall through and
4543            // give them what they want
4544        } else {
4545            // Caller expressed no opinion, so match based on user state
4546            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4547                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4548            } else {
4549                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4550            }
4551        }
4552        return flags;
4553    }
4554
4555    private UserManagerInternal getUserManagerInternal() {
4556        if (mUserManagerInternal == null) {
4557            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4558        }
4559        return mUserManagerInternal;
4560    }
4561
4562    private DeviceIdleController.LocalService getDeviceIdleController() {
4563        if (mDeviceIdleController == null) {
4564            mDeviceIdleController =
4565                    LocalServices.getService(DeviceIdleController.LocalService.class);
4566        }
4567        return mDeviceIdleController;
4568    }
4569
4570    /**
4571     * Update given flags when being used to request {@link PackageInfo}.
4572     */
4573    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4574        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4575        boolean triaged = true;
4576        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4577                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4578            // Caller is asking for component details, so they'd better be
4579            // asking for specific encryption matching behavior, or be triaged
4580            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4581                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4582                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4583                triaged = false;
4584            }
4585        }
4586        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4587                | PackageManager.MATCH_SYSTEM_ONLY
4588                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4589            triaged = false;
4590        }
4591        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4592            mPermissionManager.enforceCrossUserPermission(
4593                    Binder.getCallingUid(), userId, false, false,
4594                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4595                    + Debug.getCallers(5));
4596        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4597                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4598            // If the caller wants all packages and has a restricted profile associated with it,
4599            // then match all users. This is to make sure that launchers that need to access work
4600            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4601            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4602            flags |= PackageManager.MATCH_ANY_USER;
4603        }
4604        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4605            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4606                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4607        }
4608        return updateFlags(flags, userId);
4609    }
4610
4611    /**
4612     * Update given flags when being used to request {@link ApplicationInfo}.
4613     */
4614    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4615        return updateFlagsForPackage(flags, userId, cookie);
4616    }
4617
4618    /**
4619     * Update given flags when being used to request {@link ComponentInfo}.
4620     */
4621    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4622        if (cookie instanceof Intent) {
4623            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4624                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4625            }
4626        }
4627
4628        boolean triaged = true;
4629        // Caller is asking for component details, so they'd better be
4630        // asking for specific encryption matching behavior, or be triaged
4631        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4632                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4633                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4634            triaged = false;
4635        }
4636        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4637            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4638                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4639        }
4640
4641        return updateFlags(flags, userId);
4642    }
4643
4644    /**
4645     * Update given intent when being used to request {@link ResolveInfo}.
4646     */
4647    private Intent updateIntentForResolve(Intent intent) {
4648        if (intent.getSelector() != null) {
4649            intent = intent.getSelector();
4650        }
4651        if (DEBUG_PREFERRED) {
4652            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4653        }
4654        return intent;
4655    }
4656
4657    /**
4658     * Update given flags when being used to request {@link ResolveInfo}.
4659     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4660     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4661     * flag set. However, this flag is only honoured in three circumstances:
4662     * <ul>
4663     * <li>when called from a system process</li>
4664     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4665     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4666     * action and a {@code android.intent.category.BROWSABLE} category</li>
4667     * </ul>
4668     */
4669    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4670        return updateFlagsForResolve(flags, userId, intent, callingUid,
4671                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4672    }
4673    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4674            boolean wantInstantApps) {
4675        return updateFlagsForResolve(flags, userId, intent, callingUid,
4676                wantInstantApps, false /*onlyExposedExplicitly*/);
4677    }
4678    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4679            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4680        // Safe mode means we shouldn't match any third-party components
4681        if (mSafeMode) {
4682            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4683        }
4684        if (getInstantAppPackageName(callingUid) != null) {
4685            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4686            if (onlyExposedExplicitly) {
4687                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4688            }
4689            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4690            flags |= PackageManager.MATCH_INSTANT;
4691        } else {
4692            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4693            final boolean allowMatchInstant =
4694                    (wantInstantApps
4695                            && Intent.ACTION_VIEW.equals(intent.getAction())
4696                            && hasWebURI(intent))
4697                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4698            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4699                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4700            if (!allowMatchInstant) {
4701                flags &= ~PackageManager.MATCH_INSTANT;
4702            }
4703        }
4704        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4705    }
4706
4707    @Override
4708    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4709        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4710    }
4711
4712    /**
4713     * Important: The provided filterCallingUid is used exclusively to filter out activities
4714     * that can be seen based on user state. It's typically the original caller uid prior
4715     * to clearing. Because it can only be provided by trusted code, it's value can be
4716     * trusted and will be used as-is; unlike userId which will be validated by this method.
4717     */
4718    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4719            int filterCallingUid, int userId) {
4720        if (!sUserManager.exists(userId)) return null;
4721        flags = updateFlagsForComponent(flags, userId, component);
4722        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4723                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4724        synchronized (mPackages) {
4725            PackageParser.Activity a = mActivities.mActivities.get(component);
4726
4727            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4728            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4729                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4730                if (ps == null) return null;
4731                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4732                    return null;
4733                }
4734                return PackageParser.generateActivityInfo(
4735                        a, flags, ps.readUserState(userId), userId);
4736            }
4737            if (mResolveComponentName.equals(component)) {
4738                return PackageParser.generateActivityInfo(
4739                        mResolveActivity, flags, new PackageUserState(), userId);
4740            }
4741        }
4742        return null;
4743    }
4744
4745    @Override
4746    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4747            String resolvedType) {
4748        synchronized (mPackages) {
4749            if (component.equals(mResolveComponentName)) {
4750                // The resolver supports EVERYTHING!
4751                return true;
4752            }
4753            final int callingUid = Binder.getCallingUid();
4754            final int callingUserId = UserHandle.getUserId(callingUid);
4755            PackageParser.Activity a = mActivities.mActivities.get(component);
4756            if (a == null) {
4757                return false;
4758            }
4759            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4760            if (ps == null) {
4761                return false;
4762            }
4763            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4764                return false;
4765            }
4766            for (int i=0; i<a.intents.size(); i++) {
4767                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4768                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4769                    return true;
4770                }
4771            }
4772            return false;
4773        }
4774    }
4775
4776    @Override
4777    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4778        if (!sUserManager.exists(userId)) return null;
4779        final int callingUid = Binder.getCallingUid();
4780        flags = updateFlagsForComponent(flags, userId, component);
4781        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4782                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4783        synchronized (mPackages) {
4784            PackageParser.Activity a = mReceivers.mActivities.get(component);
4785            if (DEBUG_PACKAGE_INFO) Log.v(
4786                TAG, "getReceiverInfo " + component + ": " + a);
4787            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4788                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4789                if (ps == null) return null;
4790                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4791                    return null;
4792                }
4793                return PackageParser.generateActivityInfo(
4794                        a, flags, ps.readUserState(userId), userId);
4795            }
4796        }
4797        return null;
4798    }
4799
4800    @Override
4801    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4802            int flags, int userId) {
4803        if (!sUserManager.exists(userId)) return null;
4804        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4805        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4806            return null;
4807        }
4808
4809        flags = updateFlagsForPackage(flags, userId, null);
4810
4811        final boolean canSeeStaticLibraries =
4812                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4813                        == PERMISSION_GRANTED
4814                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4815                        == PERMISSION_GRANTED
4816                || canRequestPackageInstallsInternal(packageName,
4817                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4818                        false  /* throwIfPermNotDeclared*/)
4819                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4820                        == PERMISSION_GRANTED;
4821
4822        synchronized (mPackages) {
4823            List<SharedLibraryInfo> result = null;
4824
4825            final int libCount = mSharedLibraries.size();
4826            for (int i = 0; i < libCount; i++) {
4827                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4828                if (versionedLib == null) {
4829                    continue;
4830                }
4831
4832                final int versionCount = versionedLib.size();
4833                for (int j = 0; j < versionCount; j++) {
4834                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4835                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4836                        break;
4837                    }
4838                    final long identity = Binder.clearCallingIdentity();
4839                    try {
4840                        PackageInfo packageInfo = getPackageInfoVersioned(
4841                                libInfo.getDeclaringPackage(), flags
4842                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4843                        if (packageInfo == null) {
4844                            continue;
4845                        }
4846                    } finally {
4847                        Binder.restoreCallingIdentity(identity);
4848                    }
4849
4850                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4851                            libInfo.getVersion(), libInfo.getType(),
4852                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4853                            flags, userId));
4854
4855                    if (result == null) {
4856                        result = new ArrayList<>();
4857                    }
4858                    result.add(resLibInfo);
4859                }
4860            }
4861
4862            return result != null ? new ParceledListSlice<>(result) : null;
4863        }
4864    }
4865
4866    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4867            SharedLibraryInfo libInfo, int flags, int userId) {
4868        List<VersionedPackage> versionedPackages = null;
4869        final int packageCount = mSettings.mPackages.size();
4870        for (int i = 0; i < packageCount; i++) {
4871            PackageSetting ps = mSettings.mPackages.valueAt(i);
4872
4873            if (ps == null) {
4874                continue;
4875            }
4876
4877            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4878                continue;
4879            }
4880
4881            final String libName = libInfo.getName();
4882            if (libInfo.isStatic()) {
4883                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4884                if (libIdx < 0) {
4885                    continue;
4886                }
4887                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4888                    continue;
4889                }
4890                if (versionedPackages == null) {
4891                    versionedPackages = new ArrayList<>();
4892                }
4893                // If the dependent is a static shared lib, use the public package name
4894                String dependentPackageName = ps.name;
4895                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4896                    dependentPackageName = ps.pkg.manifestPackageName;
4897                }
4898                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4899            } else if (ps.pkg != null) {
4900                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4901                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4902                    if (versionedPackages == null) {
4903                        versionedPackages = new ArrayList<>();
4904                    }
4905                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4906                }
4907            }
4908        }
4909
4910        return versionedPackages;
4911    }
4912
4913    @Override
4914    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4915        if (!sUserManager.exists(userId)) return null;
4916        final int callingUid = Binder.getCallingUid();
4917        flags = updateFlagsForComponent(flags, userId, component);
4918        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4919                false /* requireFullPermission */, false /* checkShell */, "get service info");
4920        synchronized (mPackages) {
4921            PackageParser.Service s = mServices.mServices.get(component);
4922            if (DEBUG_PACKAGE_INFO) Log.v(
4923                TAG, "getServiceInfo " + component + ": " + s);
4924            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4925                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4926                if (ps == null) return null;
4927                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4928                    return null;
4929                }
4930                return PackageParser.generateServiceInfo(
4931                        s, flags, ps.readUserState(userId), userId);
4932            }
4933        }
4934        return null;
4935    }
4936
4937    @Override
4938    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4939        if (!sUserManager.exists(userId)) return null;
4940        final int callingUid = Binder.getCallingUid();
4941        flags = updateFlagsForComponent(flags, userId, component);
4942        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4943                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4944        synchronized (mPackages) {
4945            PackageParser.Provider p = mProviders.mProviders.get(component);
4946            if (DEBUG_PACKAGE_INFO) Log.v(
4947                TAG, "getProviderInfo " + component + ": " + p);
4948            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4949                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4950                if (ps == null) return null;
4951                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4952                    return null;
4953                }
4954                return PackageParser.generateProviderInfo(
4955                        p, flags, ps.readUserState(userId), userId);
4956            }
4957        }
4958        return null;
4959    }
4960
4961    @Override
4962    public String[] getSystemSharedLibraryNames() {
4963        // allow instant applications
4964        synchronized (mPackages) {
4965            Set<String> libs = null;
4966            final int libCount = mSharedLibraries.size();
4967            for (int i = 0; i < libCount; i++) {
4968                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4969                if (versionedLib == null) {
4970                    continue;
4971                }
4972                final int versionCount = versionedLib.size();
4973                for (int j = 0; j < versionCount; j++) {
4974                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4975                    if (!libEntry.info.isStatic()) {
4976                        if (libs == null) {
4977                            libs = new ArraySet<>();
4978                        }
4979                        libs.add(libEntry.info.getName());
4980                        break;
4981                    }
4982                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4983                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4984                            UserHandle.getUserId(Binder.getCallingUid()),
4985                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4986                        if (libs == null) {
4987                            libs = new ArraySet<>();
4988                        }
4989                        libs.add(libEntry.info.getName());
4990                        break;
4991                    }
4992                }
4993            }
4994
4995            if (libs != null) {
4996                String[] libsArray = new String[libs.size()];
4997                libs.toArray(libsArray);
4998                return libsArray;
4999            }
5000
5001            return null;
5002        }
5003    }
5004
5005    @Override
5006    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5007        // allow instant applications
5008        synchronized (mPackages) {
5009            return mServicesSystemSharedLibraryPackageName;
5010        }
5011    }
5012
5013    @Override
5014    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5015        // allow instant applications
5016        synchronized (mPackages) {
5017            return mSharedSystemSharedLibraryPackageName;
5018        }
5019    }
5020
5021    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5022        for (int i = userList.length - 1; i >= 0; --i) {
5023            final int userId = userList[i];
5024            // don't add instant app to the list of updates
5025            if (pkgSetting.getInstantApp(userId)) {
5026                continue;
5027            }
5028            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5029            if (changedPackages == null) {
5030                changedPackages = new SparseArray<>();
5031                mChangedPackages.put(userId, changedPackages);
5032            }
5033            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5034            if (sequenceNumbers == null) {
5035                sequenceNumbers = new HashMap<>();
5036                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5037            }
5038            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5039            if (sequenceNumber != null) {
5040                changedPackages.remove(sequenceNumber);
5041            }
5042            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5043            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5044        }
5045        mChangedPackagesSequenceNumber++;
5046    }
5047
5048    @Override
5049    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5050        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5051            return null;
5052        }
5053        synchronized (mPackages) {
5054            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5055                return null;
5056            }
5057            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5058            if (changedPackages == null) {
5059                return null;
5060            }
5061            final List<String> packageNames =
5062                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5063            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5064                final String packageName = changedPackages.get(i);
5065                if (packageName != null) {
5066                    packageNames.add(packageName);
5067                }
5068            }
5069            return packageNames.isEmpty()
5070                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5071        }
5072    }
5073
5074    @Override
5075    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5076        // allow instant applications
5077        ArrayList<FeatureInfo> res;
5078        synchronized (mAvailableFeatures) {
5079            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5080            res.addAll(mAvailableFeatures.values());
5081        }
5082        final FeatureInfo fi = new FeatureInfo();
5083        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5084                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5085        res.add(fi);
5086
5087        return new ParceledListSlice<>(res);
5088    }
5089
5090    @Override
5091    public boolean hasSystemFeature(String name, int version) {
5092        // allow instant applications
5093        synchronized (mAvailableFeatures) {
5094            final FeatureInfo feat = mAvailableFeatures.get(name);
5095            if (feat == null) {
5096                return false;
5097            } else {
5098                return feat.version >= version;
5099            }
5100        }
5101    }
5102
5103    @Override
5104    public int checkPermission(String permName, String pkgName, int userId) {
5105        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5106    }
5107
5108    @Override
5109    public int checkUidPermission(String permName, int uid) {
5110        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5111    }
5112
5113    @Override
5114    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5115        if (UserHandle.getCallingUserId() != userId) {
5116            mContext.enforceCallingPermission(
5117                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5118                    "isPermissionRevokedByPolicy for user " + userId);
5119        }
5120
5121        if (checkPermission(permission, packageName, userId)
5122                == PackageManager.PERMISSION_GRANTED) {
5123            return false;
5124        }
5125
5126        final int callingUid = Binder.getCallingUid();
5127        if (getInstantAppPackageName(callingUid) != null) {
5128            if (!isCallerSameApp(packageName, callingUid)) {
5129                return false;
5130            }
5131        } else {
5132            if (isInstantApp(packageName, userId)) {
5133                return false;
5134            }
5135        }
5136
5137        final long identity = Binder.clearCallingIdentity();
5138        try {
5139            final int flags = getPermissionFlags(permission, packageName, userId);
5140            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5141        } finally {
5142            Binder.restoreCallingIdentity(identity);
5143        }
5144    }
5145
5146    @Override
5147    public String getPermissionControllerPackageName() {
5148        synchronized (mPackages) {
5149            return mRequiredInstallerPackage;
5150        }
5151    }
5152
5153    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5154        return mPermissionManager.addDynamicPermission(
5155                info, async, getCallingUid(), new PermissionCallback() {
5156                    @Override
5157                    public void onPermissionChanged() {
5158                        if (!async) {
5159                            mSettings.writeLPr();
5160                        } else {
5161                            scheduleWriteSettingsLocked();
5162                        }
5163                    }
5164                });
5165    }
5166
5167    @Override
5168    public boolean addPermission(PermissionInfo info) {
5169        synchronized (mPackages) {
5170            return addDynamicPermission(info, false);
5171        }
5172    }
5173
5174    @Override
5175    public boolean addPermissionAsync(PermissionInfo info) {
5176        synchronized (mPackages) {
5177            return addDynamicPermission(info, true);
5178        }
5179    }
5180
5181    @Override
5182    public void removePermission(String permName) {
5183        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5184    }
5185
5186    @Override
5187    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5188        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5189                getCallingUid(), userId, mPermissionCallback);
5190    }
5191
5192    @Override
5193    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5194        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5195                getCallingUid(), userId, mPermissionCallback);
5196    }
5197
5198    /**
5199     * Get the first event id for the permission.
5200     *
5201     * <p>There are four events for each permission: <ul>
5202     *     <li>Request permission: first id + 0</li>
5203     *     <li>Grant permission: first id + 1</li>
5204     *     <li>Request for permission denied: first id + 2</li>
5205     *     <li>Revoke permission: first id + 3</li>
5206     * </ul></p>
5207     *
5208     * @param name name of the permission
5209     *
5210     * @return The first event id for the permission
5211     */
5212    private static int getBaseEventId(@NonNull String name) {
5213        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5214
5215        if (eventIdIndex == -1) {
5216            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5217                    || Build.IS_USER) {
5218                Log.i(TAG, "Unknown permission " + name);
5219
5220                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5221            } else {
5222                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5223                //
5224                // Also update
5225                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5226                // - metrics_constants.proto
5227                throw new IllegalStateException("Unknown permission " + name);
5228            }
5229        }
5230
5231        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5232    }
5233
5234    /**
5235     * Log that a permission was revoked.
5236     *
5237     * @param context Context of the caller
5238     * @param name name of the permission
5239     * @param packageName package permission if for
5240     */
5241    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5242            @NonNull String packageName) {
5243        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5244    }
5245
5246    /**
5247     * Log that a permission request was granted.
5248     *
5249     * @param context Context of the caller
5250     * @param name name of the permission
5251     * @param packageName package permission if for
5252     */
5253    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5254            @NonNull String packageName) {
5255        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5256    }
5257
5258    @Override
5259    public void resetRuntimePermissions() {
5260        mContext.enforceCallingOrSelfPermission(
5261                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5262                "revokeRuntimePermission");
5263
5264        int callingUid = Binder.getCallingUid();
5265        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5266            mContext.enforceCallingOrSelfPermission(
5267                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5268                    "resetRuntimePermissions");
5269        }
5270
5271        synchronized (mPackages) {
5272            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5273            for (int userId : UserManagerService.getInstance().getUserIds()) {
5274                final int packageCount = mPackages.size();
5275                for (int i = 0; i < packageCount; i++) {
5276                    PackageParser.Package pkg = mPackages.valueAt(i);
5277                    if (!(pkg.mExtras instanceof PackageSetting)) {
5278                        continue;
5279                    }
5280                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5281                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5282                }
5283            }
5284        }
5285    }
5286
5287    @Override
5288    public int getPermissionFlags(String permName, String packageName, int userId) {
5289        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5290    }
5291
5292    @Override
5293    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5294            int flagValues, int userId) {
5295        mPermissionManager.updatePermissionFlags(
5296                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5297                mPermissionCallback);
5298    }
5299
5300    /**
5301     * Update the permission flags for all packages and runtime permissions of a user in order
5302     * to allow device or profile owner to remove POLICY_FIXED.
5303     */
5304    @Override
5305    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5306        synchronized (mPackages) {
5307            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5308                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5309                    mPermissionCallback);
5310            if (changed) {
5311                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5312            }
5313        }
5314    }
5315
5316    @Override
5317    public boolean shouldShowRequestPermissionRationale(String permissionName,
5318            String packageName, int userId) {
5319        if (UserHandle.getCallingUserId() != userId) {
5320            mContext.enforceCallingPermission(
5321                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5322                    "canShowRequestPermissionRationale for user " + userId);
5323        }
5324
5325        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5326        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5327            return false;
5328        }
5329
5330        if (checkPermission(permissionName, packageName, userId)
5331                == PackageManager.PERMISSION_GRANTED) {
5332            return false;
5333        }
5334
5335        final int flags;
5336
5337        final long identity = Binder.clearCallingIdentity();
5338        try {
5339            flags = getPermissionFlags(permissionName,
5340                    packageName, userId);
5341        } finally {
5342            Binder.restoreCallingIdentity(identity);
5343        }
5344
5345        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5346                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5347                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5348
5349        if ((flags & fixedFlags) != 0) {
5350            return false;
5351        }
5352
5353        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5354    }
5355
5356    @Override
5357    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5358        mContext.enforceCallingOrSelfPermission(
5359                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5360                "addOnPermissionsChangeListener");
5361
5362        synchronized (mPackages) {
5363            mOnPermissionChangeListeners.addListenerLocked(listener);
5364        }
5365    }
5366
5367    @Override
5368    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5369        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5370            throw new SecurityException("Instant applications don't have access to this method");
5371        }
5372        synchronized (mPackages) {
5373            mOnPermissionChangeListeners.removeListenerLocked(listener);
5374        }
5375    }
5376
5377    @Override
5378    public boolean isProtectedBroadcast(String actionName) {
5379        // allow instant applications
5380        synchronized (mProtectedBroadcasts) {
5381            if (mProtectedBroadcasts.contains(actionName)) {
5382                return true;
5383            } else if (actionName != null) {
5384                // TODO: remove these terrible hacks
5385                if (actionName.startsWith("android.net.netmon.lingerExpired")
5386                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5387                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5388                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5389                    return true;
5390                }
5391            }
5392        }
5393        return false;
5394    }
5395
5396    @Override
5397    public int checkSignatures(String pkg1, String pkg2) {
5398        synchronized (mPackages) {
5399            final PackageParser.Package p1 = mPackages.get(pkg1);
5400            final PackageParser.Package p2 = mPackages.get(pkg2);
5401            if (p1 == null || p1.mExtras == null
5402                    || p2 == null || p2.mExtras == null) {
5403                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5404            }
5405            final int callingUid = Binder.getCallingUid();
5406            final int callingUserId = UserHandle.getUserId(callingUid);
5407            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5408            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5409            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5410                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5411                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5412            }
5413            return compareSignatures(p1.mSignatures, p2.mSignatures);
5414        }
5415    }
5416
5417    @Override
5418    public int checkUidSignatures(int uid1, int uid2) {
5419        final int callingUid = Binder.getCallingUid();
5420        final int callingUserId = UserHandle.getUserId(callingUid);
5421        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5422        // Map to base uids.
5423        uid1 = UserHandle.getAppId(uid1);
5424        uid2 = UserHandle.getAppId(uid2);
5425        // reader
5426        synchronized (mPackages) {
5427            Signature[] s1;
5428            Signature[] s2;
5429            Object obj = mSettings.getUserIdLPr(uid1);
5430            if (obj != null) {
5431                if (obj instanceof SharedUserSetting) {
5432                    if (isCallerInstantApp) {
5433                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5434                    }
5435                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5436                } else if (obj instanceof PackageSetting) {
5437                    final PackageSetting ps = (PackageSetting) obj;
5438                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5439                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5440                    }
5441                    s1 = ps.signatures.mSignatures;
5442                } else {
5443                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5444                }
5445            } else {
5446                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5447            }
5448            obj = mSettings.getUserIdLPr(uid2);
5449            if (obj != null) {
5450                if (obj instanceof SharedUserSetting) {
5451                    if (isCallerInstantApp) {
5452                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5453                    }
5454                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5455                } else if (obj instanceof PackageSetting) {
5456                    final PackageSetting ps = (PackageSetting) obj;
5457                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5458                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5459                    }
5460                    s2 = ps.signatures.mSignatures;
5461                } else {
5462                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5463                }
5464            } else {
5465                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5466            }
5467            return compareSignatures(s1, s2);
5468        }
5469    }
5470
5471    /**
5472     * This method should typically only be used when granting or revoking
5473     * permissions, since the app may immediately restart after this call.
5474     * <p>
5475     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5476     * guard your work against the app being relaunched.
5477     */
5478    private void killUid(int appId, int userId, String reason) {
5479        final long identity = Binder.clearCallingIdentity();
5480        try {
5481            IActivityManager am = ActivityManager.getService();
5482            if (am != null) {
5483                try {
5484                    am.killUid(appId, userId, reason);
5485                } catch (RemoteException e) {
5486                    /* ignore - same process */
5487                }
5488            }
5489        } finally {
5490            Binder.restoreCallingIdentity(identity);
5491        }
5492    }
5493
5494    /**
5495     * Compares two sets of signatures. Returns:
5496     * <br />
5497     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5498     * <br />
5499     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5500     * <br />
5501     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5502     * <br />
5503     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5504     * <br />
5505     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5506     */
5507    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5508        if (s1 == null) {
5509            return s2 == null
5510                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5511                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5512        }
5513
5514        if (s2 == null) {
5515            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5516        }
5517
5518        if (s1.length != s2.length) {
5519            return PackageManager.SIGNATURE_NO_MATCH;
5520        }
5521
5522        // Since both signature sets are of size 1, we can compare without HashSets.
5523        if (s1.length == 1) {
5524            return s1[0].equals(s2[0]) ?
5525                    PackageManager.SIGNATURE_MATCH :
5526                    PackageManager.SIGNATURE_NO_MATCH;
5527        }
5528
5529        ArraySet<Signature> set1 = new ArraySet<Signature>();
5530        for (Signature sig : s1) {
5531            set1.add(sig);
5532        }
5533        ArraySet<Signature> set2 = new ArraySet<Signature>();
5534        for (Signature sig : s2) {
5535            set2.add(sig);
5536        }
5537        // Make sure s2 contains all signatures in s1.
5538        if (set1.equals(set2)) {
5539            return PackageManager.SIGNATURE_MATCH;
5540        }
5541        return PackageManager.SIGNATURE_NO_MATCH;
5542    }
5543
5544    /**
5545     * If the database version for this type of package (internal storage or
5546     * external storage) is less than the version where package signatures
5547     * were updated, return true.
5548     */
5549    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5550        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5551        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5552    }
5553
5554    /**
5555     * Used for backward compatibility to make sure any packages with
5556     * certificate chains get upgraded to the new style. {@code existingSigs}
5557     * will be in the old format (since they were stored on disk from before the
5558     * system upgrade) and {@code scannedSigs} will be in the newer format.
5559     */
5560    private int compareSignaturesCompat(PackageSignatures existingSigs,
5561            PackageParser.Package scannedPkg) {
5562        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5563            return PackageManager.SIGNATURE_NO_MATCH;
5564        }
5565
5566        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5567        for (Signature sig : existingSigs.mSignatures) {
5568            existingSet.add(sig);
5569        }
5570        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5571        for (Signature sig : scannedPkg.mSignatures) {
5572            try {
5573                Signature[] chainSignatures = sig.getChainSignatures();
5574                for (Signature chainSig : chainSignatures) {
5575                    scannedCompatSet.add(chainSig);
5576                }
5577            } catch (CertificateEncodingException e) {
5578                scannedCompatSet.add(sig);
5579            }
5580        }
5581        /*
5582         * Make sure the expanded scanned set contains all signatures in the
5583         * existing one.
5584         */
5585        if (scannedCompatSet.equals(existingSet)) {
5586            // Migrate the old signatures to the new scheme.
5587            existingSigs.assignSignatures(scannedPkg.mSignatures);
5588            // The new KeySets will be re-added later in the scanning process.
5589            synchronized (mPackages) {
5590                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5591            }
5592            return PackageManager.SIGNATURE_MATCH;
5593        }
5594        return PackageManager.SIGNATURE_NO_MATCH;
5595    }
5596
5597    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5598        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5599        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5600    }
5601
5602    private int compareSignaturesRecover(PackageSignatures existingSigs,
5603            PackageParser.Package scannedPkg) {
5604        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5605            return PackageManager.SIGNATURE_NO_MATCH;
5606        }
5607
5608        String msg = null;
5609        try {
5610            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5611                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5612                        + scannedPkg.packageName);
5613                return PackageManager.SIGNATURE_MATCH;
5614            }
5615        } catch (CertificateException e) {
5616            msg = e.getMessage();
5617        }
5618
5619        logCriticalInfo(Log.INFO,
5620                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5621        return PackageManager.SIGNATURE_NO_MATCH;
5622    }
5623
5624    @Override
5625    public List<String> getAllPackages() {
5626        final int callingUid = Binder.getCallingUid();
5627        final int callingUserId = UserHandle.getUserId(callingUid);
5628        synchronized (mPackages) {
5629            if (canViewInstantApps(callingUid, callingUserId)) {
5630                return new ArrayList<String>(mPackages.keySet());
5631            }
5632            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5633            final List<String> result = new ArrayList<>();
5634            if (instantAppPkgName != null) {
5635                // caller is an instant application; filter unexposed applications
5636                for (PackageParser.Package pkg : mPackages.values()) {
5637                    if (!pkg.visibleToInstantApps) {
5638                        continue;
5639                    }
5640                    result.add(pkg.packageName);
5641                }
5642            } else {
5643                // caller is a normal application; filter instant applications
5644                for (PackageParser.Package pkg : mPackages.values()) {
5645                    final PackageSetting ps =
5646                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5647                    if (ps != null
5648                            && ps.getInstantApp(callingUserId)
5649                            && !mInstantAppRegistry.isInstantAccessGranted(
5650                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5651                        continue;
5652                    }
5653                    result.add(pkg.packageName);
5654                }
5655            }
5656            return result;
5657        }
5658    }
5659
5660    @Override
5661    public String[] getPackagesForUid(int uid) {
5662        final int callingUid = Binder.getCallingUid();
5663        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5664        final int userId = UserHandle.getUserId(uid);
5665        uid = UserHandle.getAppId(uid);
5666        // reader
5667        synchronized (mPackages) {
5668            Object obj = mSettings.getUserIdLPr(uid);
5669            if (obj instanceof SharedUserSetting) {
5670                if (isCallerInstantApp) {
5671                    return null;
5672                }
5673                final SharedUserSetting sus = (SharedUserSetting) obj;
5674                final int N = sus.packages.size();
5675                String[] res = new String[N];
5676                final Iterator<PackageSetting> it = sus.packages.iterator();
5677                int i = 0;
5678                while (it.hasNext()) {
5679                    PackageSetting ps = it.next();
5680                    if (ps.getInstalled(userId)) {
5681                        res[i++] = ps.name;
5682                    } else {
5683                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5684                    }
5685                }
5686                return res;
5687            } else if (obj instanceof PackageSetting) {
5688                final PackageSetting ps = (PackageSetting) obj;
5689                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5690                    return new String[]{ps.name};
5691                }
5692            }
5693        }
5694        return null;
5695    }
5696
5697    @Override
5698    public String getNameForUid(int uid) {
5699        final int callingUid = Binder.getCallingUid();
5700        if (getInstantAppPackageName(callingUid) != null) {
5701            return null;
5702        }
5703        synchronized (mPackages) {
5704            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5705            if (obj instanceof SharedUserSetting) {
5706                final SharedUserSetting sus = (SharedUserSetting) obj;
5707                return sus.name + ":" + sus.userId;
5708            } else if (obj instanceof PackageSetting) {
5709                final PackageSetting ps = (PackageSetting) obj;
5710                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5711                    return null;
5712                }
5713                return ps.name;
5714            }
5715            return null;
5716        }
5717    }
5718
5719    @Override
5720    public String[] getNamesForUids(int[] uids) {
5721        if (uids == null || uids.length == 0) {
5722            return null;
5723        }
5724        final int callingUid = Binder.getCallingUid();
5725        if (getInstantAppPackageName(callingUid) != null) {
5726            return null;
5727        }
5728        final String[] names = new String[uids.length];
5729        synchronized (mPackages) {
5730            for (int i = uids.length - 1; i >= 0; i--) {
5731                final int uid = uids[i];
5732                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5733                if (obj instanceof SharedUserSetting) {
5734                    final SharedUserSetting sus = (SharedUserSetting) obj;
5735                    names[i] = "shared:" + sus.name;
5736                } else if (obj instanceof PackageSetting) {
5737                    final PackageSetting ps = (PackageSetting) obj;
5738                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5739                        names[i] = null;
5740                    } else {
5741                        names[i] = ps.name;
5742                    }
5743                } else {
5744                    names[i] = null;
5745                }
5746            }
5747        }
5748        return names;
5749    }
5750
5751    @Override
5752    public int getUidForSharedUser(String sharedUserName) {
5753        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5754            return -1;
5755        }
5756        if (sharedUserName == null) {
5757            return -1;
5758        }
5759        // reader
5760        synchronized (mPackages) {
5761            SharedUserSetting suid;
5762            try {
5763                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5764                if (suid != null) {
5765                    return suid.userId;
5766                }
5767            } catch (PackageManagerException ignore) {
5768                // can't happen, but, still need to catch it
5769            }
5770            return -1;
5771        }
5772    }
5773
5774    @Override
5775    public int getFlagsForUid(int uid) {
5776        final int callingUid = Binder.getCallingUid();
5777        if (getInstantAppPackageName(callingUid) != null) {
5778            return 0;
5779        }
5780        synchronized (mPackages) {
5781            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5782            if (obj instanceof SharedUserSetting) {
5783                final SharedUserSetting sus = (SharedUserSetting) obj;
5784                return sus.pkgFlags;
5785            } else if (obj instanceof PackageSetting) {
5786                final PackageSetting ps = (PackageSetting) obj;
5787                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5788                    return 0;
5789                }
5790                return ps.pkgFlags;
5791            }
5792        }
5793        return 0;
5794    }
5795
5796    @Override
5797    public int getPrivateFlagsForUid(int uid) {
5798        final int callingUid = Binder.getCallingUid();
5799        if (getInstantAppPackageName(callingUid) != null) {
5800            return 0;
5801        }
5802        synchronized (mPackages) {
5803            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5804            if (obj instanceof SharedUserSetting) {
5805                final SharedUserSetting sus = (SharedUserSetting) obj;
5806                return sus.pkgPrivateFlags;
5807            } else if (obj instanceof PackageSetting) {
5808                final PackageSetting ps = (PackageSetting) obj;
5809                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5810                    return 0;
5811                }
5812                return ps.pkgPrivateFlags;
5813            }
5814        }
5815        return 0;
5816    }
5817
5818    @Override
5819    public boolean isUidPrivileged(int uid) {
5820        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5821            return false;
5822        }
5823        uid = UserHandle.getAppId(uid);
5824        // reader
5825        synchronized (mPackages) {
5826            Object obj = mSettings.getUserIdLPr(uid);
5827            if (obj instanceof SharedUserSetting) {
5828                final SharedUserSetting sus = (SharedUserSetting) obj;
5829                final Iterator<PackageSetting> it = sus.packages.iterator();
5830                while (it.hasNext()) {
5831                    if (it.next().isPrivileged()) {
5832                        return true;
5833                    }
5834                }
5835            } else if (obj instanceof PackageSetting) {
5836                final PackageSetting ps = (PackageSetting) obj;
5837                return ps.isPrivileged();
5838            }
5839        }
5840        return false;
5841    }
5842
5843    @Override
5844    public String[] getAppOpPermissionPackages(String permName) {
5845        return mPermissionManager.getAppOpPermissionPackages(permName);
5846    }
5847
5848    @Override
5849    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5850            int flags, int userId) {
5851        return resolveIntentInternal(
5852                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5853    }
5854
5855    /**
5856     * Normally instant apps can only be resolved when they're visible to the caller.
5857     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5858     * since we need to allow the system to start any installed application.
5859     */
5860    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5861            int flags, int userId, boolean resolveForStart) {
5862        try {
5863            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5864
5865            if (!sUserManager.exists(userId)) return null;
5866            final int callingUid = Binder.getCallingUid();
5867            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5868            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5869                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5870
5871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5872            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5873                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5874            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5875
5876            final ResolveInfo bestChoice =
5877                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5878            return bestChoice;
5879        } finally {
5880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5881        }
5882    }
5883
5884    @Override
5885    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5886        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5887            throw new SecurityException(
5888                    "findPersistentPreferredActivity can only be run by the system");
5889        }
5890        if (!sUserManager.exists(userId)) {
5891            return null;
5892        }
5893        final int callingUid = Binder.getCallingUid();
5894        intent = updateIntentForResolve(intent);
5895        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5896        final int flags = updateFlagsForResolve(
5897                0, userId, intent, callingUid, false /*includeInstantApps*/);
5898        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5899                userId);
5900        synchronized (mPackages) {
5901            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5902                    userId);
5903        }
5904    }
5905
5906    @Override
5907    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5908            IntentFilter filter, int match, ComponentName activity) {
5909        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5910            return;
5911        }
5912        final int userId = UserHandle.getCallingUserId();
5913        if (DEBUG_PREFERRED) {
5914            Log.v(TAG, "setLastChosenActivity intent=" + intent
5915                + " resolvedType=" + resolvedType
5916                + " flags=" + flags
5917                + " filter=" + filter
5918                + " match=" + match
5919                + " activity=" + activity);
5920            filter.dump(new PrintStreamPrinter(System.out), "    ");
5921        }
5922        intent.setComponent(null);
5923        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5924                userId);
5925        // Find any earlier preferred or last chosen entries and nuke them
5926        findPreferredActivity(intent, resolvedType,
5927                flags, query, 0, false, true, false, userId);
5928        // Add the new activity as the last chosen for this filter
5929        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5930                "Setting last chosen");
5931    }
5932
5933    @Override
5934    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5936            return null;
5937        }
5938        final int userId = UserHandle.getCallingUserId();
5939        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5940        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5941                userId);
5942        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5943                false, false, false, userId);
5944    }
5945
5946    /**
5947     * Returns whether or not instant apps have been disabled remotely.
5948     */
5949    private boolean isEphemeralDisabled() {
5950        return mEphemeralAppsDisabled;
5951    }
5952
5953    private boolean isInstantAppAllowed(
5954            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5955            boolean skipPackageCheck) {
5956        if (mInstantAppResolverConnection == null) {
5957            return false;
5958        }
5959        if (mInstantAppInstallerActivity == null) {
5960            return false;
5961        }
5962        if (intent.getComponent() != null) {
5963            return false;
5964        }
5965        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5966            return false;
5967        }
5968        if (!skipPackageCheck && intent.getPackage() != null) {
5969            return false;
5970        }
5971        final boolean isWebUri = hasWebURI(intent);
5972        if (!isWebUri || intent.getData().getHost() == null) {
5973            return false;
5974        }
5975        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5976        // Or if there's already an ephemeral app installed that handles the action
5977        synchronized (mPackages) {
5978            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5979            for (int n = 0; n < count; n++) {
5980                final ResolveInfo info = resolvedActivities.get(n);
5981                final String packageName = info.activityInfo.packageName;
5982                final PackageSetting ps = mSettings.mPackages.get(packageName);
5983                if (ps != null) {
5984                    // only check domain verification status if the app is not a browser
5985                    if (!info.handleAllWebDataURI) {
5986                        // Try to get the status from User settings first
5987                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5988                        final int status = (int) (packedStatus >> 32);
5989                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5990                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5991                            if (DEBUG_EPHEMERAL) {
5992                                Slog.v(TAG, "DENY instant app;"
5993                                    + " pkg: " + packageName + ", status: " + status);
5994                            }
5995                            return false;
5996                        }
5997                    }
5998                    if (ps.getInstantApp(userId)) {
5999                        if (DEBUG_EPHEMERAL) {
6000                            Slog.v(TAG, "DENY instant app installed;"
6001                                    + " pkg: " + packageName);
6002                        }
6003                        return false;
6004                    }
6005                }
6006            }
6007        }
6008        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6009        return true;
6010    }
6011
6012    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6013            Intent origIntent, String resolvedType, String callingPackage,
6014            Bundle verificationBundle, int userId) {
6015        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6016                new InstantAppRequest(responseObj, origIntent, resolvedType,
6017                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6018        mHandler.sendMessage(msg);
6019    }
6020
6021    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6022            int flags, List<ResolveInfo> query, int userId) {
6023        if (query != null) {
6024            final int N = query.size();
6025            if (N == 1) {
6026                return query.get(0);
6027            } else if (N > 1) {
6028                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6029                // If there is more than one activity with the same priority,
6030                // then let the user decide between them.
6031                ResolveInfo r0 = query.get(0);
6032                ResolveInfo r1 = query.get(1);
6033                if (DEBUG_INTENT_MATCHING || debug) {
6034                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6035                            + r1.activityInfo.name + "=" + r1.priority);
6036                }
6037                // If the first activity has a higher priority, or a different
6038                // default, then it is always desirable to pick it.
6039                if (r0.priority != r1.priority
6040                        || r0.preferredOrder != r1.preferredOrder
6041                        || r0.isDefault != r1.isDefault) {
6042                    return query.get(0);
6043                }
6044                // If we have saved a preference for a preferred activity for
6045                // this Intent, use that.
6046                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6047                        flags, query, r0.priority, true, false, debug, userId);
6048                if (ri != null) {
6049                    return ri;
6050                }
6051                // If we have an ephemeral app, use it
6052                for (int i = 0; i < N; i++) {
6053                    ri = query.get(i);
6054                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6055                        final String packageName = ri.activityInfo.packageName;
6056                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6057                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6058                        final int status = (int)(packedStatus >> 32);
6059                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6060                            return ri;
6061                        }
6062                    }
6063                }
6064                ri = new ResolveInfo(mResolveInfo);
6065                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6066                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6067                // If all of the options come from the same package, show the application's
6068                // label and icon instead of the generic resolver's.
6069                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6070                // and then throw away the ResolveInfo itself, meaning that the caller loses
6071                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6072                // a fallback for this case; we only set the target package's resources on
6073                // the ResolveInfo, not the ActivityInfo.
6074                final String intentPackage = intent.getPackage();
6075                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6076                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6077                    ri.resolvePackageName = intentPackage;
6078                    if (userNeedsBadging(userId)) {
6079                        ri.noResourceId = true;
6080                    } else {
6081                        ri.icon = appi.icon;
6082                    }
6083                    ri.iconResourceId = appi.icon;
6084                    ri.labelRes = appi.labelRes;
6085                }
6086                ri.activityInfo.applicationInfo = new ApplicationInfo(
6087                        ri.activityInfo.applicationInfo);
6088                if (userId != 0) {
6089                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6090                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6091                }
6092                // Make sure that the resolver is displayable in car mode
6093                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6094                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6095                return ri;
6096            }
6097        }
6098        return null;
6099    }
6100
6101    /**
6102     * Return true if the given list is not empty and all of its contents have
6103     * an activityInfo with the given package name.
6104     */
6105    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6106        if (ArrayUtils.isEmpty(list)) {
6107            return false;
6108        }
6109        for (int i = 0, N = list.size(); i < N; i++) {
6110            final ResolveInfo ri = list.get(i);
6111            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6112            if (ai == null || !packageName.equals(ai.packageName)) {
6113                return false;
6114            }
6115        }
6116        return true;
6117    }
6118
6119    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6120            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6121        final int N = query.size();
6122        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6123                .get(userId);
6124        // Get the list of persistent preferred activities that handle the intent
6125        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6126        List<PersistentPreferredActivity> pprefs = ppir != null
6127                ? ppir.queryIntent(intent, resolvedType,
6128                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6129                        userId)
6130                : null;
6131        if (pprefs != null && pprefs.size() > 0) {
6132            final int M = pprefs.size();
6133            for (int i=0; i<M; i++) {
6134                final PersistentPreferredActivity ppa = pprefs.get(i);
6135                if (DEBUG_PREFERRED || debug) {
6136                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6137                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6138                            + "\n  component=" + ppa.mComponent);
6139                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6140                }
6141                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6142                        flags | MATCH_DISABLED_COMPONENTS, userId);
6143                if (DEBUG_PREFERRED || debug) {
6144                    Slog.v(TAG, "Found persistent preferred activity:");
6145                    if (ai != null) {
6146                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6147                    } else {
6148                        Slog.v(TAG, "  null");
6149                    }
6150                }
6151                if (ai == null) {
6152                    // This previously registered persistent preferred activity
6153                    // component is no longer known. Ignore it and do NOT remove it.
6154                    continue;
6155                }
6156                for (int j=0; j<N; j++) {
6157                    final ResolveInfo ri = query.get(j);
6158                    if (!ri.activityInfo.applicationInfo.packageName
6159                            .equals(ai.applicationInfo.packageName)) {
6160                        continue;
6161                    }
6162                    if (!ri.activityInfo.name.equals(ai.name)) {
6163                        continue;
6164                    }
6165                    //  Found a persistent preference that can handle the intent.
6166                    if (DEBUG_PREFERRED || debug) {
6167                        Slog.v(TAG, "Returning persistent preferred activity: " +
6168                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6169                    }
6170                    return ri;
6171                }
6172            }
6173        }
6174        return null;
6175    }
6176
6177    // TODO: handle preferred activities missing while user has amnesia
6178    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6179            List<ResolveInfo> query, int priority, boolean always,
6180            boolean removeMatches, boolean debug, int userId) {
6181        if (!sUserManager.exists(userId)) return null;
6182        final int callingUid = Binder.getCallingUid();
6183        flags = updateFlagsForResolve(
6184                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6185        intent = updateIntentForResolve(intent);
6186        // writer
6187        synchronized (mPackages) {
6188            // Try to find a matching persistent preferred activity.
6189            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6190                    debug, userId);
6191
6192            // If a persistent preferred activity matched, use it.
6193            if (pri != null) {
6194                return pri;
6195            }
6196
6197            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6198            // Get the list of preferred activities that handle the intent
6199            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6200            List<PreferredActivity> prefs = pir != null
6201                    ? pir.queryIntent(intent, resolvedType,
6202                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6203                            userId)
6204                    : null;
6205            if (prefs != null && prefs.size() > 0) {
6206                boolean changed = false;
6207                try {
6208                    // First figure out how good the original match set is.
6209                    // We will only allow preferred activities that came
6210                    // from the same match quality.
6211                    int match = 0;
6212
6213                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6214
6215                    final int N = query.size();
6216                    for (int j=0; j<N; j++) {
6217                        final ResolveInfo ri = query.get(j);
6218                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6219                                + ": 0x" + Integer.toHexString(match));
6220                        if (ri.match > match) {
6221                            match = ri.match;
6222                        }
6223                    }
6224
6225                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6226                            + Integer.toHexString(match));
6227
6228                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6229                    final int M = prefs.size();
6230                    for (int i=0; i<M; i++) {
6231                        final PreferredActivity pa = prefs.get(i);
6232                        if (DEBUG_PREFERRED || debug) {
6233                            Slog.v(TAG, "Checking PreferredActivity ds="
6234                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6235                                    + "\n  component=" + pa.mPref.mComponent);
6236                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6237                        }
6238                        if (pa.mPref.mMatch != match) {
6239                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6240                                    + Integer.toHexString(pa.mPref.mMatch));
6241                            continue;
6242                        }
6243                        // If it's not an "always" type preferred activity and that's what we're
6244                        // looking for, skip it.
6245                        if (always && !pa.mPref.mAlways) {
6246                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6247                            continue;
6248                        }
6249                        final ActivityInfo ai = getActivityInfo(
6250                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6251                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6252                                userId);
6253                        if (DEBUG_PREFERRED || debug) {
6254                            Slog.v(TAG, "Found preferred activity:");
6255                            if (ai != null) {
6256                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6257                            } else {
6258                                Slog.v(TAG, "  null");
6259                            }
6260                        }
6261                        if (ai == null) {
6262                            // This previously registered preferred activity
6263                            // component is no longer known.  Most likely an update
6264                            // to the app was installed and in the new version this
6265                            // component no longer exists.  Clean it up by removing
6266                            // it from the preferred activities list, and skip it.
6267                            Slog.w(TAG, "Removing dangling preferred activity: "
6268                                    + pa.mPref.mComponent);
6269                            pir.removeFilter(pa);
6270                            changed = true;
6271                            continue;
6272                        }
6273                        for (int j=0; j<N; j++) {
6274                            final ResolveInfo ri = query.get(j);
6275                            if (!ri.activityInfo.applicationInfo.packageName
6276                                    .equals(ai.applicationInfo.packageName)) {
6277                                continue;
6278                            }
6279                            if (!ri.activityInfo.name.equals(ai.name)) {
6280                                continue;
6281                            }
6282
6283                            if (removeMatches) {
6284                                pir.removeFilter(pa);
6285                                changed = true;
6286                                if (DEBUG_PREFERRED) {
6287                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6288                                }
6289                                break;
6290                            }
6291
6292                            // Okay we found a previously set preferred or last chosen app.
6293                            // If the result set is different from when this
6294                            // was created, and is not a subset of the preferred set, we need to
6295                            // clear it and re-ask the user their preference, if we're looking for
6296                            // an "always" type entry.
6297                            if (always && !pa.mPref.sameSet(query)) {
6298                                if (pa.mPref.isSuperset(query)) {
6299                                    // some components of the set are no longer present in
6300                                    // the query, but the preferred activity can still be reused
6301                                    if (DEBUG_PREFERRED) {
6302                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6303                                                + " still valid as only non-preferred components"
6304                                                + " were removed for " + intent + " type "
6305                                                + resolvedType);
6306                                    }
6307                                    // remove obsolete components and re-add the up-to-date filter
6308                                    PreferredActivity freshPa = new PreferredActivity(pa,
6309                                            pa.mPref.mMatch,
6310                                            pa.mPref.discardObsoleteComponents(query),
6311                                            pa.mPref.mComponent,
6312                                            pa.mPref.mAlways);
6313                                    pir.removeFilter(pa);
6314                                    pir.addFilter(freshPa);
6315                                    changed = true;
6316                                } else {
6317                                    Slog.i(TAG,
6318                                            "Result set changed, dropping preferred activity for "
6319                                                    + intent + " type " + resolvedType);
6320                                    if (DEBUG_PREFERRED) {
6321                                        Slog.v(TAG, "Removing preferred activity since set changed "
6322                                                + pa.mPref.mComponent);
6323                                    }
6324                                    pir.removeFilter(pa);
6325                                    // Re-add the filter as a "last chosen" entry (!always)
6326                                    PreferredActivity lastChosen = new PreferredActivity(
6327                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6328                                    pir.addFilter(lastChosen);
6329                                    changed = true;
6330                                    return null;
6331                                }
6332                            }
6333
6334                            // Yay! Either the set matched or we're looking for the last chosen
6335                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6336                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6337                            return ri;
6338                        }
6339                    }
6340                } finally {
6341                    if (changed) {
6342                        if (DEBUG_PREFERRED) {
6343                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6344                        }
6345                        scheduleWritePackageRestrictionsLocked(userId);
6346                    }
6347                }
6348            }
6349        }
6350        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6351        return null;
6352    }
6353
6354    /*
6355     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6356     */
6357    @Override
6358    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6359            int targetUserId) {
6360        mContext.enforceCallingOrSelfPermission(
6361                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6362        List<CrossProfileIntentFilter> matches =
6363                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6364        if (matches != null) {
6365            int size = matches.size();
6366            for (int i = 0; i < size; i++) {
6367                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6368            }
6369        }
6370        if (hasWebURI(intent)) {
6371            // cross-profile app linking works only towards the parent.
6372            final int callingUid = Binder.getCallingUid();
6373            final UserInfo parent = getProfileParent(sourceUserId);
6374            synchronized(mPackages) {
6375                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6376                        false /*includeInstantApps*/);
6377                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6378                        intent, resolvedType, flags, sourceUserId, parent.id);
6379                return xpDomainInfo != null;
6380            }
6381        }
6382        return false;
6383    }
6384
6385    private UserInfo getProfileParent(int userId) {
6386        final long identity = Binder.clearCallingIdentity();
6387        try {
6388            return sUserManager.getProfileParent(userId);
6389        } finally {
6390            Binder.restoreCallingIdentity(identity);
6391        }
6392    }
6393
6394    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6395            String resolvedType, int userId) {
6396        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6397        if (resolver != null) {
6398            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6399        }
6400        return null;
6401    }
6402
6403    @Override
6404    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6405            String resolvedType, int flags, int userId) {
6406        try {
6407            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6408
6409            return new ParceledListSlice<>(
6410                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6411        } finally {
6412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6413        }
6414    }
6415
6416    /**
6417     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6418     * instant, returns {@code null}.
6419     */
6420    private String getInstantAppPackageName(int callingUid) {
6421        synchronized (mPackages) {
6422            // If the caller is an isolated app use the owner's uid for the lookup.
6423            if (Process.isIsolated(callingUid)) {
6424                callingUid = mIsolatedOwners.get(callingUid);
6425            }
6426            final int appId = UserHandle.getAppId(callingUid);
6427            final Object obj = mSettings.getUserIdLPr(appId);
6428            if (obj instanceof PackageSetting) {
6429                final PackageSetting ps = (PackageSetting) obj;
6430                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6431                return isInstantApp ? ps.pkg.packageName : null;
6432            }
6433        }
6434        return null;
6435    }
6436
6437    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6438            String resolvedType, int flags, int userId) {
6439        return queryIntentActivitiesInternal(
6440                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6441                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6442    }
6443
6444    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6445            String resolvedType, int flags, int filterCallingUid, int userId,
6446            boolean resolveForStart, boolean allowDynamicSplits) {
6447        if (!sUserManager.exists(userId)) return Collections.emptyList();
6448        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6449        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6450                false /* requireFullPermission */, false /* checkShell */,
6451                "query intent activities");
6452        final String pkgName = intent.getPackage();
6453        ComponentName comp = intent.getComponent();
6454        if (comp == null) {
6455            if (intent.getSelector() != null) {
6456                intent = intent.getSelector();
6457                comp = intent.getComponent();
6458            }
6459        }
6460
6461        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6462                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6463        if (comp != null) {
6464            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6465            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6466            if (ai != null) {
6467                // When specifying an explicit component, we prevent the activity from being
6468                // used when either 1) the calling package is normal and the activity is within
6469                // an ephemeral application or 2) the calling package is ephemeral and the
6470                // activity is not visible to ephemeral applications.
6471                final boolean matchInstantApp =
6472                        (flags & PackageManager.MATCH_INSTANT) != 0;
6473                final boolean matchVisibleToInstantAppOnly =
6474                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6475                final boolean matchExplicitlyVisibleOnly =
6476                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6477                final boolean isCallerInstantApp =
6478                        instantAppPkgName != null;
6479                final boolean isTargetSameInstantApp =
6480                        comp.getPackageName().equals(instantAppPkgName);
6481                final boolean isTargetInstantApp =
6482                        (ai.applicationInfo.privateFlags
6483                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6484                final boolean isTargetVisibleToInstantApp =
6485                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6486                final boolean isTargetExplicitlyVisibleToInstantApp =
6487                        isTargetVisibleToInstantApp
6488                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6489                final boolean isTargetHiddenFromInstantApp =
6490                        !isTargetVisibleToInstantApp
6491                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6492                final boolean blockResolution =
6493                        !isTargetSameInstantApp
6494                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6495                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6496                                        && isTargetHiddenFromInstantApp));
6497                if (!blockResolution) {
6498                    final ResolveInfo ri = new ResolveInfo();
6499                    ri.activityInfo = ai;
6500                    list.add(ri);
6501                }
6502            }
6503            return applyPostResolutionFilter(
6504                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6505        }
6506
6507        // reader
6508        boolean sortResult = false;
6509        boolean addEphemeral = false;
6510        List<ResolveInfo> result;
6511        final boolean ephemeralDisabled = isEphemeralDisabled();
6512        synchronized (mPackages) {
6513            if (pkgName == null) {
6514                List<CrossProfileIntentFilter> matchingFilters =
6515                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6516                // Check for results that need to skip the current profile.
6517                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6518                        resolvedType, flags, userId);
6519                if (xpResolveInfo != null) {
6520                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6521                    xpResult.add(xpResolveInfo);
6522                    return applyPostResolutionFilter(
6523                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6524                            allowDynamicSplits, filterCallingUid, userId);
6525                }
6526
6527                // Check for results in the current profile.
6528                result = filterIfNotSystemUser(mActivities.queryIntent(
6529                        intent, resolvedType, flags, userId), userId);
6530                addEphemeral = !ephemeralDisabled
6531                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6532                // Check for cross profile results.
6533                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6534                xpResolveInfo = queryCrossProfileIntents(
6535                        matchingFilters, intent, resolvedType, flags, userId,
6536                        hasNonNegativePriorityResult);
6537                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6538                    boolean isVisibleToUser = filterIfNotSystemUser(
6539                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6540                    if (isVisibleToUser) {
6541                        result.add(xpResolveInfo);
6542                        sortResult = true;
6543                    }
6544                }
6545                if (hasWebURI(intent)) {
6546                    CrossProfileDomainInfo xpDomainInfo = null;
6547                    final UserInfo parent = getProfileParent(userId);
6548                    if (parent != null) {
6549                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6550                                flags, userId, parent.id);
6551                    }
6552                    if (xpDomainInfo != null) {
6553                        if (xpResolveInfo != null) {
6554                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6555                            // in the result.
6556                            result.remove(xpResolveInfo);
6557                        }
6558                        if (result.size() == 0 && !addEphemeral) {
6559                            // No result in current profile, but found candidate in parent user.
6560                            // And we are not going to add emphemeral app, so we can return the
6561                            // result straight away.
6562                            result.add(xpDomainInfo.resolveInfo);
6563                            return applyPostResolutionFilter(result, instantAppPkgName,
6564                                    allowDynamicSplits, filterCallingUid, userId);
6565                        }
6566                    } else if (result.size() <= 1 && !addEphemeral) {
6567                        // No result in parent user and <= 1 result in current profile, and we
6568                        // are not going to add emphemeral app, so we can return the result without
6569                        // further processing.
6570                        return applyPostResolutionFilter(result, instantAppPkgName,
6571                                allowDynamicSplits, filterCallingUid, userId);
6572                    }
6573                    // We have more than one candidate (combining results from current and parent
6574                    // profile), so we need filtering and sorting.
6575                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6576                            intent, flags, result, xpDomainInfo, userId);
6577                    sortResult = true;
6578                }
6579            } else {
6580                final PackageParser.Package pkg = mPackages.get(pkgName);
6581                result = null;
6582                if (pkg != null) {
6583                    result = filterIfNotSystemUser(
6584                            mActivities.queryIntentForPackage(
6585                                    intent, resolvedType, flags, pkg.activities, userId),
6586                            userId);
6587                }
6588                if (result == null || result.size() == 0) {
6589                    // the caller wants to resolve for a particular package; however, there
6590                    // were no installed results, so, try to find an ephemeral result
6591                    addEphemeral = !ephemeralDisabled
6592                            && isInstantAppAllowed(
6593                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6594                    if (result == null) {
6595                        result = new ArrayList<>();
6596                    }
6597                }
6598            }
6599        }
6600        if (addEphemeral) {
6601            result = maybeAddInstantAppInstaller(
6602                    result, intent, resolvedType, flags, userId, resolveForStart);
6603        }
6604        if (sortResult) {
6605            Collections.sort(result, mResolvePrioritySorter);
6606        }
6607        return applyPostResolutionFilter(
6608                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6609    }
6610
6611    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6612            String resolvedType, int flags, int userId, boolean resolveForStart) {
6613        // first, check to see if we've got an instant app already installed
6614        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6615        ResolveInfo localInstantApp = null;
6616        boolean blockResolution = false;
6617        if (!alreadyResolvedLocally) {
6618            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6619                    flags
6620                        | PackageManager.GET_RESOLVED_FILTER
6621                        | PackageManager.MATCH_INSTANT
6622                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6623                    userId);
6624            for (int i = instantApps.size() - 1; i >= 0; --i) {
6625                final ResolveInfo info = instantApps.get(i);
6626                final String packageName = info.activityInfo.packageName;
6627                final PackageSetting ps = mSettings.mPackages.get(packageName);
6628                if (ps.getInstantApp(userId)) {
6629                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6630                    final int status = (int)(packedStatus >> 32);
6631                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6632                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6633                        // there's a local instant application installed, but, the user has
6634                        // chosen to never use it; skip resolution and don't acknowledge
6635                        // an instant application is even available
6636                        if (DEBUG_EPHEMERAL) {
6637                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6638                        }
6639                        blockResolution = true;
6640                        break;
6641                    } else {
6642                        // we have a locally installed instant application; skip resolution
6643                        // but acknowledge there's an instant application available
6644                        if (DEBUG_EPHEMERAL) {
6645                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6646                        }
6647                        localInstantApp = info;
6648                        break;
6649                    }
6650                }
6651            }
6652        }
6653        // no app installed, let's see if one's available
6654        AuxiliaryResolveInfo auxiliaryResponse = null;
6655        if (!blockResolution) {
6656            if (localInstantApp == null) {
6657                // we don't have an instant app locally, resolve externally
6658                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6659                final InstantAppRequest requestObject = new InstantAppRequest(
6660                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6661                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6662                        resolveForStart);
6663                auxiliaryResponse =
6664                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6665                                mContext, mInstantAppResolverConnection, requestObject);
6666                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6667            } else {
6668                // we have an instant application locally, but, we can't admit that since
6669                // callers shouldn't be able to determine prior browsing. create a dummy
6670                // auxiliary response so the downstream code behaves as if there's an
6671                // instant application available externally. when it comes time to start
6672                // the instant application, we'll do the right thing.
6673                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6674                auxiliaryResponse = new AuxiliaryResolveInfo(
6675                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6676                        ai.versionCode, null /*failureIntent*/);
6677            }
6678        }
6679        if (auxiliaryResponse != null) {
6680            if (DEBUG_EPHEMERAL) {
6681                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6682            }
6683            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6684            final PackageSetting ps =
6685                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6686            if (ps != null) {
6687                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6688                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6689                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6690                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6691                // make sure this resolver is the default
6692                ephemeralInstaller.isDefault = true;
6693                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6694                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6695                // add a non-generic filter
6696                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6697                ephemeralInstaller.filter.addDataPath(
6698                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6699                ephemeralInstaller.isInstantAppAvailable = true;
6700                result.add(ephemeralInstaller);
6701            }
6702        }
6703        return result;
6704    }
6705
6706    private static class CrossProfileDomainInfo {
6707        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6708        ResolveInfo resolveInfo;
6709        /* Best domain verification status of the activities found in the other profile */
6710        int bestDomainVerificationStatus;
6711    }
6712
6713    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6714            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6715        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6716                sourceUserId)) {
6717            return null;
6718        }
6719        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6720                resolvedType, flags, parentUserId);
6721
6722        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6723            return null;
6724        }
6725        CrossProfileDomainInfo result = null;
6726        int size = resultTargetUser.size();
6727        for (int i = 0; i < size; i++) {
6728            ResolveInfo riTargetUser = resultTargetUser.get(i);
6729            // Intent filter verification is only for filters that specify a host. So don't return
6730            // those that handle all web uris.
6731            if (riTargetUser.handleAllWebDataURI) {
6732                continue;
6733            }
6734            String packageName = riTargetUser.activityInfo.packageName;
6735            PackageSetting ps = mSettings.mPackages.get(packageName);
6736            if (ps == null) {
6737                continue;
6738            }
6739            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6740            int status = (int)(verificationState >> 32);
6741            if (result == null) {
6742                result = new CrossProfileDomainInfo();
6743                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6744                        sourceUserId, parentUserId);
6745                result.bestDomainVerificationStatus = status;
6746            } else {
6747                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6748                        result.bestDomainVerificationStatus);
6749            }
6750        }
6751        // Don't consider matches with status NEVER across profiles.
6752        if (result != null && result.bestDomainVerificationStatus
6753                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6754            return null;
6755        }
6756        return result;
6757    }
6758
6759    /**
6760     * Verification statuses are ordered from the worse to the best, except for
6761     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6762     */
6763    private int bestDomainVerificationStatus(int status1, int status2) {
6764        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6765            return status2;
6766        }
6767        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6768            return status1;
6769        }
6770        return (int) MathUtils.max(status1, status2);
6771    }
6772
6773    private boolean isUserEnabled(int userId) {
6774        long callingId = Binder.clearCallingIdentity();
6775        try {
6776            UserInfo userInfo = sUserManager.getUserInfo(userId);
6777            return userInfo != null && userInfo.isEnabled();
6778        } finally {
6779            Binder.restoreCallingIdentity(callingId);
6780        }
6781    }
6782
6783    /**
6784     * Filter out activities with systemUserOnly flag set, when current user is not System.
6785     *
6786     * @return filtered list
6787     */
6788    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6789        if (userId == UserHandle.USER_SYSTEM) {
6790            return resolveInfos;
6791        }
6792        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6793            ResolveInfo info = resolveInfos.get(i);
6794            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6795                resolveInfos.remove(i);
6796            }
6797        }
6798        return resolveInfos;
6799    }
6800
6801    /**
6802     * Filters out ephemeral activities.
6803     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6804     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6805     *
6806     * @param resolveInfos The pre-filtered list of resolved activities
6807     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6808     *          is performed.
6809     * @return A filtered list of resolved activities.
6810     */
6811    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6812            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6813        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6814            final ResolveInfo info = resolveInfos.get(i);
6815            // allow activities that are defined in the provided package
6816            if (allowDynamicSplits
6817                    && info.activityInfo.splitName != null
6818                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6819                            info.activityInfo.splitName)) {
6820                if (mInstantAppInstallerInfo == null) {
6821                    if (DEBUG_INSTALL) {
6822                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6823                    }
6824                    resolveInfos.remove(i);
6825                    continue;
6826                }
6827                // requested activity is defined in a split that hasn't been installed yet.
6828                // add the installer to the resolve list
6829                if (DEBUG_INSTALL) {
6830                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6831                }
6832                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6833                final ComponentName installFailureActivity = findInstallFailureActivity(
6834                        info.activityInfo.packageName,  filterCallingUid, userId);
6835                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6836                        info.activityInfo.packageName, info.activityInfo.splitName,
6837                        installFailureActivity,
6838                        info.activityInfo.applicationInfo.versionCode,
6839                        null /*failureIntent*/);
6840                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6841                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6842                // add a non-generic filter
6843                installerInfo.filter = new IntentFilter();
6844
6845                // This resolve info may appear in the chooser UI, so let us make it
6846                // look as the one it replaces as far as the user is concerned which
6847                // requires loading the correct label and icon for the resolve info.
6848                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6849                installerInfo.labelRes = info.resolveLabelResId();
6850                installerInfo.icon = info.resolveIconResId();
6851
6852                // propagate priority/preferred order/default
6853                installerInfo.priority = info.priority;
6854                installerInfo.preferredOrder = info.preferredOrder;
6855                installerInfo.isDefault = info.isDefault;
6856                resolveInfos.set(i, installerInfo);
6857                continue;
6858            }
6859            // caller is a full app, don't need to apply any other filtering
6860            if (ephemeralPkgName == null) {
6861                continue;
6862            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6863                // caller is same app; don't need to apply any other filtering
6864                continue;
6865            }
6866            // allow activities that have been explicitly exposed to ephemeral apps
6867            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6868            if (!isEphemeralApp
6869                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6870                continue;
6871            }
6872            resolveInfos.remove(i);
6873        }
6874        return resolveInfos;
6875    }
6876
6877    /**
6878     * Returns the activity component that can handle install failures.
6879     * <p>By default, the instant application installer handles failures. However, an
6880     * application may want to handle failures on its own. Applications do this by
6881     * creating an activity with an intent filter that handles the action
6882     * {@link Intent#ACTION_INSTALL_FAILURE}.
6883     */
6884    private @Nullable ComponentName findInstallFailureActivity(
6885            String packageName, int filterCallingUid, int userId) {
6886        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6887        failureActivityIntent.setPackage(packageName);
6888        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6889        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6890                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6891                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6892        final int NR = result.size();
6893        if (NR > 0) {
6894            for (int i = 0; i < NR; i++) {
6895                final ResolveInfo info = result.get(i);
6896                if (info.activityInfo.splitName != null) {
6897                    continue;
6898                }
6899                return new ComponentName(packageName, info.activityInfo.name);
6900            }
6901        }
6902        return null;
6903    }
6904
6905    /**
6906     * @param resolveInfos list of resolve infos in descending priority order
6907     * @return if the list contains a resolve info with non-negative priority
6908     */
6909    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6910        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6911    }
6912
6913    private static boolean hasWebURI(Intent intent) {
6914        if (intent.getData() == null) {
6915            return false;
6916        }
6917        final String scheme = intent.getScheme();
6918        if (TextUtils.isEmpty(scheme)) {
6919            return false;
6920        }
6921        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6922    }
6923
6924    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6925            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6926            int userId) {
6927        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6928
6929        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6930            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6931                    candidates.size());
6932        }
6933
6934        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6935        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6936        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6937        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6938        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6939        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6940
6941        synchronized (mPackages) {
6942            final int count = candidates.size();
6943            // First, try to use linked apps. Partition the candidates into four lists:
6944            // one for the final results, one for the "do not use ever", one for "undefined status"
6945            // and finally one for "browser app type".
6946            for (int n=0; n<count; n++) {
6947                ResolveInfo info = candidates.get(n);
6948                String packageName = info.activityInfo.packageName;
6949                PackageSetting ps = mSettings.mPackages.get(packageName);
6950                if (ps != null) {
6951                    // Add to the special match all list (Browser use case)
6952                    if (info.handleAllWebDataURI) {
6953                        matchAllList.add(info);
6954                        continue;
6955                    }
6956                    // Try to get the status from User settings first
6957                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6958                    int status = (int)(packedStatus >> 32);
6959                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6960                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6961                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6962                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6963                                    + " : linkgen=" + linkGeneration);
6964                        }
6965                        // Use link-enabled generation as preferredOrder, i.e.
6966                        // prefer newly-enabled over earlier-enabled.
6967                        info.preferredOrder = linkGeneration;
6968                        alwaysList.add(info);
6969                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6970                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6971                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6972                        }
6973                        neverList.add(info);
6974                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6975                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6976                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6977                        }
6978                        alwaysAskList.add(info);
6979                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6980                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6981                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6982                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6983                        }
6984                        undefinedList.add(info);
6985                    }
6986                }
6987            }
6988
6989            // We'll want to include browser possibilities in a few cases
6990            boolean includeBrowser = false;
6991
6992            // First try to add the "always" resolution(s) for the current user, if any
6993            if (alwaysList.size() > 0) {
6994                result.addAll(alwaysList);
6995            } else {
6996                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6997                result.addAll(undefinedList);
6998                // Maybe add one for the other profile.
6999                if (xpDomainInfo != null && (
7000                        xpDomainInfo.bestDomainVerificationStatus
7001                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7002                    result.add(xpDomainInfo.resolveInfo);
7003                }
7004                includeBrowser = true;
7005            }
7006
7007            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7008            // If there were 'always' entries their preferred order has been set, so we also
7009            // back that off to make the alternatives equivalent
7010            if (alwaysAskList.size() > 0) {
7011                for (ResolveInfo i : result) {
7012                    i.preferredOrder = 0;
7013                }
7014                result.addAll(alwaysAskList);
7015                includeBrowser = true;
7016            }
7017
7018            if (includeBrowser) {
7019                // Also add browsers (all of them or only the default one)
7020                if (DEBUG_DOMAIN_VERIFICATION) {
7021                    Slog.v(TAG, "   ...including browsers in candidate set");
7022                }
7023                if ((matchFlags & MATCH_ALL) != 0) {
7024                    result.addAll(matchAllList);
7025                } else {
7026                    // Browser/generic handling case.  If there's a default browser, go straight
7027                    // to that (but only if there is no other higher-priority match).
7028                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7029                    int maxMatchPrio = 0;
7030                    ResolveInfo defaultBrowserMatch = null;
7031                    final int numCandidates = matchAllList.size();
7032                    for (int n = 0; n < numCandidates; n++) {
7033                        ResolveInfo info = matchAllList.get(n);
7034                        // track the highest overall match priority...
7035                        if (info.priority > maxMatchPrio) {
7036                            maxMatchPrio = info.priority;
7037                        }
7038                        // ...and the highest-priority default browser match
7039                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7040                            if (defaultBrowserMatch == null
7041                                    || (defaultBrowserMatch.priority < info.priority)) {
7042                                if (debug) {
7043                                    Slog.v(TAG, "Considering default browser match " + info);
7044                                }
7045                                defaultBrowserMatch = info;
7046                            }
7047                        }
7048                    }
7049                    if (defaultBrowserMatch != null
7050                            && defaultBrowserMatch.priority >= maxMatchPrio
7051                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7052                    {
7053                        if (debug) {
7054                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7055                        }
7056                        result.add(defaultBrowserMatch);
7057                    } else {
7058                        result.addAll(matchAllList);
7059                    }
7060                }
7061
7062                // If there is nothing selected, add all candidates and remove the ones that the user
7063                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7064                if (result.size() == 0) {
7065                    result.addAll(candidates);
7066                    result.removeAll(neverList);
7067                }
7068            }
7069        }
7070        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7071            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7072                    result.size());
7073            for (ResolveInfo info : result) {
7074                Slog.v(TAG, "  + " + info.activityInfo);
7075            }
7076        }
7077        return result;
7078    }
7079
7080    // Returns a packed value as a long:
7081    //
7082    // high 'int'-sized word: link status: undefined/ask/never/always.
7083    // low 'int'-sized word: relative priority among 'always' results.
7084    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7085        long result = ps.getDomainVerificationStatusForUser(userId);
7086        // if none available, get the master status
7087        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7088            if (ps.getIntentFilterVerificationInfo() != null) {
7089                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7090            }
7091        }
7092        return result;
7093    }
7094
7095    private ResolveInfo querySkipCurrentProfileIntents(
7096            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7097            int flags, int sourceUserId) {
7098        if (matchingFilters != null) {
7099            int size = matchingFilters.size();
7100            for (int i = 0; i < size; i ++) {
7101                CrossProfileIntentFilter filter = matchingFilters.get(i);
7102                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7103                    // Checking if there are activities in the target user that can handle the
7104                    // intent.
7105                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7106                            resolvedType, flags, sourceUserId);
7107                    if (resolveInfo != null) {
7108                        return resolveInfo;
7109                    }
7110                }
7111            }
7112        }
7113        return null;
7114    }
7115
7116    // Return matching ResolveInfo in target user if any.
7117    private ResolveInfo queryCrossProfileIntents(
7118            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7119            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7120        if (matchingFilters != null) {
7121            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7122            // match the same intent. For performance reasons, it is better not to
7123            // run queryIntent twice for the same userId
7124            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7125            int size = matchingFilters.size();
7126            for (int i = 0; i < size; i++) {
7127                CrossProfileIntentFilter filter = matchingFilters.get(i);
7128                int targetUserId = filter.getTargetUserId();
7129                boolean skipCurrentProfile =
7130                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7131                boolean skipCurrentProfileIfNoMatchFound =
7132                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7133                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7134                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7135                    // Checking if there are activities in the target user that can handle the
7136                    // intent.
7137                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7138                            resolvedType, flags, sourceUserId);
7139                    if (resolveInfo != null) return resolveInfo;
7140                    alreadyTriedUserIds.put(targetUserId, true);
7141                }
7142            }
7143        }
7144        return null;
7145    }
7146
7147    /**
7148     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7149     * will forward the intent to the filter's target user.
7150     * Otherwise, returns null.
7151     */
7152    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7153            String resolvedType, int flags, int sourceUserId) {
7154        int targetUserId = filter.getTargetUserId();
7155        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7156                resolvedType, flags, targetUserId);
7157        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7158            // If all the matches in the target profile are suspended, return null.
7159            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7160                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7161                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7162                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7163                            targetUserId);
7164                }
7165            }
7166        }
7167        return null;
7168    }
7169
7170    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7171            int sourceUserId, int targetUserId) {
7172        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7173        long ident = Binder.clearCallingIdentity();
7174        boolean targetIsProfile;
7175        try {
7176            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7177        } finally {
7178            Binder.restoreCallingIdentity(ident);
7179        }
7180        String className;
7181        if (targetIsProfile) {
7182            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7183        } else {
7184            className = FORWARD_INTENT_TO_PARENT;
7185        }
7186        ComponentName forwardingActivityComponentName = new ComponentName(
7187                mAndroidApplication.packageName, className);
7188        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7189                sourceUserId);
7190        if (!targetIsProfile) {
7191            forwardingActivityInfo.showUserIcon = targetUserId;
7192            forwardingResolveInfo.noResourceId = true;
7193        }
7194        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7195        forwardingResolveInfo.priority = 0;
7196        forwardingResolveInfo.preferredOrder = 0;
7197        forwardingResolveInfo.match = 0;
7198        forwardingResolveInfo.isDefault = true;
7199        forwardingResolveInfo.filter = filter;
7200        forwardingResolveInfo.targetUserId = targetUserId;
7201        return forwardingResolveInfo;
7202    }
7203
7204    @Override
7205    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7206            Intent[] specifics, String[] specificTypes, Intent intent,
7207            String resolvedType, int flags, int userId) {
7208        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7209                specificTypes, intent, resolvedType, flags, userId));
7210    }
7211
7212    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7213            Intent[] specifics, String[] specificTypes, Intent intent,
7214            String resolvedType, int flags, int userId) {
7215        if (!sUserManager.exists(userId)) return Collections.emptyList();
7216        final int callingUid = Binder.getCallingUid();
7217        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7218                false /*includeInstantApps*/);
7219        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7220                false /*requireFullPermission*/, false /*checkShell*/,
7221                "query intent activity options");
7222        final String resultsAction = intent.getAction();
7223
7224        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7225                | PackageManager.GET_RESOLVED_FILTER, userId);
7226
7227        if (DEBUG_INTENT_MATCHING) {
7228            Log.v(TAG, "Query " + intent + ": " + results);
7229        }
7230
7231        int specificsPos = 0;
7232        int N;
7233
7234        // todo: note that the algorithm used here is O(N^2).  This
7235        // isn't a problem in our current environment, but if we start running
7236        // into situations where we have more than 5 or 10 matches then this
7237        // should probably be changed to something smarter...
7238
7239        // First we go through and resolve each of the specific items
7240        // that were supplied, taking care of removing any corresponding
7241        // duplicate items in the generic resolve list.
7242        if (specifics != null) {
7243            for (int i=0; i<specifics.length; i++) {
7244                final Intent sintent = specifics[i];
7245                if (sintent == null) {
7246                    continue;
7247                }
7248
7249                if (DEBUG_INTENT_MATCHING) {
7250                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7251                }
7252
7253                String action = sintent.getAction();
7254                if (resultsAction != null && resultsAction.equals(action)) {
7255                    // If this action was explicitly requested, then don't
7256                    // remove things that have it.
7257                    action = null;
7258                }
7259
7260                ResolveInfo ri = null;
7261                ActivityInfo ai = null;
7262
7263                ComponentName comp = sintent.getComponent();
7264                if (comp == null) {
7265                    ri = resolveIntent(
7266                        sintent,
7267                        specificTypes != null ? specificTypes[i] : null,
7268                            flags, userId);
7269                    if (ri == null) {
7270                        continue;
7271                    }
7272                    if (ri == mResolveInfo) {
7273                        // ACK!  Must do something better with this.
7274                    }
7275                    ai = ri.activityInfo;
7276                    comp = new ComponentName(ai.applicationInfo.packageName,
7277                            ai.name);
7278                } else {
7279                    ai = getActivityInfo(comp, flags, userId);
7280                    if (ai == null) {
7281                        continue;
7282                    }
7283                }
7284
7285                // Look for any generic query activities that are duplicates
7286                // of this specific one, and remove them from the results.
7287                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7288                N = results.size();
7289                int j;
7290                for (j=specificsPos; j<N; j++) {
7291                    ResolveInfo sri = results.get(j);
7292                    if ((sri.activityInfo.name.equals(comp.getClassName())
7293                            && sri.activityInfo.applicationInfo.packageName.equals(
7294                                    comp.getPackageName()))
7295                        || (action != null && sri.filter.matchAction(action))) {
7296                        results.remove(j);
7297                        if (DEBUG_INTENT_MATCHING) Log.v(
7298                            TAG, "Removing duplicate item from " + j
7299                            + " due to specific " + specificsPos);
7300                        if (ri == null) {
7301                            ri = sri;
7302                        }
7303                        j--;
7304                        N--;
7305                    }
7306                }
7307
7308                // Add this specific item to its proper place.
7309                if (ri == null) {
7310                    ri = new ResolveInfo();
7311                    ri.activityInfo = ai;
7312                }
7313                results.add(specificsPos, ri);
7314                ri.specificIndex = i;
7315                specificsPos++;
7316            }
7317        }
7318
7319        // Now we go through the remaining generic results and remove any
7320        // duplicate actions that are found here.
7321        N = results.size();
7322        for (int i=specificsPos; i<N-1; i++) {
7323            final ResolveInfo rii = results.get(i);
7324            if (rii.filter == null) {
7325                continue;
7326            }
7327
7328            // Iterate over all of the actions of this result's intent
7329            // filter...  typically this should be just one.
7330            final Iterator<String> it = rii.filter.actionsIterator();
7331            if (it == null) {
7332                continue;
7333            }
7334            while (it.hasNext()) {
7335                final String action = it.next();
7336                if (resultsAction != null && resultsAction.equals(action)) {
7337                    // If this action was explicitly requested, then don't
7338                    // remove things that have it.
7339                    continue;
7340                }
7341                for (int j=i+1; j<N; j++) {
7342                    final ResolveInfo rij = results.get(j);
7343                    if (rij.filter != null && rij.filter.hasAction(action)) {
7344                        results.remove(j);
7345                        if (DEBUG_INTENT_MATCHING) Log.v(
7346                            TAG, "Removing duplicate item from " + j
7347                            + " due to action " + action + " at " + i);
7348                        j--;
7349                        N--;
7350                    }
7351                }
7352            }
7353
7354            // If the caller didn't request filter information, drop it now
7355            // so we don't have to marshall/unmarshall it.
7356            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7357                rii.filter = null;
7358            }
7359        }
7360
7361        // Filter out the caller activity if so requested.
7362        if (caller != null) {
7363            N = results.size();
7364            for (int i=0; i<N; i++) {
7365                ActivityInfo ainfo = results.get(i).activityInfo;
7366                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7367                        && caller.getClassName().equals(ainfo.name)) {
7368                    results.remove(i);
7369                    break;
7370                }
7371            }
7372        }
7373
7374        // If the caller didn't request filter information,
7375        // drop them now so we don't have to
7376        // marshall/unmarshall it.
7377        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7378            N = results.size();
7379            for (int i=0; i<N; i++) {
7380                results.get(i).filter = null;
7381            }
7382        }
7383
7384        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7385        return results;
7386    }
7387
7388    @Override
7389    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7390            String resolvedType, int flags, int userId) {
7391        return new ParceledListSlice<>(
7392                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7393                        false /*allowDynamicSplits*/));
7394    }
7395
7396    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7397            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7398        if (!sUserManager.exists(userId)) return Collections.emptyList();
7399        final int callingUid = Binder.getCallingUid();
7400        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7401                false /*requireFullPermission*/, false /*checkShell*/,
7402                "query intent receivers");
7403        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7404        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7405                false /*includeInstantApps*/);
7406        ComponentName comp = intent.getComponent();
7407        if (comp == null) {
7408            if (intent.getSelector() != null) {
7409                intent = intent.getSelector();
7410                comp = intent.getComponent();
7411            }
7412        }
7413        if (comp != null) {
7414            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7415            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7416            if (ai != null) {
7417                // When specifying an explicit component, we prevent the activity from being
7418                // used when either 1) the calling package is normal and the activity is within
7419                // an instant application or 2) the calling package is ephemeral and the
7420                // activity is not visible to instant applications.
7421                final boolean matchInstantApp =
7422                        (flags & PackageManager.MATCH_INSTANT) != 0;
7423                final boolean matchVisibleToInstantAppOnly =
7424                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7425                final boolean matchExplicitlyVisibleOnly =
7426                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7427                final boolean isCallerInstantApp =
7428                        instantAppPkgName != null;
7429                final boolean isTargetSameInstantApp =
7430                        comp.getPackageName().equals(instantAppPkgName);
7431                final boolean isTargetInstantApp =
7432                        (ai.applicationInfo.privateFlags
7433                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7434                final boolean isTargetVisibleToInstantApp =
7435                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7436                final boolean isTargetExplicitlyVisibleToInstantApp =
7437                        isTargetVisibleToInstantApp
7438                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7439                final boolean isTargetHiddenFromInstantApp =
7440                        !isTargetVisibleToInstantApp
7441                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7442                final boolean blockResolution =
7443                        !isTargetSameInstantApp
7444                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7445                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7446                                        && isTargetHiddenFromInstantApp));
7447                if (!blockResolution) {
7448                    ResolveInfo ri = new ResolveInfo();
7449                    ri.activityInfo = ai;
7450                    list.add(ri);
7451                }
7452            }
7453            return applyPostResolutionFilter(
7454                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7455        }
7456
7457        // reader
7458        synchronized (mPackages) {
7459            String pkgName = intent.getPackage();
7460            if (pkgName == null) {
7461                final List<ResolveInfo> result =
7462                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7463                return applyPostResolutionFilter(
7464                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7465            }
7466            final PackageParser.Package pkg = mPackages.get(pkgName);
7467            if (pkg != null) {
7468                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7469                        intent, resolvedType, flags, pkg.receivers, userId);
7470                return applyPostResolutionFilter(
7471                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7472            }
7473            return Collections.emptyList();
7474        }
7475    }
7476
7477    @Override
7478    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7479        final int callingUid = Binder.getCallingUid();
7480        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7481    }
7482
7483    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7484            int userId, int callingUid) {
7485        if (!sUserManager.exists(userId)) return null;
7486        flags = updateFlagsForResolve(
7487                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7488        List<ResolveInfo> query = queryIntentServicesInternal(
7489                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7490        if (query != null) {
7491            if (query.size() >= 1) {
7492                // If there is more than one service with the same priority,
7493                // just arbitrarily pick the first one.
7494                return query.get(0);
7495            }
7496        }
7497        return null;
7498    }
7499
7500    @Override
7501    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7502            String resolvedType, int flags, int userId) {
7503        final int callingUid = Binder.getCallingUid();
7504        return new ParceledListSlice<>(queryIntentServicesInternal(
7505                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7506    }
7507
7508    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7509            String resolvedType, int flags, int userId, int callingUid,
7510            boolean includeInstantApps) {
7511        if (!sUserManager.exists(userId)) return Collections.emptyList();
7512        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7513                false /*requireFullPermission*/, false /*checkShell*/,
7514                "query intent receivers");
7515        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7516        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7517        ComponentName comp = intent.getComponent();
7518        if (comp == null) {
7519            if (intent.getSelector() != null) {
7520                intent = intent.getSelector();
7521                comp = intent.getComponent();
7522            }
7523        }
7524        if (comp != null) {
7525            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7526            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7527            if (si != null) {
7528                // When specifying an explicit component, we prevent the service from being
7529                // used when either 1) the service is in an instant application and the
7530                // caller is not the same instant application or 2) the calling package is
7531                // ephemeral and the activity is not visible to ephemeral applications.
7532                final boolean matchInstantApp =
7533                        (flags & PackageManager.MATCH_INSTANT) != 0;
7534                final boolean matchVisibleToInstantAppOnly =
7535                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7536                final boolean isCallerInstantApp =
7537                        instantAppPkgName != null;
7538                final boolean isTargetSameInstantApp =
7539                        comp.getPackageName().equals(instantAppPkgName);
7540                final boolean isTargetInstantApp =
7541                        (si.applicationInfo.privateFlags
7542                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7543                final boolean isTargetHiddenFromInstantApp =
7544                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7545                final boolean blockResolution =
7546                        !isTargetSameInstantApp
7547                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7548                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7549                                        && isTargetHiddenFromInstantApp));
7550                if (!blockResolution) {
7551                    final ResolveInfo ri = new ResolveInfo();
7552                    ri.serviceInfo = si;
7553                    list.add(ri);
7554                }
7555            }
7556            return list;
7557        }
7558
7559        // reader
7560        synchronized (mPackages) {
7561            String pkgName = intent.getPackage();
7562            if (pkgName == null) {
7563                return applyPostServiceResolutionFilter(
7564                        mServices.queryIntent(intent, resolvedType, flags, userId),
7565                        instantAppPkgName);
7566            }
7567            final PackageParser.Package pkg = mPackages.get(pkgName);
7568            if (pkg != null) {
7569                return applyPostServiceResolutionFilter(
7570                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7571                                userId),
7572                        instantAppPkgName);
7573            }
7574            return Collections.emptyList();
7575        }
7576    }
7577
7578    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7579            String instantAppPkgName) {
7580        if (instantAppPkgName == null) {
7581            return resolveInfos;
7582        }
7583        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7584            final ResolveInfo info = resolveInfos.get(i);
7585            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7586            // allow services that are defined in the provided package
7587            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7588                if (info.serviceInfo.splitName != null
7589                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7590                                info.serviceInfo.splitName)) {
7591                    // requested service is defined in a split that hasn't been installed yet.
7592                    // add the installer to the resolve list
7593                    if (DEBUG_EPHEMERAL) {
7594                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7595                    }
7596                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7597                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7598                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7599                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7600                            null /*failureIntent*/);
7601                    // make sure this resolver is the default
7602                    installerInfo.isDefault = true;
7603                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7604                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7605                    // add a non-generic filter
7606                    installerInfo.filter = new IntentFilter();
7607                    // load resources from the correct package
7608                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7609                    resolveInfos.set(i, installerInfo);
7610                }
7611                continue;
7612            }
7613            // allow services that have been explicitly exposed to ephemeral apps
7614            if (!isEphemeralApp
7615                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7616                continue;
7617            }
7618            resolveInfos.remove(i);
7619        }
7620        return resolveInfos;
7621    }
7622
7623    @Override
7624    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7625            String resolvedType, int flags, int userId) {
7626        return new ParceledListSlice<>(
7627                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7628    }
7629
7630    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7631            Intent intent, String resolvedType, int flags, int userId) {
7632        if (!sUserManager.exists(userId)) return Collections.emptyList();
7633        final int callingUid = Binder.getCallingUid();
7634        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7635        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7636                false /*includeInstantApps*/);
7637        ComponentName comp = intent.getComponent();
7638        if (comp == null) {
7639            if (intent.getSelector() != null) {
7640                intent = intent.getSelector();
7641                comp = intent.getComponent();
7642            }
7643        }
7644        if (comp != null) {
7645            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7646            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7647            if (pi != null) {
7648                // When specifying an explicit component, we prevent the provider from being
7649                // used when either 1) the provider is in an instant application and the
7650                // caller is not the same instant application or 2) the calling package is an
7651                // instant application and the provider is not visible to instant applications.
7652                final boolean matchInstantApp =
7653                        (flags & PackageManager.MATCH_INSTANT) != 0;
7654                final boolean matchVisibleToInstantAppOnly =
7655                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7656                final boolean isCallerInstantApp =
7657                        instantAppPkgName != null;
7658                final boolean isTargetSameInstantApp =
7659                        comp.getPackageName().equals(instantAppPkgName);
7660                final boolean isTargetInstantApp =
7661                        (pi.applicationInfo.privateFlags
7662                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7663                final boolean isTargetHiddenFromInstantApp =
7664                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7665                final boolean blockResolution =
7666                        !isTargetSameInstantApp
7667                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7668                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7669                                        && isTargetHiddenFromInstantApp));
7670                if (!blockResolution) {
7671                    final ResolveInfo ri = new ResolveInfo();
7672                    ri.providerInfo = pi;
7673                    list.add(ri);
7674                }
7675            }
7676            return list;
7677        }
7678
7679        // reader
7680        synchronized (mPackages) {
7681            String pkgName = intent.getPackage();
7682            if (pkgName == null) {
7683                return applyPostContentProviderResolutionFilter(
7684                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7685                        instantAppPkgName);
7686            }
7687            final PackageParser.Package pkg = mPackages.get(pkgName);
7688            if (pkg != null) {
7689                return applyPostContentProviderResolutionFilter(
7690                        mProviders.queryIntentForPackage(
7691                        intent, resolvedType, flags, pkg.providers, userId),
7692                        instantAppPkgName);
7693            }
7694            return Collections.emptyList();
7695        }
7696    }
7697
7698    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7699            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7700        if (instantAppPkgName == null) {
7701            return resolveInfos;
7702        }
7703        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7704            final ResolveInfo info = resolveInfos.get(i);
7705            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7706            // allow providers that are defined in the provided package
7707            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7708                if (info.providerInfo.splitName != null
7709                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7710                                info.providerInfo.splitName)) {
7711                    // requested provider is defined in a split that hasn't been installed yet.
7712                    // add the installer to the resolve list
7713                    if (DEBUG_EPHEMERAL) {
7714                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7715                    }
7716                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7717                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7718                            info.providerInfo.packageName, info.providerInfo.splitName,
7719                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7720                            null /*failureIntent*/);
7721                    // make sure this resolver is the default
7722                    installerInfo.isDefault = true;
7723                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7724                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7725                    // add a non-generic filter
7726                    installerInfo.filter = new IntentFilter();
7727                    // load resources from the correct package
7728                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7729                    resolveInfos.set(i, installerInfo);
7730                }
7731                continue;
7732            }
7733            // allow providers that have been explicitly exposed to instant applications
7734            if (!isEphemeralApp
7735                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7736                continue;
7737            }
7738            resolveInfos.remove(i);
7739        }
7740        return resolveInfos;
7741    }
7742
7743    @Override
7744    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7745        final int callingUid = Binder.getCallingUid();
7746        if (getInstantAppPackageName(callingUid) != null) {
7747            return ParceledListSlice.emptyList();
7748        }
7749        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7750        flags = updateFlagsForPackage(flags, userId, null);
7751        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7752        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7753                true /* requireFullPermission */, false /* checkShell */,
7754                "get installed packages");
7755
7756        // writer
7757        synchronized (mPackages) {
7758            ArrayList<PackageInfo> list;
7759            if (listUninstalled) {
7760                list = new ArrayList<>(mSettings.mPackages.size());
7761                for (PackageSetting ps : mSettings.mPackages.values()) {
7762                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7763                        continue;
7764                    }
7765                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7766                        continue;
7767                    }
7768                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7769                    if (pi != null) {
7770                        list.add(pi);
7771                    }
7772                }
7773            } else {
7774                list = new ArrayList<>(mPackages.size());
7775                for (PackageParser.Package p : mPackages.values()) {
7776                    final PackageSetting ps = (PackageSetting) p.mExtras;
7777                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7778                        continue;
7779                    }
7780                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7781                        continue;
7782                    }
7783                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7784                            p.mExtras, flags, userId);
7785                    if (pi != null) {
7786                        list.add(pi);
7787                    }
7788                }
7789            }
7790
7791            return new ParceledListSlice<>(list);
7792        }
7793    }
7794
7795    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7796            String[] permissions, boolean[] tmp, int flags, int userId) {
7797        int numMatch = 0;
7798        final PermissionsState permissionsState = ps.getPermissionsState();
7799        for (int i=0; i<permissions.length; i++) {
7800            final String permission = permissions[i];
7801            if (permissionsState.hasPermission(permission, userId)) {
7802                tmp[i] = true;
7803                numMatch++;
7804            } else {
7805                tmp[i] = false;
7806            }
7807        }
7808        if (numMatch == 0) {
7809            return;
7810        }
7811        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7812
7813        // The above might return null in cases of uninstalled apps or install-state
7814        // skew across users/profiles.
7815        if (pi != null) {
7816            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7817                if (numMatch == permissions.length) {
7818                    pi.requestedPermissions = permissions;
7819                } else {
7820                    pi.requestedPermissions = new String[numMatch];
7821                    numMatch = 0;
7822                    for (int i=0; i<permissions.length; i++) {
7823                        if (tmp[i]) {
7824                            pi.requestedPermissions[numMatch] = permissions[i];
7825                            numMatch++;
7826                        }
7827                    }
7828                }
7829            }
7830            list.add(pi);
7831        }
7832    }
7833
7834    @Override
7835    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7836            String[] permissions, int flags, int userId) {
7837        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7838        flags = updateFlagsForPackage(flags, userId, permissions);
7839        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7840                true /* requireFullPermission */, false /* checkShell */,
7841                "get packages holding permissions");
7842        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7843
7844        // writer
7845        synchronized (mPackages) {
7846            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7847            boolean[] tmpBools = new boolean[permissions.length];
7848            if (listUninstalled) {
7849                for (PackageSetting ps : mSettings.mPackages.values()) {
7850                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7851                            userId);
7852                }
7853            } else {
7854                for (PackageParser.Package pkg : mPackages.values()) {
7855                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7856                    if (ps != null) {
7857                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7858                                userId);
7859                    }
7860                }
7861            }
7862
7863            return new ParceledListSlice<PackageInfo>(list);
7864        }
7865    }
7866
7867    @Override
7868    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7869        final int callingUid = Binder.getCallingUid();
7870        if (getInstantAppPackageName(callingUid) != null) {
7871            return ParceledListSlice.emptyList();
7872        }
7873        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7874        flags = updateFlagsForApplication(flags, userId, null);
7875        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7876
7877        // writer
7878        synchronized (mPackages) {
7879            ArrayList<ApplicationInfo> list;
7880            if (listUninstalled) {
7881                list = new ArrayList<>(mSettings.mPackages.size());
7882                for (PackageSetting ps : mSettings.mPackages.values()) {
7883                    ApplicationInfo ai;
7884                    int effectiveFlags = flags;
7885                    if (ps.isSystem()) {
7886                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7887                    }
7888                    if (ps.pkg != null) {
7889                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7890                            continue;
7891                        }
7892                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7893                            continue;
7894                        }
7895                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7896                                ps.readUserState(userId), userId);
7897                        if (ai != null) {
7898                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7899                        }
7900                    } else {
7901                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7902                        // and already converts to externally visible package name
7903                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7904                                callingUid, effectiveFlags, userId);
7905                    }
7906                    if (ai != null) {
7907                        list.add(ai);
7908                    }
7909                }
7910            } else {
7911                list = new ArrayList<>(mPackages.size());
7912                for (PackageParser.Package p : mPackages.values()) {
7913                    if (p.mExtras != null) {
7914                        PackageSetting ps = (PackageSetting) p.mExtras;
7915                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7916                            continue;
7917                        }
7918                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7919                            continue;
7920                        }
7921                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7922                                ps.readUserState(userId), userId);
7923                        if (ai != null) {
7924                            ai.packageName = resolveExternalPackageNameLPr(p);
7925                            list.add(ai);
7926                        }
7927                    }
7928                }
7929            }
7930
7931            return new ParceledListSlice<>(list);
7932        }
7933    }
7934
7935    @Override
7936    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7937        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7938            return null;
7939        }
7940        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7941            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7942                    "getEphemeralApplications");
7943        }
7944        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7945                true /* requireFullPermission */, false /* checkShell */,
7946                "getEphemeralApplications");
7947        synchronized (mPackages) {
7948            List<InstantAppInfo> instantApps = mInstantAppRegistry
7949                    .getInstantAppsLPr(userId);
7950            if (instantApps != null) {
7951                return new ParceledListSlice<>(instantApps);
7952            }
7953        }
7954        return null;
7955    }
7956
7957    @Override
7958    public boolean isInstantApp(String packageName, int userId) {
7959        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7960                true /* requireFullPermission */, false /* checkShell */,
7961                "isInstantApp");
7962        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7963            return false;
7964        }
7965
7966        synchronized (mPackages) {
7967            int callingUid = Binder.getCallingUid();
7968            if (Process.isIsolated(callingUid)) {
7969                callingUid = mIsolatedOwners.get(callingUid);
7970            }
7971            final PackageSetting ps = mSettings.mPackages.get(packageName);
7972            PackageParser.Package pkg = mPackages.get(packageName);
7973            final boolean returnAllowed =
7974                    ps != null
7975                    && (isCallerSameApp(packageName, callingUid)
7976                            || canViewInstantApps(callingUid, userId)
7977                            || mInstantAppRegistry.isInstantAccessGranted(
7978                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7979            if (returnAllowed) {
7980                return ps.getInstantApp(userId);
7981            }
7982        }
7983        return false;
7984    }
7985
7986    @Override
7987    public byte[] getInstantAppCookie(String packageName, int userId) {
7988        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7989            return null;
7990        }
7991
7992        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7993                true /* requireFullPermission */, false /* checkShell */,
7994                "getInstantAppCookie");
7995        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7996            return null;
7997        }
7998        synchronized (mPackages) {
7999            return mInstantAppRegistry.getInstantAppCookieLPw(
8000                    packageName, userId);
8001        }
8002    }
8003
8004    @Override
8005    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8006        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8007            return true;
8008        }
8009
8010        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8011                true /* requireFullPermission */, true /* checkShell */,
8012                "setInstantAppCookie");
8013        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8014            return false;
8015        }
8016        synchronized (mPackages) {
8017            return mInstantAppRegistry.setInstantAppCookieLPw(
8018                    packageName, cookie, userId);
8019        }
8020    }
8021
8022    @Override
8023    public Bitmap getInstantAppIcon(String packageName, int userId) {
8024        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8025            return null;
8026        }
8027
8028        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8029            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8030                    "getInstantAppIcon");
8031        }
8032        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8033                true /* requireFullPermission */, false /* checkShell */,
8034                "getInstantAppIcon");
8035
8036        synchronized (mPackages) {
8037            return mInstantAppRegistry.getInstantAppIconLPw(
8038                    packageName, userId);
8039        }
8040    }
8041
8042    private boolean isCallerSameApp(String packageName, int uid) {
8043        PackageParser.Package pkg = mPackages.get(packageName);
8044        return pkg != null
8045                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8046    }
8047
8048    @Override
8049    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8050        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8051            return ParceledListSlice.emptyList();
8052        }
8053        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8054    }
8055
8056    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8057        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8058
8059        // reader
8060        synchronized (mPackages) {
8061            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8062            final int userId = UserHandle.getCallingUserId();
8063            while (i.hasNext()) {
8064                final PackageParser.Package p = i.next();
8065                if (p.applicationInfo == null) continue;
8066
8067                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8068                        && !p.applicationInfo.isDirectBootAware();
8069                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8070                        && p.applicationInfo.isDirectBootAware();
8071
8072                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8073                        && (!mSafeMode || isSystemApp(p))
8074                        && (matchesUnaware || matchesAware)) {
8075                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8076                    if (ps != null) {
8077                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8078                                ps.readUserState(userId), userId);
8079                        if (ai != null) {
8080                            finalList.add(ai);
8081                        }
8082                    }
8083                }
8084            }
8085        }
8086
8087        return finalList;
8088    }
8089
8090    @Override
8091    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8092        return resolveContentProviderInternal(name, flags, userId);
8093    }
8094
8095    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8096        if (!sUserManager.exists(userId)) return null;
8097        flags = updateFlagsForComponent(flags, userId, name);
8098        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8099        // reader
8100        synchronized (mPackages) {
8101            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8102            PackageSetting ps = provider != null
8103                    ? mSettings.mPackages.get(provider.owner.packageName)
8104                    : null;
8105            if (ps != null) {
8106                final boolean isInstantApp = ps.getInstantApp(userId);
8107                // normal application; filter out instant application provider
8108                if (instantAppPkgName == null && isInstantApp) {
8109                    return null;
8110                }
8111                // instant application; filter out other instant applications
8112                if (instantAppPkgName != null
8113                        && isInstantApp
8114                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8115                    return null;
8116                }
8117                // instant application; filter out non-exposed provider
8118                if (instantAppPkgName != null
8119                        && !isInstantApp
8120                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8121                    return null;
8122                }
8123                // provider not enabled
8124                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8125                    return null;
8126                }
8127                return PackageParser.generateProviderInfo(
8128                        provider, flags, ps.readUserState(userId), userId);
8129            }
8130            return null;
8131        }
8132    }
8133
8134    /**
8135     * @deprecated
8136     */
8137    @Deprecated
8138    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8139        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8140            return;
8141        }
8142        // reader
8143        synchronized (mPackages) {
8144            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8145                    .entrySet().iterator();
8146            final int userId = UserHandle.getCallingUserId();
8147            while (i.hasNext()) {
8148                Map.Entry<String, PackageParser.Provider> entry = i.next();
8149                PackageParser.Provider p = entry.getValue();
8150                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8151
8152                if (ps != null && p.syncable
8153                        && (!mSafeMode || (p.info.applicationInfo.flags
8154                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8155                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8156                            ps.readUserState(userId), userId);
8157                    if (info != null) {
8158                        outNames.add(entry.getKey());
8159                        outInfo.add(info);
8160                    }
8161                }
8162            }
8163        }
8164    }
8165
8166    @Override
8167    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8168            int uid, int flags, String metaDataKey) {
8169        final int callingUid = Binder.getCallingUid();
8170        final int userId = processName != null ? UserHandle.getUserId(uid)
8171                : UserHandle.getCallingUserId();
8172        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8173        flags = updateFlagsForComponent(flags, userId, processName);
8174        ArrayList<ProviderInfo> finalList = null;
8175        // reader
8176        synchronized (mPackages) {
8177            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8178            while (i.hasNext()) {
8179                final PackageParser.Provider p = i.next();
8180                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8181                if (ps != null && p.info.authority != null
8182                        && (processName == null
8183                                || (p.info.processName.equals(processName)
8184                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8185                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8186
8187                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8188                    // parameter.
8189                    if (metaDataKey != null
8190                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8191                        continue;
8192                    }
8193                    final ComponentName component =
8194                            new ComponentName(p.info.packageName, p.info.name);
8195                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8196                        continue;
8197                    }
8198                    if (finalList == null) {
8199                        finalList = new ArrayList<ProviderInfo>(3);
8200                    }
8201                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8202                            ps.readUserState(userId), userId);
8203                    if (info != null) {
8204                        finalList.add(info);
8205                    }
8206                }
8207            }
8208        }
8209
8210        if (finalList != null) {
8211            Collections.sort(finalList, mProviderInitOrderSorter);
8212            return new ParceledListSlice<ProviderInfo>(finalList);
8213        }
8214
8215        return ParceledListSlice.emptyList();
8216    }
8217
8218    @Override
8219    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8220        // reader
8221        synchronized (mPackages) {
8222            final int callingUid = Binder.getCallingUid();
8223            final int callingUserId = UserHandle.getUserId(callingUid);
8224            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8225            if (ps == null) return null;
8226            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8227                return null;
8228            }
8229            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8230            return PackageParser.generateInstrumentationInfo(i, flags);
8231        }
8232    }
8233
8234    @Override
8235    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8236            String targetPackage, int flags) {
8237        final int callingUid = Binder.getCallingUid();
8238        final int callingUserId = UserHandle.getUserId(callingUid);
8239        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8240        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8241            return ParceledListSlice.emptyList();
8242        }
8243        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8244    }
8245
8246    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8247            int flags) {
8248        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8249
8250        // reader
8251        synchronized (mPackages) {
8252            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8253            while (i.hasNext()) {
8254                final PackageParser.Instrumentation p = i.next();
8255                if (targetPackage == null
8256                        || targetPackage.equals(p.info.targetPackage)) {
8257                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8258                            flags);
8259                    if (ii != null) {
8260                        finalList.add(ii);
8261                    }
8262                }
8263            }
8264        }
8265
8266        return finalList;
8267    }
8268
8269    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8270        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8271        try {
8272            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8273        } finally {
8274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8275        }
8276    }
8277
8278    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8279        final File[] files = dir.listFiles();
8280        if (ArrayUtils.isEmpty(files)) {
8281            Log.d(TAG, "No files in app dir " + dir);
8282            return;
8283        }
8284
8285        if (DEBUG_PACKAGE_SCANNING) {
8286            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8287                    + " flags=0x" + Integer.toHexString(parseFlags));
8288        }
8289        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8290                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8291                mParallelPackageParserCallback);
8292
8293        // Submit files for parsing in parallel
8294        int fileCount = 0;
8295        for (File file : files) {
8296            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8297                    && !PackageInstallerService.isStageName(file.getName());
8298            if (!isPackage) {
8299                // Ignore entries which are not packages
8300                continue;
8301            }
8302            parallelPackageParser.submit(file, parseFlags);
8303            fileCount++;
8304        }
8305
8306        // Process results one by one
8307        for (; fileCount > 0; fileCount--) {
8308            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8309            Throwable throwable = parseResult.throwable;
8310            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8311
8312            if (throwable == null) {
8313                // Static shared libraries have synthetic package names
8314                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8315                    renameStaticSharedLibraryPackage(parseResult.pkg);
8316                }
8317                try {
8318                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8319                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8320                                currentTime, null);
8321                    }
8322                } catch (PackageManagerException e) {
8323                    errorCode = e.error;
8324                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8325                }
8326            } else if (throwable instanceof PackageParser.PackageParserException) {
8327                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8328                        throwable;
8329                errorCode = e.error;
8330                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8331            } else {
8332                throw new IllegalStateException("Unexpected exception occurred while parsing "
8333                        + parseResult.scanFile, throwable);
8334            }
8335
8336            // Delete invalid userdata apps
8337            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8338                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8339                logCriticalInfo(Log.WARN,
8340                        "Deleting invalid package at " + parseResult.scanFile);
8341                removeCodePathLI(parseResult.scanFile);
8342            }
8343        }
8344        parallelPackageParser.close();
8345    }
8346
8347    private static File getSettingsProblemFile() {
8348        File dataDir = Environment.getDataDirectory();
8349        File systemDir = new File(dataDir, "system");
8350        File fname = new File(systemDir, "uiderrors.txt");
8351        return fname;
8352    }
8353
8354    public static void reportSettingsProblem(int priority, String msg) {
8355        logCriticalInfo(priority, msg);
8356    }
8357
8358    public static void logCriticalInfo(int priority, String msg) {
8359        Slog.println(priority, TAG, msg);
8360        EventLogTags.writePmCriticalInfo(msg);
8361        try {
8362            File fname = getSettingsProblemFile();
8363            FileOutputStream out = new FileOutputStream(fname, true);
8364            PrintWriter pw = new FastPrintWriter(out);
8365            SimpleDateFormat formatter = new SimpleDateFormat();
8366            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8367            pw.println(dateString + ": " + msg);
8368            pw.close();
8369            FileUtils.setPermissions(
8370                    fname.toString(),
8371                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8372                    -1, -1);
8373        } catch (java.io.IOException e) {
8374        }
8375    }
8376
8377    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8378        if (srcFile.isDirectory()) {
8379            final File baseFile = new File(pkg.baseCodePath);
8380            long maxModifiedTime = baseFile.lastModified();
8381            if (pkg.splitCodePaths != null) {
8382                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8383                    final File splitFile = new File(pkg.splitCodePaths[i]);
8384                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8385                }
8386            }
8387            return maxModifiedTime;
8388        }
8389        return srcFile.lastModified();
8390    }
8391
8392    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8393            final int policyFlags) throws PackageManagerException {
8394        // When upgrading from pre-N MR1, verify the package time stamp using the package
8395        // directory and not the APK file.
8396        final long lastModifiedTime = mIsPreNMR1Upgrade
8397                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8398        if (ps != null
8399                && ps.codePath.equals(srcFile)
8400                && ps.timeStamp == lastModifiedTime
8401                && !isCompatSignatureUpdateNeeded(pkg)
8402                && !isRecoverSignatureUpdateNeeded(pkg)) {
8403            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8404            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8405            ArraySet<PublicKey> signingKs;
8406            synchronized (mPackages) {
8407                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8408            }
8409            if (ps.signatures.mSignatures != null
8410                    && ps.signatures.mSignatures.length != 0
8411                    && signingKs != null) {
8412                // Optimization: reuse the existing cached certificates
8413                // if the package appears to be unchanged.
8414                pkg.mSignatures = ps.signatures.mSignatures;
8415                pkg.mSigningKeys = signingKs;
8416                return;
8417            }
8418
8419            Slog.w(TAG, "PackageSetting for " + ps.name
8420                    + " is missing signatures.  Collecting certs again to recover them.");
8421        } else {
8422            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8423        }
8424
8425        try {
8426            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8427            PackageParser.collectCertificates(pkg, policyFlags);
8428        } catch (PackageParserException e) {
8429            throw PackageManagerException.from(e);
8430        } finally {
8431            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8432        }
8433    }
8434
8435    /**
8436     *  Traces a package scan.
8437     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8438     */
8439    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8440            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8442        try {
8443            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8444        } finally {
8445            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8446        }
8447    }
8448
8449    /**
8450     *  Scans a package and returns the newly parsed package.
8451     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8452     */
8453    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8454            long currentTime, UserHandle user) throws PackageManagerException {
8455        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8456        PackageParser pp = new PackageParser();
8457        pp.setSeparateProcesses(mSeparateProcesses);
8458        pp.setOnlyCoreApps(mOnlyCore);
8459        pp.setDisplayMetrics(mMetrics);
8460        pp.setCallback(mPackageParserCallback);
8461
8462        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8463            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8464        }
8465
8466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8467        final PackageParser.Package pkg;
8468        try {
8469            pkg = pp.parsePackage(scanFile, parseFlags);
8470        } catch (PackageParserException e) {
8471            throw PackageManagerException.from(e);
8472        } finally {
8473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8474        }
8475
8476        // Static shared libraries have synthetic package names
8477        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8478            renameStaticSharedLibraryPackage(pkg);
8479        }
8480
8481        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8482    }
8483
8484    /**
8485     *  Scans a package and returns the newly parsed package.
8486     *  @throws PackageManagerException on a parse error.
8487     */
8488    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8489            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8490            throws PackageManagerException {
8491        // If the package has children and this is the first dive in the function
8492        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8493        // packages (parent and children) would be successfully scanned before the
8494        // actual scan since scanning mutates internal state and we want to atomically
8495        // install the package and its children.
8496        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8497            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8498                scanFlags |= SCAN_CHECK_ONLY;
8499            }
8500        } else {
8501            scanFlags &= ~SCAN_CHECK_ONLY;
8502        }
8503
8504        // Scan the parent
8505        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8506                scanFlags, currentTime, user);
8507
8508        // Scan the children
8509        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8510        for (int i = 0; i < childCount; i++) {
8511            PackageParser.Package childPackage = pkg.childPackages.get(i);
8512            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8513                    currentTime, user);
8514        }
8515
8516
8517        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8518            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8519        }
8520
8521        return scannedPkg;
8522    }
8523
8524    /**
8525     *  Scans a package and returns the newly parsed package.
8526     *  @throws PackageManagerException on a parse error.
8527     */
8528    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8529            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8530            throws PackageManagerException {
8531        PackageSetting ps = null;
8532        PackageSetting updatedPkg;
8533        // reader
8534        synchronized (mPackages) {
8535            // Look to see if we already know about this package.
8536            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8537            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8538                // This package has been renamed to its original name.  Let's
8539                // use that.
8540                ps = mSettings.getPackageLPr(oldName);
8541            }
8542            // If there was no original package, see one for the real package name.
8543            if (ps == null) {
8544                ps = mSettings.getPackageLPr(pkg.packageName);
8545            }
8546            // Check to see if this package could be hiding/updating a system
8547            // package.  Must look for it either under the original or real
8548            // package name depending on our state.
8549            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8550            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8551
8552            // If this is a package we don't know about on the system partition, we
8553            // may need to remove disabled child packages on the system partition
8554            // or may need to not add child packages if the parent apk is updated
8555            // on the data partition and no longer defines this child package.
8556            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8557                // If this is a parent package for an updated system app and this system
8558                // app got an OTA update which no longer defines some of the child packages
8559                // we have to prune them from the disabled system packages.
8560                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8561                if (disabledPs != null) {
8562                    final int scannedChildCount = (pkg.childPackages != null)
8563                            ? pkg.childPackages.size() : 0;
8564                    final int disabledChildCount = disabledPs.childPackageNames != null
8565                            ? disabledPs.childPackageNames.size() : 0;
8566                    for (int i = 0; i < disabledChildCount; i++) {
8567                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8568                        boolean disabledPackageAvailable = false;
8569                        for (int j = 0; j < scannedChildCount; j++) {
8570                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8571                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8572                                disabledPackageAvailable = true;
8573                                break;
8574                            }
8575                         }
8576                         if (!disabledPackageAvailable) {
8577                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8578                         }
8579                    }
8580                }
8581            }
8582        }
8583
8584        final boolean isUpdatedPkg = updatedPkg != null;
8585        final boolean isUpdatedSystemPkg = isUpdatedPkg
8586                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8587        boolean isUpdatedPkgBetter = false;
8588        // First check if this is a system package that may involve an update
8589        if (isUpdatedSystemPkg) {
8590            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8591            // it needs to drop FLAG_PRIVILEGED.
8592            if (locationIsPrivileged(scanFile)) {
8593                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8594            } else {
8595                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8596            }
8597            // If new package is not located in "/oem" (e.g. due to an OTA),
8598            // it needs to drop FLAG_OEM.
8599            if (locationIsOem(scanFile)) {
8600                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8601            } else {
8602                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8603            }
8604
8605            if (ps != null && !ps.codePath.equals(scanFile)) {
8606                // The path has changed from what was last scanned...  check the
8607                // version of the new path against what we have stored to determine
8608                // what to do.
8609                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8610                if (pkg.mVersionCode <= ps.versionCode) {
8611                    // The system package has been updated and the code path does not match
8612                    // Ignore entry. Skip it.
8613                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8614                            + " ignored: updated version " + ps.versionCode
8615                            + " better than this " + pkg.mVersionCode);
8616                    if (!updatedPkg.codePath.equals(scanFile)) {
8617                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8618                                + ps.name + " changing from " + updatedPkg.codePathString
8619                                + " to " + scanFile);
8620                        updatedPkg.codePath = scanFile;
8621                        updatedPkg.codePathString = scanFile.toString();
8622                        updatedPkg.resourcePath = scanFile;
8623                        updatedPkg.resourcePathString = scanFile.toString();
8624                    }
8625                    updatedPkg.pkg = pkg;
8626                    updatedPkg.versionCode = pkg.mVersionCode;
8627
8628                    // Update the disabled system child packages to point to the package too.
8629                    final int childCount = updatedPkg.childPackageNames != null
8630                            ? updatedPkg.childPackageNames.size() : 0;
8631                    for (int i = 0; i < childCount; i++) {
8632                        String childPackageName = updatedPkg.childPackageNames.get(i);
8633                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8634                                childPackageName);
8635                        if (updatedChildPkg != null) {
8636                            updatedChildPkg.pkg = pkg;
8637                            updatedChildPkg.versionCode = pkg.mVersionCode;
8638                        }
8639                    }
8640                } else {
8641                    // The current app on the system partition is better than
8642                    // what we have updated to on the data partition; switch
8643                    // back to the system partition version.
8644                    // At this point, its safely assumed that package installation for
8645                    // apps in system partition will go through. If not there won't be a working
8646                    // version of the app
8647                    // writer
8648                    synchronized (mPackages) {
8649                        // Just remove the loaded entries from package lists.
8650                        mPackages.remove(ps.name);
8651                    }
8652
8653                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8654                            + " reverting from " + ps.codePathString
8655                            + ": new version " + pkg.mVersionCode
8656                            + " better than installed " + ps.versionCode);
8657
8658                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8659                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8660                    synchronized (mInstallLock) {
8661                        args.cleanUpResourcesLI();
8662                    }
8663                    synchronized (mPackages) {
8664                        mSettings.enableSystemPackageLPw(ps.name);
8665                    }
8666                    isUpdatedPkgBetter = true;
8667                }
8668            }
8669        }
8670
8671        String resourcePath = null;
8672        String baseResourcePath = null;
8673        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8674            if (ps != null && ps.resourcePathString != null) {
8675                resourcePath = ps.resourcePathString;
8676                baseResourcePath = ps.resourcePathString;
8677            } else {
8678                // Should not happen at all. Just log an error.
8679                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8680            }
8681        } else {
8682            resourcePath = pkg.codePath;
8683            baseResourcePath = pkg.baseCodePath;
8684        }
8685
8686        // Set application objects path explicitly.
8687        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8688        pkg.setApplicationInfoCodePath(pkg.codePath);
8689        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8690        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8691        pkg.setApplicationInfoResourcePath(resourcePath);
8692        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8693        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8694
8695        // throw an exception if we have an update to a system application, but, it's not more
8696        // recent than the package we've already scanned
8697        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8698            // Set CPU Abis to application info.
8699            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8700                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8701                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8702            } else {
8703                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8704                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8705            }
8706
8707            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8708                    + scanFile + " ignored: updated version " + ps.versionCode
8709                    + " better than this " + pkg.mVersionCode);
8710        }
8711
8712        if (isUpdatedPkg) {
8713            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8714            // initially
8715            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8716
8717            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8718            // flag set initially
8719            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8720                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8721            }
8722
8723            // An updated OEM app will not have the PARSE_IS_OEM
8724            // flag set initially
8725            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8726                policyFlags |= PackageParser.PARSE_IS_OEM;
8727            }
8728        }
8729
8730        // Verify certificates against what was last scanned
8731        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8732
8733        /*
8734         * A new system app appeared, but we already had a non-system one of the
8735         * same name installed earlier.
8736         */
8737        boolean shouldHideSystemApp = false;
8738        if (!isUpdatedPkg && ps != null
8739                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8740            /*
8741             * Check to make sure the signatures match first. If they don't,
8742             * wipe the installed application and its data.
8743             */
8744            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8745                    != PackageManager.SIGNATURE_MATCH) {
8746                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8747                        + " signatures don't match existing userdata copy; removing");
8748                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8749                        "scanPackageInternalLI")) {
8750                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8751                }
8752                ps = null;
8753            } else {
8754                /*
8755                 * If the newly-added system app is an older version than the
8756                 * already installed version, hide it. It will be scanned later
8757                 * and re-added like an update.
8758                 */
8759                if (pkg.mVersionCode <= ps.versionCode) {
8760                    shouldHideSystemApp = true;
8761                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8762                            + " but new version " + pkg.mVersionCode + " better than installed "
8763                            + ps.versionCode + "; hiding system");
8764                } else {
8765                    /*
8766                     * The newly found system app is a newer version that the
8767                     * one previously installed. Simply remove the
8768                     * already-installed application and replace it with our own
8769                     * while keeping the application data.
8770                     */
8771                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8772                            + " reverting from " + ps.codePathString + ": new version "
8773                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8774                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8775                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8776                    synchronized (mInstallLock) {
8777                        args.cleanUpResourcesLI();
8778                    }
8779                }
8780            }
8781        }
8782
8783        // The apk is forward locked (not public) if its code and resources
8784        // are kept in different files. (except for app in either system or
8785        // vendor path).
8786        // TODO grab this value from PackageSettings
8787        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8788            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8789                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8790            }
8791        }
8792
8793        final int userId = ((user == null) ? 0 : user.getIdentifier());
8794        if (ps != null && ps.getInstantApp(userId)) {
8795            scanFlags |= SCAN_AS_INSTANT_APP;
8796        }
8797        if (ps != null && ps.getVirtulalPreload(userId)) {
8798            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8799        }
8800
8801        // Note that we invoke the following method only if we are about to unpack an application
8802        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8803                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8804
8805        /*
8806         * If the system app should be overridden by a previously installed
8807         * data, hide the system app now and let the /data/app scan pick it up
8808         * again.
8809         */
8810        if (shouldHideSystemApp) {
8811            synchronized (mPackages) {
8812                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8813            }
8814        }
8815
8816        return scannedPkg;
8817    }
8818
8819    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8820        // Derive the new package synthetic package name
8821        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8822                + pkg.staticSharedLibVersion);
8823    }
8824
8825    private static String fixProcessName(String defProcessName,
8826            String processName) {
8827        if (processName == null) {
8828            return defProcessName;
8829        }
8830        return processName;
8831    }
8832
8833    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8834            throws PackageManagerException {
8835        if (pkgSetting.signatures.mSignatures != null) {
8836            // Already existing package. Make sure signatures match
8837            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8838                    == PackageManager.SIGNATURE_MATCH;
8839            if (!match) {
8840                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8841                        == PackageManager.SIGNATURE_MATCH;
8842            }
8843            if (!match) {
8844                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8845                        == PackageManager.SIGNATURE_MATCH;
8846            }
8847            if (!match) {
8848                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8849                        + pkg.packageName + " signatures do not match the "
8850                        + "previously installed version; ignoring!");
8851            }
8852        }
8853
8854        // Check for shared user signatures
8855        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8856            // Already existing package. Make sure signatures match
8857            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8858                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8859            if (!match) {
8860                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8861                        == PackageManager.SIGNATURE_MATCH;
8862            }
8863            if (!match) {
8864                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8865                        == PackageManager.SIGNATURE_MATCH;
8866            }
8867            if (!match) {
8868                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8869                        "Package " + pkg.packageName
8870                        + " has no signatures that match those in shared user "
8871                        + pkgSetting.sharedUser.name + "; ignoring!");
8872            }
8873        }
8874    }
8875
8876    /**
8877     * Enforces that only the system UID or root's UID can call a method exposed
8878     * via Binder.
8879     *
8880     * @param message used as message if SecurityException is thrown
8881     * @throws SecurityException if the caller is not system or root
8882     */
8883    private static final void enforceSystemOrRoot(String message) {
8884        final int uid = Binder.getCallingUid();
8885        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8886            throw new SecurityException(message);
8887        }
8888    }
8889
8890    @Override
8891    public void performFstrimIfNeeded() {
8892        enforceSystemOrRoot("Only the system can request fstrim");
8893
8894        // Before everything else, see whether we need to fstrim.
8895        try {
8896            IStorageManager sm = PackageHelper.getStorageManager();
8897            if (sm != null) {
8898                boolean doTrim = false;
8899                final long interval = android.provider.Settings.Global.getLong(
8900                        mContext.getContentResolver(),
8901                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8902                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8903                if (interval > 0) {
8904                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8905                    if (timeSinceLast > interval) {
8906                        doTrim = true;
8907                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8908                                + "; running immediately");
8909                    }
8910                }
8911                if (doTrim) {
8912                    final boolean dexOptDialogShown;
8913                    synchronized (mPackages) {
8914                        dexOptDialogShown = mDexOptDialogShown;
8915                    }
8916                    if (!isFirstBoot() && dexOptDialogShown) {
8917                        try {
8918                            ActivityManager.getService().showBootMessage(
8919                                    mContext.getResources().getString(
8920                                            R.string.android_upgrading_fstrim), true);
8921                        } catch (RemoteException e) {
8922                        }
8923                    }
8924                    sm.runMaintenance();
8925                }
8926            } else {
8927                Slog.e(TAG, "storageManager service unavailable!");
8928            }
8929        } catch (RemoteException e) {
8930            // Can't happen; StorageManagerService is local
8931        }
8932    }
8933
8934    @Override
8935    public void updatePackagesIfNeeded() {
8936        enforceSystemOrRoot("Only the system can request package update");
8937
8938        // We need to re-extract after an OTA.
8939        boolean causeUpgrade = isUpgrade();
8940
8941        // First boot or factory reset.
8942        // Note: we also handle devices that are upgrading to N right now as if it is their
8943        //       first boot, as they do not have profile data.
8944        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8945
8946        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8947        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8948
8949        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8950            return;
8951        }
8952
8953        List<PackageParser.Package> pkgs;
8954        synchronized (mPackages) {
8955            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8956        }
8957
8958        final long startTime = System.nanoTime();
8959        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8960                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8961                    false /* bootComplete */);
8962
8963        final int elapsedTimeSeconds =
8964                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8965
8966        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8967        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8968        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8969        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8970        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8971    }
8972
8973    /*
8974     * Return the prebuilt profile path given a package base code path.
8975     */
8976    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8977        return pkg.baseCodePath + ".prof";
8978    }
8979
8980    /**
8981     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8982     * containing statistics about the invocation. The array consists of three elements,
8983     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8984     * and {@code numberOfPackagesFailed}.
8985     */
8986    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8987            final String compilerFilter, boolean bootComplete) {
8988
8989        int numberOfPackagesVisited = 0;
8990        int numberOfPackagesOptimized = 0;
8991        int numberOfPackagesSkipped = 0;
8992        int numberOfPackagesFailed = 0;
8993        final int numberOfPackagesToDexopt = pkgs.size();
8994
8995        for (PackageParser.Package pkg : pkgs) {
8996            numberOfPackagesVisited++;
8997
8998            boolean useProfileForDexopt = false;
8999
9000            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9001                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9002                // that are already compiled.
9003                File profileFile = new File(getPrebuildProfilePath(pkg));
9004                // Copy profile if it exists.
9005                if (profileFile.exists()) {
9006                    try {
9007                        // We could also do this lazily before calling dexopt in
9008                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9009                        // is that we don't have a good way to say "do this only once".
9010                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9011                                pkg.applicationInfo.uid, pkg.packageName)) {
9012                            Log.e(TAG, "Installer failed to copy system profile!");
9013                        } else {
9014                            // Disabled as this causes speed-profile compilation during first boot
9015                            // even if things are already compiled.
9016                            // useProfileForDexopt = true;
9017                        }
9018                    } catch (Exception e) {
9019                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9020                                e);
9021                    }
9022                } else {
9023                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9024                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9025                    // minimize the number off apps being speed-profile compiled during first boot.
9026                    // The other paths will not change the filter.
9027                    if (disabledPs != null && disabledPs.pkg.isStub) {
9028                        // The package is the stub one, remove the stub suffix to get the normal
9029                        // package and APK names.
9030                        String systemProfilePath =
9031                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9032                        profileFile = new File(systemProfilePath);
9033                        // If we have a profile for a compressed APK, copy it to the reference
9034                        // location.
9035                        // Note that copying the profile here will cause it to override the
9036                        // reference profile every OTA even though the existing reference profile
9037                        // may have more data. We can't copy during decompression since the
9038                        // directories are not set up at that point.
9039                        if (profileFile.exists()) {
9040                            try {
9041                                // We could also do this lazily before calling dexopt in
9042                                // PackageDexOptimizer to prevent this happening on first boot. The
9043                                // issue is that we don't have a good way to say "do this only
9044                                // once".
9045                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9046                                        pkg.applicationInfo.uid, pkg.packageName)) {
9047                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9048                                } else {
9049                                    useProfileForDexopt = true;
9050                                }
9051                            } catch (Exception e) {
9052                                Log.e(TAG, "Failed to copy profile " +
9053                                        profileFile.getAbsolutePath() + " ", e);
9054                            }
9055                        }
9056                    }
9057                }
9058            }
9059
9060            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9061                if (DEBUG_DEXOPT) {
9062                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9063                }
9064                numberOfPackagesSkipped++;
9065                continue;
9066            }
9067
9068            if (DEBUG_DEXOPT) {
9069                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9070                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9071            }
9072
9073            if (showDialog) {
9074                try {
9075                    ActivityManager.getService().showBootMessage(
9076                            mContext.getResources().getString(R.string.android_upgrading_apk,
9077                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9078                } catch (RemoteException e) {
9079                }
9080                synchronized (mPackages) {
9081                    mDexOptDialogShown = true;
9082                }
9083            }
9084
9085            String pkgCompilerFilter = compilerFilter;
9086            if (useProfileForDexopt) {
9087                // Use background dexopt mode to try and use the profile. Note that this does not
9088                // guarantee usage of the profile.
9089                pkgCompilerFilter =
9090                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9091                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9092            }
9093
9094            // checkProfiles is false to avoid merging profiles during boot which
9095            // might interfere with background compilation (b/28612421).
9096            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9097            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9098            // trade-off worth doing to save boot time work.
9099            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9100            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9101                    pkg.packageName,
9102                    pkgCompilerFilter,
9103                    dexoptFlags));
9104
9105            switch (primaryDexOptStaus) {
9106                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9107                    numberOfPackagesOptimized++;
9108                    break;
9109                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9110                    numberOfPackagesSkipped++;
9111                    break;
9112                case PackageDexOptimizer.DEX_OPT_FAILED:
9113                    numberOfPackagesFailed++;
9114                    break;
9115                default:
9116                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9117                    break;
9118            }
9119        }
9120
9121        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9122                numberOfPackagesFailed };
9123    }
9124
9125    @Override
9126    public void notifyPackageUse(String packageName, int reason) {
9127        synchronized (mPackages) {
9128            final int callingUid = Binder.getCallingUid();
9129            final int callingUserId = UserHandle.getUserId(callingUid);
9130            if (getInstantAppPackageName(callingUid) != null) {
9131                if (!isCallerSameApp(packageName, callingUid)) {
9132                    return;
9133                }
9134            } else {
9135                if (isInstantApp(packageName, callingUserId)) {
9136                    return;
9137                }
9138            }
9139            notifyPackageUseLocked(packageName, reason);
9140        }
9141    }
9142
9143    private void notifyPackageUseLocked(String packageName, int reason) {
9144        final PackageParser.Package p = mPackages.get(packageName);
9145        if (p == null) {
9146            return;
9147        }
9148        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9149    }
9150
9151    @Override
9152    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9153            List<String> classPaths, String loaderIsa) {
9154        int userId = UserHandle.getCallingUserId();
9155        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9156        if (ai == null) {
9157            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9158                + loadingPackageName + ", user=" + userId);
9159            return;
9160        }
9161        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9162    }
9163
9164    @Override
9165    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9166            IDexModuleRegisterCallback callback) {
9167        int userId = UserHandle.getCallingUserId();
9168        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9169        DexManager.RegisterDexModuleResult result;
9170        if (ai == null) {
9171            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9172                     " calling user. package=" + packageName + ", user=" + userId);
9173            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9174        } else {
9175            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9176        }
9177
9178        if (callback != null) {
9179            mHandler.post(() -> {
9180                try {
9181                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9182                } catch (RemoteException e) {
9183                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9184                }
9185            });
9186        }
9187    }
9188
9189    /**
9190     * Ask the package manager to perform a dex-opt with the given compiler filter.
9191     *
9192     * Note: exposed only for the shell command to allow moving packages explicitly to a
9193     *       definite state.
9194     */
9195    @Override
9196    public boolean performDexOptMode(String packageName,
9197            boolean checkProfiles, String targetCompilerFilter, boolean force,
9198            boolean bootComplete, String splitName) {
9199        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9200                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9201                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9202        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9203                splitName, flags));
9204    }
9205
9206    /**
9207     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9208     * secondary dex files belonging to the given package.
9209     *
9210     * Note: exposed only for the shell command to allow moving packages explicitly to a
9211     *       definite state.
9212     */
9213    @Override
9214    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9215            boolean force) {
9216        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9217                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9218                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9219                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9220        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9221    }
9222
9223    /*package*/ boolean performDexOpt(DexoptOptions options) {
9224        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9225            return false;
9226        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9227            return false;
9228        }
9229
9230        if (options.isDexoptOnlySecondaryDex()) {
9231            return mDexManager.dexoptSecondaryDex(options);
9232        } else {
9233            int dexoptStatus = performDexOptWithStatus(options);
9234            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9235        }
9236    }
9237
9238    /**
9239     * Perform dexopt on the given package and return one of following result:
9240     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9241     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9242     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9243     */
9244    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9245        return performDexOptTraced(options);
9246    }
9247
9248    private int performDexOptTraced(DexoptOptions options) {
9249        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9250        try {
9251            return performDexOptInternal(options);
9252        } finally {
9253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9254        }
9255    }
9256
9257    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9258    // if the package can now be considered up to date for the given filter.
9259    private int performDexOptInternal(DexoptOptions options) {
9260        PackageParser.Package p;
9261        synchronized (mPackages) {
9262            p = mPackages.get(options.getPackageName());
9263            if (p == null) {
9264                // Package could not be found. Report failure.
9265                return PackageDexOptimizer.DEX_OPT_FAILED;
9266            }
9267            mPackageUsage.maybeWriteAsync(mPackages);
9268            mCompilerStats.maybeWriteAsync();
9269        }
9270        long callingId = Binder.clearCallingIdentity();
9271        try {
9272            synchronized (mInstallLock) {
9273                return performDexOptInternalWithDependenciesLI(p, options);
9274            }
9275        } finally {
9276            Binder.restoreCallingIdentity(callingId);
9277        }
9278    }
9279
9280    public ArraySet<String> getOptimizablePackages() {
9281        ArraySet<String> pkgs = new ArraySet<String>();
9282        synchronized (mPackages) {
9283            for (PackageParser.Package p : mPackages.values()) {
9284                if (PackageDexOptimizer.canOptimizePackage(p)) {
9285                    pkgs.add(p.packageName);
9286                }
9287            }
9288        }
9289        return pkgs;
9290    }
9291
9292    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9293            DexoptOptions options) {
9294        // Select the dex optimizer based on the force parameter.
9295        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9296        //       allocate an object here.
9297        PackageDexOptimizer pdo = options.isForce()
9298                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9299                : mPackageDexOptimizer;
9300
9301        // Dexopt all dependencies first. Note: we ignore the return value and march on
9302        // on errors.
9303        // Note that we are going to call performDexOpt on those libraries as many times as
9304        // they are referenced in packages. When we do a batch of performDexOpt (for example
9305        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9306        // and the first package that uses the library will dexopt it. The
9307        // others will see that the compiled code for the library is up to date.
9308        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9309        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9310        if (!deps.isEmpty()) {
9311            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9312                    options.getCompilerFilter(), options.getSplitName(),
9313                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9314            for (PackageParser.Package depPackage : deps) {
9315                // TODO: Analyze and investigate if we (should) profile libraries.
9316                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9317                        getOrCreateCompilerPackageStats(depPackage),
9318                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9319            }
9320        }
9321        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9322                getOrCreateCompilerPackageStats(p),
9323                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9324    }
9325
9326    /**
9327     * Reconcile the information we have about the secondary dex files belonging to
9328     * {@code packagName} and the actual dex files. For all dex files that were
9329     * deleted, update the internal records and delete the generated oat files.
9330     */
9331    @Override
9332    public void reconcileSecondaryDexFiles(String packageName) {
9333        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9334            return;
9335        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9336            return;
9337        }
9338        mDexManager.reconcileSecondaryDexFiles(packageName);
9339    }
9340
9341    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9342    // a reference there.
9343    /*package*/ DexManager getDexManager() {
9344        return mDexManager;
9345    }
9346
9347    /**
9348     * Execute the background dexopt job immediately.
9349     */
9350    @Override
9351    public boolean runBackgroundDexoptJob() {
9352        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9353            return false;
9354        }
9355        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9356    }
9357
9358    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9359        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9360                || p.usesStaticLibraries != null) {
9361            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9362            Set<String> collectedNames = new HashSet<>();
9363            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9364
9365            retValue.remove(p);
9366
9367            return retValue;
9368        } else {
9369            return Collections.emptyList();
9370        }
9371    }
9372
9373    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9374            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9375        if (!collectedNames.contains(p.packageName)) {
9376            collectedNames.add(p.packageName);
9377            collected.add(p);
9378
9379            if (p.usesLibraries != null) {
9380                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9381                        null, collected, collectedNames);
9382            }
9383            if (p.usesOptionalLibraries != null) {
9384                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9385                        null, collected, collectedNames);
9386            }
9387            if (p.usesStaticLibraries != null) {
9388                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9389                        p.usesStaticLibrariesVersions, collected, collectedNames);
9390            }
9391        }
9392    }
9393
9394    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9395            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9396        final int libNameCount = libs.size();
9397        for (int i = 0; i < libNameCount; i++) {
9398            String libName = libs.get(i);
9399            int version = (versions != null && versions.length == libNameCount)
9400                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9401            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9402            if (libPkg != null) {
9403                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9404            }
9405        }
9406    }
9407
9408    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9409        synchronized (mPackages) {
9410            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9411            if (libEntry != null) {
9412                return mPackages.get(libEntry.apk);
9413            }
9414            return null;
9415        }
9416    }
9417
9418    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9419        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9420        if (versionedLib == null) {
9421            return null;
9422        }
9423        return versionedLib.get(version);
9424    }
9425
9426    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9427        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9428                pkg.staticSharedLibName);
9429        if (versionedLib == null) {
9430            return null;
9431        }
9432        int previousLibVersion = -1;
9433        final int versionCount = versionedLib.size();
9434        for (int i = 0; i < versionCount; i++) {
9435            final int libVersion = versionedLib.keyAt(i);
9436            if (libVersion < pkg.staticSharedLibVersion) {
9437                previousLibVersion = Math.max(previousLibVersion, libVersion);
9438            }
9439        }
9440        if (previousLibVersion >= 0) {
9441            return versionedLib.get(previousLibVersion);
9442        }
9443        return null;
9444    }
9445
9446    public void shutdown() {
9447        mPackageUsage.writeNow(mPackages);
9448        mCompilerStats.writeNow();
9449        mDexManager.writePackageDexUsageNow();
9450    }
9451
9452    @Override
9453    public void dumpProfiles(String packageName) {
9454        PackageParser.Package pkg;
9455        synchronized (mPackages) {
9456            pkg = mPackages.get(packageName);
9457            if (pkg == null) {
9458                throw new IllegalArgumentException("Unknown package: " + packageName);
9459            }
9460        }
9461        /* Only the shell, root, or the app user should be able to dump profiles. */
9462        int callingUid = Binder.getCallingUid();
9463        if (callingUid != Process.SHELL_UID &&
9464            callingUid != Process.ROOT_UID &&
9465            callingUid != pkg.applicationInfo.uid) {
9466            throw new SecurityException("dumpProfiles");
9467        }
9468
9469        synchronized (mInstallLock) {
9470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9471            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9472            try {
9473                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9474                String codePaths = TextUtils.join(";", allCodePaths);
9475                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9476            } catch (InstallerException e) {
9477                Slog.w(TAG, "Failed to dump profiles", e);
9478            }
9479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9480        }
9481    }
9482
9483    @Override
9484    public void forceDexOpt(String packageName) {
9485        enforceSystemOrRoot("forceDexOpt");
9486
9487        PackageParser.Package pkg;
9488        synchronized (mPackages) {
9489            pkg = mPackages.get(packageName);
9490            if (pkg == null) {
9491                throw new IllegalArgumentException("Unknown package: " + packageName);
9492            }
9493        }
9494
9495        synchronized (mInstallLock) {
9496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9497
9498            // Whoever is calling forceDexOpt wants a compiled package.
9499            // Don't use profiles since that may cause compilation to be skipped.
9500            final int res = performDexOptInternalWithDependenciesLI(
9501                    pkg,
9502                    new DexoptOptions(packageName,
9503                            getDefaultCompilerFilter(),
9504                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9505
9506            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9507            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9508                throw new IllegalStateException("Failed to dexopt: " + res);
9509            }
9510        }
9511    }
9512
9513    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9514        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9515            Slog.w(TAG, "Unable to update from " + oldPkg.name
9516                    + " to " + newPkg.packageName
9517                    + ": old package not in system partition");
9518            return false;
9519        } else if (mPackages.get(oldPkg.name) != null) {
9520            Slog.w(TAG, "Unable to update from " + oldPkg.name
9521                    + " to " + newPkg.packageName
9522                    + ": old package still exists");
9523            return false;
9524        }
9525        return true;
9526    }
9527
9528    void removeCodePathLI(File codePath) {
9529        if (codePath.isDirectory()) {
9530            try {
9531                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9532            } catch (InstallerException e) {
9533                Slog.w(TAG, "Failed to remove code path", e);
9534            }
9535        } else {
9536            codePath.delete();
9537        }
9538    }
9539
9540    private int[] resolveUserIds(int userId) {
9541        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9542    }
9543
9544    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9545        if (pkg == null) {
9546            Slog.wtf(TAG, "Package was null!", new Throwable());
9547            return;
9548        }
9549        clearAppDataLeafLIF(pkg, userId, flags);
9550        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9551        for (int i = 0; i < childCount; i++) {
9552            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9553        }
9554    }
9555
9556    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9557        final PackageSetting ps;
9558        synchronized (mPackages) {
9559            ps = mSettings.mPackages.get(pkg.packageName);
9560        }
9561        for (int realUserId : resolveUserIds(userId)) {
9562            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9563            try {
9564                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9565                        ceDataInode);
9566            } catch (InstallerException e) {
9567                Slog.w(TAG, String.valueOf(e));
9568            }
9569        }
9570    }
9571
9572    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9573        if (pkg == null) {
9574            Slog.wtf(TAG, "Package was null!", new Throwable());
9575            return;
9576        }
9577        destroyAppDataLeafLIF(pkg, userId, flags);
9578        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9579        for (int i = 0; i < childCount; i++) {
9580            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9581        }
9582    }
9583
9584    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9585        final PackageSetting ps;
9586        synchronized (mPackages) {
9587            ps = mSettings.mPackages.get(pkg.packageName);
9588        }
9589        for (int realUserId : resolveUserIds(userId)) {
9590            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9591            try {
9592                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9593                        ceDataInode);
9594            } catch (InstallerException e) {
9595                Slog.w(TAG, String.valueOf(e));
9596            }
9597            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9598        }
9599    }
9600
9601    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9602        if (pkg == null) {
9603            Slog.wtf(TAG, "Package was null!", new Throwable());
9604            return;
9605        }
9606        destroyAppProfilesLeafLIF(pkg);
9607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9608        for (int i = 0; i < childCount; i++) {
9609            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9610        }
9611    }
9612
9613    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9614        try {
9615            mInstaller.destroyAppProfiles(pkg.packageName);
9616        } catch (InstallerException e) {
9617            Slog.w(TAG, String.valueOf(e));
9618        }
9619    }
9620
9621    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9622        if (pkg == null) {
9623            Slog.wtf(TAG, "Package was null!", new Throwable());
9624            return;
9625        }
9626        clearAppProfilesLeafLIF(pkg);
9627        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9628        for (int i = 0; i < childCount; i++) {
9629            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9630        }
9631    }
9632
9633    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9634        try {
9635            mInstaller.clearAppProfiles(pkg.packageName);
9636        } catch (InstallerException e) {
9637            Slog.w(TAG, String.valueOf(e));
9638        }
9639    }
9640
9641    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9642            long lastUpdateTime) {
9643        // Set parent install/update time
9644        PackageSetting ps = (PackageSetting) pkg.mExtras;
9645        if (ps != null) {
9646            ps.firstInstallTime = firstInstallTime;
9647            ps.lastUpdateTime = lastUpdateTime;
9648        }
9649        // Set children install/update time
9650        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9651        for (int i = 0; i < childCount; i++) {
9652            PackageParser.Package childPkg = pkg.childPackages.get(i);
9653            ps = (PackageSetting) childPkg.mExtras;
9654            if (ps != null) {
9655                ps.firstInstallTime = firstInstallTime;
9656                ps.lastUpdateTime = lastUpdateTime;
9657            }
9658        }
9659    }
9660
9661    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9662            SharedLibraryEntry file,
9663            PackageParser.Package changingLib) {
9664        if (file.path != null) {
9665            usesLibraryFiles.add(file.path);
9666            return;
9667        }
9668        PackageParser.Package p = mPackages.get(file.apk);
9669        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9670            // If we are doing this while in the middle of updating a library apk,
9671            // then we need to make sure to use that new apk for determining the
9672            // dependencies here.  (We haven't yet finished committing the new apk
9673            // to the package manager state.)
9674            if (p == null || p.packageName.equals(changingLib.packageName)) {
9675                p = changingLib;
9676            }
9677        }
9678        if (p != null) {
9679            usesLibraryFiles.addAll(p.getAllCodePaths());
9680            if (p.usesLibraryFiles != null) {
9681                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9682            }
9683        }
9684    }
9685
9686    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9687            PackageParser.Package changingLib) throws PackageManagerException {
9688        if (pkg == null) {
9689            return;
9690        }
9691        // The collection used here must maintain the order of addition (so
9692        // that libraries are searched in the correct order) and must have no
9693        // duplicates.
9694        Set<String> usesLibraryFiles = null;
9695        if (pkg.usesLibraries != null) {
9696            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9697                    null, null, pkg.packageName, changingLib, true,
9698                    pkg.applicationInfo.targetSdkVersion, null);
9699        }
9700        if (pkg.usesStaticLibraries != null) {
9701            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9702                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9703                    pkg.packageName, changingLib, true,
9704                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9705        }
9706        if (pkg.usesOptionalLibraries != null) {
9707            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9708                    null, null, pkg.packageName, changingLib, false,
9709                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9710        }
9711        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9712            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9713        } else {
9714            pkg.usesLibraryFiles = null;
9715        }
9716    }
9717
9718    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9719            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9720            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9721            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9722            throws PackageManagerException {
9723        final int libCount = requestedLibraries.size();
9724        for (int i = 0; i < libCount; i++) {
9725            final String libName = requestedLibraries.get(i);
9726            final int libVersion = requiredVersions != null ? requiredVersions[i]
9727                    : SharedLibraryInfo.VERSION_UNDEFINED;
9728            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9729            if (libEntry == null) {
9730                if (required) {
9731                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9732                            "Package " + packageName + " requires unavailable shared library "
9733                                    + libName + "; failing!");
9734                } else if (DEBUG_SHARED_LIBRARIES) {
9735                    Slog.i(TAG, "Package " + packageName
9736                            + " desires unavailable shared library "
9737                            + libName + "; ignoring!");
9738                }
9739            } else {
9740                if (requiredVersions != null && requiredCertDigests != null) {
9741                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9742                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9743                            "Package " + packageName + " requires unavailable static shared"
9744                                    + " library " + libName + " version "
9745                                    + libEntry.info.getVersion() + "; failing!");
9746                    }
9747
9748                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9749                    if (libPkg == null) {
9750                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9751                                "Package " + packageName + " requires unavailable static shared"
9752                                        + " library; failing!");
9753                    }
9754
9755                    final String[] expectedCertDigests = requiredCertDigests[i];
9756                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9757                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9758                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9759                            : PackageUtils.computeSignaturesSha256Digests(
9760                                    new Signature[]{libPkg.mSignatures[0]});
9761
9762                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9763                    // target O we don't parse the "additional-certificate" tags similarly
9764                    // how we only consider all certs only for apps targeting O (see above).
9765                    // Therefore, the size check is safe to make.
9766                    if (expectedCertDigests.length != libCertDigests.length) {
9767                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9768                                "Package " + packageName + " requires differently signed" +
9769                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9770                    }
9771
9772                    // Use a predictable order as signature order may vary
9773                    Arrays.sort(libCertDigests);
9774                    Arrays.sort(expectedCertDigests);
9775
9776                    final int certCount = libCertDigests.length;
9777                    for (int j = 0; j < certCount; j++) {
9778                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9779                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9780                                    "Package " + packageName + " requires differently signed" +
9781                                            " static shared library; failing!");
9782                        }
9783                    }
9784                }
9785
9786                if (outUsedLibraries == null) {
9787                    // Use LinkedHashSet to preserve the order of files added to
9788                    // usesLibraryFiles while eliminating duplicates.
9789                    outUsedLibraries = new LinkedHashSet<>();
9790                }
9791                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9792            }
9793        }
9794        return outUsedLibraries;
9795    }
9796
9797    private static boolean hasString(List<String> list, List<String> which) {
9798        if (list == null) {
9799            return false;
9800        }
9801        for (int i=list.size()-1; i>=0; i--) {
9802            for (int j=which.size()-1; j>=0; j--) {
9803                if (which.get(j).equals(list.get(i))) {
9804                    return true;
9805                }
9806            }
9807        }
9808        return false;
9809    }
9810
9811    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9812            PackageParser.Package changingPkg) {
9813        ArrayList<PackageParser.Package> res = null;
9814        for (PackageParser.Package pkg : mPackages.values()) {
9815            if (changingPkg != null
9816                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9817                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9818                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9819                            changingPkg.staticSharedLibName)) {
9820                return null;
9821            }
9822            if (res == null) {
9823                res = new ArrayList<>();
9824            }
9825            res.add(pkg);
9826            try {
9827                updateSharedLibrariesLPr(pkg, changingPkg);
9828            } catch (PackageManagerException e) {
9829                // If a system app update or an app and a required lib missing we
9830                // delete the package and for updated system apps keep the data as
9831                // it is better for the user to reinstall than to be in an limbo
9832                // state. Also libs disappearing under an app should never happen
9833                // - just in case.
9834                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9835                    final int flags = pkg.isUpdatedSystemApp()
9836                            ? PackageManager.DELETE_KEEP_DATA : 0;
9837                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9838                            flags , null, true, null);
9839                }
9840                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9841            }
9842        }
9843        return res;
9844    }
9845
9846    /**
9847     * Derive the value of the {@code cpuAbiOverride} based on the provided
9848     * value and an optional stored value from the package settings.
9849     */
9850    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9851        String cpuAbiOverride = null;
9852
9853        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9854            cpuAbiOverride = null;
9855        } else if (abiOverride != null) {
9856            cpuAbiOverride = abiOverride;
9857        } else if (settings != null) {
9858            cpuAbiOverride = settings.cpuAbiOverrideString;
9859        }
9860
9861        return cpuAbiOverride;
9862    }
9863
9864    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9865            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9866                    throws PackageManagerException {
9867        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9868        // If the package has children and this is the first dive in the function
9869        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9870        // whether all packages (parent and children) would be successfully scanned
9871        // before the actual scan since scanning mutates internal state and we want
9872        // to atomically install the package and its children.
9873        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9874            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9875                scanFlags |= SCAN_CHECK_ONLY;
9876            }
9877        } else {
9878            scanFlags &= ~SCAN_CHECK_ONLY;
9879        }
9880
9881        final PackageParser.Package scannedPkg;
9882        try {
9883            // Scan the parent
9884            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9885            // Scan the children
9886            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9887            for (int i = 0; i < childCount; i++) {
9888                PackageParser.Package childPkg = pkg.childPackages.get(i);
9889                scanPackageLI(childPkg, policyFlags,
9890                        scanFlags, currentTime, user);
9891            }
9892        } finally {
9893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9894        }
9895
9896        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9897            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9898        }
9899
9900        return scannedPkg;
9901    }
9902
9903    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9904            int scanFlags, long currentTime, @Nullable UserHandle user)
9905                    throws PackageManagerException {
9906        boolean success = false;
9907        try {
9908            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9909                    currentTime, user);
9910            success = true;
9911            return res;
9912        } finally {
9913            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9914                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9915                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9916                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9917                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9918            }
9919        }
9920    }
9921
9922    /**
9923     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9924     */
9925    private static boolean apkHasCode(String fileName) {
9926        StrictJarFile jarFile = null;
9927        try {
9928            jarFile = new StrictJarFile(fileName,
9929                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9930            return jarFile.findEntry("classes.dex") != null;
9931        } catch (IOException ignore) {
9932        } finally {
9933            try {
9934                if (jarFile != null) {
9935                    jarFile.close();
9936                }
9937            } catch (IOException ignore) {}
9938        }
9939        return false;
9940    }
9941
9942    /**
9943     * Enforces code policy for the package. This ensures that if an APK has
9944     * declared hasCode="true" in its manifest that the APK actually contains
9945     * code.
9946     *
9947     * @throws PackageManagerException If bytecode could not be found when it should exist
9948     */
9949    private static void assertCodePolicy(PackageParser.Package pkg)
9950            throws PackageManagerException {
9951        final boolean shouldHaveCode =
9952                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9953        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9954            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9955                    "Package " + pkg.baseCodePath + " code is missing");
9956        }
9957
9958        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9959            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9960                final boolean splitShouldHaveCode =
9961                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9962                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9963                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9964                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9965                }
9966            }
9967        }
9968    }
9969
9970    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9971            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9972                    throws PackageManagerException {
9973        if (DEBUG_PACKAGE_SCANNING) {
9974            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9975                Log.d(TAG, "Scanning package " + pkg.packageName);
9976        }
9977
9978        applyPolicy(pkg, policyFlags);
9979
9980        assertPackageIsValid(pkg, policyFlags, scanFlags);
9981
9982        if (Build.IS_DEBUGGABLE &&
9983                pkg.isPrivilegedApp() &&
9984                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
9985            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9986        }
9987
9988        // Initialize package source and resource directories
9989        final File scanFile = new File(pkg.codePath);
9990        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9991        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9992
9993        SharedUserSetting suid = null;
9994        PackageSetting pkgSetting = null;
9995
9996        // Getting the package setting may have a side-effect, so if we
9997        // are only checking if scan would succeed, stash a copy of the
9998        // old setting to restore at the end.
9999        PackageSetting nonMutatedPs = null;
10000
10001        // We keep references to the derived CPU Abis from settings in oder to reuse
10002        // them in the case where we're not upgrading or booting for the first time.
10003        String primaryCpuAbiFromSettings = null;
10004        String secondaryCpuAbiFromSettings = null;
10005
10006        // writer
10007        synchronized (mPackages) {
10008            if (pkg.mSharedUserId != null) {
10009                // SIDE EFFECTS; may potentially allocate a new shared user
10010                suid = mSettings.getSharedUserLPw(
10011                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10012                if (DEBUG_PACKAGE_SCANNING) {
10013                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10014                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10015                                + "): packages=" + suid.packages);
10016                }
10017            }
10018
10019            // Check if we are renaming from an original package name.
10020            PackageSetting origPackage = null;
10021            String realName = null;
10022            if (pkg.mOriginalPackages != null) {
10023                // This package may need to be renamed to a previously
10024                // installed name.  Let's check on that...
10025                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10026                if (pkg.mOriginalPackages.contains(renamed)) {
10027                    // This package had originally been installed as the
10028                    // original name, and we have already taken care of
10029                    // transitioning to the new one.  Just update the new
10030                    // one to continue using the old name.
10031                    realName = pkg.mRealPackage;
10032                    if (!pkg.packageName.equals(renamed)) {
10033                        // Callers into this function may have already taken
10034                        // care of renaming the package; only do it here if
10035                        // it is not already done.
10036                        pkg.setPackageName(renamed);
10037                    }
10038                } else {
10039                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10040                        if ((origPackage = mSettings.getPackageLPr(
10041                                pkg.mOriginalPackages.get(i))) != null) {
10042                            // We do have the package already installed under its
10043                            // original name...  should we use it?
10044                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10045                                // New package is not compatible with original.
10046                                origPackage = null;
10047                                continue;
10048                            } else if (origPackage.sharedUser != null) {
10049                                // Make sure uid is compatible between packages.
10050                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10051                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10052                                            + " to " + pkg.packageName + ": old uid "
10053                                            + origPackage.sharedUser.name
10054                                            + " differs from " + pkg.mSharedUserId);
10055                                    origPackage = null;
10056                                    continue;
10057                                }
10058                                // TODO: Add case when shared user id is added [b/28144775]
10059                            } else {
10060                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10061                                        + pkg.packageName + " to old name " + origPackage.name);
10062                            }
10063                            break;
10064                        }
10065                    }
10066                }
10067            }
10068
10069            if (mTransferedPackages.contains(pkg.packageName)) {
10070                Slog.w(TAG, "Package " + pkg.packageName
10071                        + " was transferred to another, but its .apk remains");
10072            }
10073
10074            // See comments in nonMutatedPs declaration
10075            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10076                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10077                if (foundPs != null) {
10078                    nonMutatedPs = new PackageSetting(foundPs);
10079                }
10080            }
10081
10082            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10083                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10084                if (foundPs != null) {
10085                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10086                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10087                }
10088            }
10089
10090            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10091            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10092                PackageManagerService.reportSettingsProblem(Log.WARN,
10093                        "Package " + pkg.packageName + " shared user changed from "
10094                                + (pkgSetting.sharedUser != null
10095                                        ? pkgSetting.sharedUser.name : "<nothing>")
10096                                + " to "
10097                                + (suid != null ? suid.name : "<nothing>")
10098                                + "; replacing with new");
10099                pkgSetting = null;
10100            }
10101            final PackageSetting oldPkgSetting =
10102                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10103            final PackageSetting disabledPkgSetting =
10104                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10105
10106            String[] usesStaticLibraries = null;
10107            if (pkg.usesStaticLibraries != null) {
10108                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10109                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10110            }
10111
10112            if (pkgSetting == null) {
10113                final String parentPackageName = (pkg.parentPackage != null)
10114                        ? pkg.parentPackage.packageName : null;
10115                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10116                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10117                // REMOVE SharedUserSetting from method; update in a separate call
10118                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10119                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10120                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10121                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10122                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10123                        true /*allowInstall*/, instantApp, virtualPreload,
10124                        parentPackageName, pkg.getChildPackageNames(),
10125                        UserManagerService.getInstance(), usesStaticLibraries,
10126                        pkg.usesStaticLibrariesVersions);
10127                // SIDE EFFECTS; updates system state; move elsewhere
10128                if (origPackage != null) {
10129                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10130                }
10131                mSettings.addUserToSettingLPw(pkgSetting);
10132            } else {
10133                // REMOVE SharedUserSetting from method; update in a separate call.
10134                //
10135                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10136                // secondaryCpuAbi are not known at this point so we always update them
10137                // to null here, only to reset them at a later point.
10138                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10139                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10140                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10141                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10142                        UserManagerService.getInstance(), usesStaticLibraries,
10143                        pkg.usesStaticLibrariesVersions);
10144            }
10145            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10146            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10147
10148            // SIDE EFFECTS; modifies system state; move elsewhere
10149            if (pkgSetting.origPackage != null) {
10150                // If we are first transitioning from an original package,
10151                // fix up the new package's name now.  We need to do this after
10152                // looking up the package under its new name, so getPackageLP
10153                // can take care of fiddling things correctly.
10154                pkg.setPackageName(origPackage.name);
10155
10156                // File a report about this.
10157                String msg = "New package " + pkgSetting.realName
10158                        + " renamed to replace old package " + pkgSetting.name;
10159                reportSettingsProblem(Log.WARN, msg);
10160
10161                // Make a note of it.
10162                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10163                    mTransferedPackages.add(origPackage.name);
10164                }
10165
10166                // No longer need to retain this.
10167                pkgSetting.origPackage = null;
10168            }
10169
10170            // SIDE EFFECTS; modifies system state; move elsewhere
10171            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10172                // Make a note of it.
10173                mTransferedPackages.add(pkg.packageName);
10174            }
10175
10176            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10177                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10178            }
10179
10180            if ((scanFlags & SCAN_BOOTING) == 0
10181                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10182                // Check all shared libraries and map to their actual file path.
10183                // We only do this here for apps not on a system dir, because those
10184                // are the only ones that can fail an install due to this.  We
10185                // will take care of the system apps by updating all of their
10186                // library paths after the scan is done. Also during the initial
10187                // scan don't update any libs as we do this wholesale after all
10188                // apps are scanned to avoid dependency based scanning.
10189                updateSharedLibrariesLPr(pkg, null);
10190            }
10191
10192            if (mFoundPolicyFile) {
10193                SELinuxMMAC.assignSeInfoValue(pkg);
10194            }
10195            pkg.applicationInfo.uid = pkgSetting.appId;
10196            pkg.mExtras = pkgSetting;
10197
10198
10199            // Static shared libs have same package with different versions where
10200            // we internally use a synthetic package name to allow multiple versions
10201            // of the same package, therefore we need to compare signatures against
10202            // the package setting for the latest library version.
10203            PackageSetting signatureCheckPs = pkgSetting;
10204            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10205                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10206                if (libraryEntry != null) {
10207                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10208                }
10209            }
10210
10211            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10212                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10213                    // We just determined the app is signed correctly, so bring
10214                    // over the latest parsed certs.
10215                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10216                } else {
10217                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10218                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10219                                "Package " + pkg.packageName + " upgrade keys do not match the "
10220                                + "previously installed version");
10221                    } else {
10222                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10223                        String msg = "System package " + pkg.packageName
10224                                + " signature changed; retaining data.";
10225                        reportSettingsProblem(Log.WARN, msg);
10226                    }
10227                }
10228            } else {
10229                try {
10230                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10231                    verifySignaturesLP(signatureCheckPs, pkg);
10232                    // We just determined the app is signed correctly, so bring
10233                    // over the latest parsed certs.
10234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10235                } catch (PackageManagerException e) {
10236                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10237                        throw e;
10238                    }
10239                    // The signature has changed, but this package is in the system
10240                    // image...  let's recover!
10241                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10242                    // However...  if this package is part of a shared user, but it
10243                    // doesn't match the signature of the shared user, let's fail.
10244                    // What this means is that you can't change the signatures
10245                    // associated with an overall shared user, which doesn't seem all
10246                    // that unreasonable.
10247                    if (signatureCheckPs.sharedUser != null) {
10248                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10249                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10250                            throw new PackageManagerException(
10251                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10252                                    "Signature mismatch for shared user: "
10253                                            + pkgSetting.sharedUser);
10254                        }
10255                    }
10256                    // File a report about this.
10257                    String msg = "System package " + pkg.packageName
10258                            + " signature changed; retaining data.";
10259                    reportSettingsProblem(Log.WARN, msg);
10260                }
10261            }
10262
10263            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10264                // This package wants to adopt ownership of permissions from
10265                // another package.
10266                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10267                    final String origName = pkg.mAdoptPermissions.get(i);
10268                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10269                    if (orig != null) {
10270                        if (verifyPackageUpdateLPr(orig, pkg)) {
10271                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10272                                    + pkg.packageName);
10273                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10274                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10275                        }
10276                    }
10277                }
10278            }
10279        }
10280
10281        pkg.applicationInfo.processName = fixProcessName(
10282                pkg.applicationInfo.packageName,
10283                pkg.applicationInfo.processName);
10284
10285        if (pkg != mPlatformPackage) {
10286            // Get all of our default paths setup
10287            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10288        }
10289
10290        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10291
10292        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10293            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10294                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10295                final boolean extractNativeLibs = !pkg.isLibrary();
10296                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10297                        mAppLib32InstallDir);
10298                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10299
10300                // Some system apps still use directory structure for native libraries
10301                // in which case we might end up not detecting abi solely based on apk
10302                // structure. Try to detect abi based on directory structure.
10303                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10304                        pkg.applicationInfo.primaryCpuAbi == null) {
10305                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10306                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10307                }
10308            } else {
10309                // This is not a first boot or an upgrade, don't bother deriving the
10310                // ABI during the scan. Instead, trust the value that was stored in the
10311                // package setting.
10312                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10313                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10314
10315                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10316
10317                if (DEBUG_ABI_SELECTION) {
10318                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10319                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10320                        pkg.applicationInfo.secondaryCpuAbi);
10321                }
10322            }
10323        } else {
10324            if ((scanFlags & SCAN_MOVE) != 0) {
10325                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10326                // but we already have this packages package info in the PackageSetting. We just
10327                // use that and derive the native library path based on the new codepath.
10328                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10329                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10330            }
10331
10332            // Set native library paths again. For moves, the path will be updated based on the
10333            // ABIs we've determined above. For non-moves, the path will be updated based on the
10334            // ABIs we determined during compilation, but the path will depend on the final
10335            // package path (after the rename away from the stage path).
10336            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10337        }
10338
10339        // This is a special case for the "system" package, where the ABI is
10340        // dictated by the zygote configuration (and init.rc). We should keep track
10341        // of this ABI so that we can deal with "normal" applications that run under
10342        // the same UID correctly.
10343        if (mPlatformPackage == pkg) {
10344            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10345                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10346        }
10347
10348        // If there's a mismatch between the abi-override in the package setting
10349        // and the abiOverride specified for the install. Warn about this because we
10350        // would've already compiled the app without taking the package setting into
10351        // account.
10352        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10353            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10354                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10355                        " for package " + pkg.packageName);
10356            }
10357        }
10358
10359        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10360        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10361        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10362
10363        // Copy the derived override back to the parsed package, so that we can
10364        // update the package settings accordingly.
10365        pkg.cpuAbiOverride = cpuAbiOverride;
10366
10367        if (DEBUG_ABI_SELECTION) {
10368            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10369                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10370                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10371        }
10372
10373        // Push the derived path down into PackageSettings so we know what to
10374        // clean up at uninstall time.
10375        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10376
10377        if (DEBUG_ABI_SELECTION) {
10378            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10379                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10380                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10381        }
10382
10383        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10384        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10385            // We don't do this here during boot because we can do it all
10386            // at once after scanning all existing packages.
10387            //
10388            // We also do this *before* we perform dexopt on this package, so that
10389            // we can avoid redundant dexopts, and also to make sure we've got the
10390            // code and package path correct.
10391            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10392        }
10393
10394        if (mFactoryTest && pkg.requestedPermissions.contains(
10395                android.Manifest.permission.FACTORY_TEST)) {
10396            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10397        }
10398
10399        if (isSystemApp(pkg)) {
10400            pkgSetting.isOrphaned = true;
10401        }
10402
10403        // Take care of first install / last update times.
10404        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10405        if (currentTime != 0) {
10406            if (pkgSetting.firstInstallTime == 0) {
10407                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10408            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10409                pkgSetting.lastUpdateTime = currentTime;
10410            }
10411        } else if (pkgSetting.firstInstallTime == 0) {
10412            // We need *something*.  Take time time stamp of the file.
10413            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10414        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10415            if (scanFileTime != pkgSetting.timeStamp) {
10416                // A package on the system image has changed; consider this
10417                // to be an update.
10418                pkgSetting.lastUpdateTime = scanFileTime;
10419            }
10420        }
10421        pkgSetting.setTimeStamp(scanFileTime);
10422
10423        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10424            if (nonMutatedPs != null) {
10425                synchronized (mPackages) {
10426                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10427                }
10428            }
10429        } else {
10430            final int userId = user == null ? 0 : user.getIdentifier();
10431            // Modify state for the given package setting
10432            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10433                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10434            if (pkgSetting.getInstantApp(userId)) {
10435                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10436            }
10437        }
10438        return pkg;
10439    }
10440
10441    /**
10442     * Applies policy to the parsed package based upon the given policy flags.
10443     * Ensures the package is in a good state.
10444     * <p>
10445     * Implementation detail: This method must NOT have any side effect. It would
10446     * ideally be static, but, it requires locks to read system state.
10447     */
10448    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10449        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10450            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10451            if (pkg.applicationInfo.isDirectBootAware()) {
10452                // we're direct boot aware; set for all components
10453                for (PackageParser.Service s : pkg.services) {
10454                    s.info.encryptionAware = s.info.directBootAware = true;
10455                }
10456                for (PackageParser.Provider p : pkg.providers) {
10457                    p.info.encryptionAware = p.info.directBootAware = true;
10458                }
10459                for (PackageParser.Activity a : pkg.activities) {
10460                    a.info.encryptionAware = a.info.directBootAware = true;
10461                }
10462                for (PackageParser.Activity r : pkg.receivers) {
10463                    r.info.encryptionAware = r.info.directBootAware = true;
10464                }
10465            }
10466            if (compressedFileExists(pkg.codePath)) {
10467                pkg.isStub = true;
10468            }
10469        } else {
10470            // Only allow system apps to be flagged as core apps.
10471            pkg.coreApp = false;
10472            // clear flags not applicable to regular apps
10473            pkg.applicationInfo.privateFlags &=
10474                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10475            pkg.applicationInfo.privateFlags &=
10476                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10477        }
10478        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10479
10480        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10481            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10482        }
10483
10484        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10485            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10486        }
10487
10488        if (!isSystemApp(pkg)) {
10489            // Only system apps can use these features.
10490            pkg.mOriginalPackages = null;
10491            pkg.mRealPackage = null;
10492            pkg.mAdoptPermissions = null;
10493        }
10494    }
10495
10496    /**
10497     * Asserts the parsed package is valid according to the given policy. If the
10498     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10499     * <p>
10500     * Implementation detail: This method must NOT have any side effects. It would
10501     * ideally be static, but, it requires locks to read system state.
10502     *
10503     * @throws PackageManagerException If the package fails any of the validation checks
10504     */
10505    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10506            throws PackageManagerException {
10507        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10508            assertCodePolicy(pkg);
10509        }
10510
10511        if (pkg.applicationInfo.getCodePath() == null ||
10512                pkg.applicationInfo.getResourcePath() == null) {
10513            // Bail out. The resource and code paths haven't been set.
10514            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10515                    "Code and resource paths haven't been set correctly");
10516        }
10517
10518        // Make sure we're not adding any bogus keyset info
10519        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10520        ksms.assertScannedPackageValid(pkg);
10521
10522        synchronized (mPackages) {
10523            // The special "android" package can only be defined once
10524            if (pkg.packageName.equals("android")) {
10525                if (mAndroidApplication != null) {
10526                    Slog.w(TAG, "*************************************************");
10527                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10528                    Slog.w(TAG, " codePath=" + pkg.codePath);
10529                    Slog.w(TAG, "*************************************************");
10530                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10531                            "Core android package being redefined.  Skipping.");
10532                }
10533            }
10534
10535            // A package name must be unique; don't allow duplicates
10536            if (mPackages.containsKey(pkg.packageName)) {
10537                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10538                        "Application package " + pkg.packageName
10539                        + " already installed.  Skipping duplicate.");
10540            }
10541
10542            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10543                // Static libs have a synthetic package name containing the version
10544                // but we still want the base name to be unique.
10545                if (mPackages.containsKey(pkg.manifestPackageName)) {
10546                    throw new PackageManagerException(
10547                            "Duplicate static shared lib provider package");
10548                }
10549
10550                // Static shared libraries should have at least O target SDK
10551                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10552                    throw new PackageManagerException(
10553                            "Packages declaring static-shared libs must target O SDK or higher");
10554                }
10555
10556                // Package declaring static a shared lib cannot be instant apps
10557                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10558                    throw new PackageManagerException(
10559                            "Packages declaring static-shared libs cannot be instant apps");
10560                }
10561
10562                // Package declaring static a shared lib cannot be renamed since the package
10563                // name is synthetic and apps can't code around package manager internals.
10564                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10565                    throw new PackageManagerException(
10566                            "Packages declaring static-shared libs cannot be renamed");
10567                }
10568
10569                // Package declaring static a shared lib cannot declare child packages
10570                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10571                    throw new PackageManagerException(
10572                            "Packages declaring static-shared libs cannot have child packages");
10573                }
10574
10575                // Package declaring static a shared lib cannot declare dynamic libs
10576                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10577                    throw new PackageManagerException(
10578                            "Packages declaring static-shared libs cannot declare dynamic libs");
10579                }
10580
10581                // Package declaring static a shared lib cannot declare shared users
10582                if (pkg.mSharedUserId != null) {
10583                    throw new PackageManagerException(
10584                            "Packages declaring static-shared libs cannot declare shared users");
10585                }
10586
10587                // Static shared libs cannot declare activities
10588                if (!pkg.activities.isEmpty()) {
10589                    throw new PackageManagerException(
10590                            "Static shared libs cannot declare activities");
10591                }
10592
10593                // Static shared libs cannot declare services
10594                if (!pkg.services.isEmpty()) {
10595                    throw new PackageManagerException(
10596                            "Static shared libs cannot declare services");
10597                }
10598
10599                // Static shared libs cannot declare providers
10600                if (!pkg.providers.isEmpty()) {
10601                    throw new PackageManagerException(
10602                            "Static shared libs cannot declare content providers");
10603                }
10604
10605                // Static shared libs cannot declare receivers
10606                if (!pkg.receivers.isEmpty()) {
10607                    throw new PackageManagerException(
10608                            "Static shared libs cannot declare broadcast receivers");
10609                }
10610
10611                // Static shared libs cannot declare permission groups
10612                if (!pkg.permissionGroups.isEmpty()) {
10613                    throw new PackageManagerException(
10614                            "Static shared libs cannot declare permission groups");
10615                }
10616
10617                // Static shared libs cannot declare permissions
10618                if (!pkg.permissions.isEmpty()) {
10619                    throw new PackageManagerException(
10620                            "Static shared libs cannot declare permissions");
10621                }
10622
10623                // Static shared libs cannot declare protected broadcasts
10624                if (pkg.protectedBroadcasts != null) {
10625                    throw new PackageManagerException(
10626                            "Static shared libs cannot declare protected broadcasts");
10627                }
10628
10629                // Static shared libs cannot be overlay targets
10630                if (pkg.mOverlayTarget != null) {
10631                    throw new PackageManagerException(
10632                            "Static shared libs cannot be overlay targets");
10633                }
10634
10635                // The version codes must be ordered as lib versions
10636                int minVersionCode = Integer.MIN_VALUE;
10637                int maxVersionCode = Integer.MAX_VALUE;
10638
10639                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10640                        pkg.staticSharedLibName);
10641                if (versionedLib != null) {
10642                    final int versionCount = versionedLib.size();
10643                    for (int i = 0; i < versionCount; i++) {
10644                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10645                        final int libVersionCode = libInfo.getDeclaringPackage()
10646                                .getVersionCode();
10647                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10648                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10649                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10650                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10651                        } else {
10652                            minVersionCode = maxVersionCode = libVersionCode;
10653                            break;
10654                        }
10655                    }
10656                }
10657                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10658                    throw new PackageManagerException("Static shared"
10659                            + " lib version codes must be ordered as lib versions");
10660                }
10661            }
10662
10663            // Only privileged apps and updated privileged apps can add child packages.
10664            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10665                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10666                    throw new PackageManagerException("Only privileged apps can add child "
10667                            + "packages. Ignoring package " + pkg.packageName);
10668                }
10669                final int childCount = pkg.childPackages.size();
10670                for (int i = 0; i < childCount; i++) {
10671                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10672                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10673                            childPkg.packageName)) {
10674                        throw new PackageManagerException("Can't override child of "
10675                                + "another disabled app. Ignoring package " + pkg.packageName);
10676                    }
10677                }
10678            }
10679
10680            // If we're only installing presumed-existing packages, require that the
10681            // scanned APK is both already known and at the path previously established
10682            // for it.  Previously unknown packages we pick up normally, but if we have an
10683            // a priori expectation about this package's install presence, enforce it.
10684            // With a singular exception for new system packages. When an OTA contains
10685            // a new system package, we allow the codepath to change from a system location
10686            // to the user-installed location. If we don't allow this change, any newer,
10687            // user-installed version of the application will be ignored.
10688            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10689                if (mExpectingBetter.containsKey(pkg.packageName)) {
10690                    logCriticalInfo(Log.WARN,
10691                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10692                } else {
10693                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10694                    if (known != null) {
10695                        if (DEBUG_PACKAGE_SCANNING) {
10696                            Log.d(TAG, "Examining " + pkg.codePath
10697                                    + " and requiring known paths " + known.codePathString
10698                                    + " & " + known.resourcePathString);
10699                        }
10700                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10701                                || !pkg.applicationInfo.getResourcePath().equals(
10702                                        known.resourcePathString)) {
10703                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10704                                    "Application package " + pkg.packageName
10705                                    + " found at " + pkg.applicationInfo.getCodePath()
10706                                    + " but expected at " + known.codePathString
10707                                    + "; ignoring.");
10708                        }
10709                    } else {
10710                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10711                                "Application package " + pkg.packageName
10712                                + " not found; ignoring.");
10713                    }
10714                }
10715            }
10716
10717            // Verify that this new package doesn't have any content providers
10718            // that conflict with existing packages.  Only do this if the
10719            // package isn't already installed, since we don't want to break
10720            // things that are installed.
10721            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10722                final int N = pkg.providers.size();
10723                int i;
10724                for (i=0; i<N; i++) {
10725                    PackageParser.Provider p = pkg.providers.get(i);
10726                    if (p.info.authority != null) {
10727                        String names[] = p.info.authority.split(";");
10728                        for (int j = 0; j < names.length; j++) {
10729                            if (mProvidersByAuthority.containsKey(names[j])) {
10730                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10731                                final String otherPackageName =
10732                                        ((other != null && other.getComponentName() != null) ?
10733                                                other.getComponentName().getPackageName() : "?");
10734                                throw new PackageManagerException(
10735                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10736                                        "Can't install because provider name " + names[j]
10737                                                + " (in package " + pkg.applicationInfo.packageName
10738                                                + ") is already used by " + otherPackageName);
10739                            }
10740                        }
10741                    }
10742                }
10743            }
10744        }
10745    }
10746
10747    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10748            int type, String declaringPackageName, int declaringVersionCode) {
10749        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10750        if (versionedLib == null) {
10751            versionedLib = new SparseArray<>();
10752            mSharedLibraries.put(name, versionedLib);
10753            if (type == SharedLibraryInfo.TYPE_STATIC) {
10754                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10755            }
10756        } else if (versionedLib.indexOfKey(version) >= 0) {
10757            return false;
10758        }
10759        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10760                version, type, declaringPackageName, declaringVersionCode);
10761        versionedLib.put(version, libEntry);
10762        return true;
10763    }
10764
10765    private boolean removeSharedLibraryLPw(String name, int version) {
10766        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10767        if (versionedLib == null) {
10768            return false;
10769        }
10770        final int libIdx = versionedLib.indexOfKey(version);
10771        if (libIdx < 0) {
10772            return false;
10773        }
10774        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10775        versionedLib.remove(version);
10776        if (versionedLib.size() <= 0) {
10777            mSharedLibraries.remove(name);
10778            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10779                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10780                        .getPackageName());
10781            }
10782        }
10783        return true;
10784    }
10785
10786    /**
10787     * Adds a scanned package to the system. When this method is finished, the package will
10788     * be available for query, resolution, etc...
10789     */
10790    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10791            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10792        final String pkgName = pkg.packageName;
10793        if (mCustomResolverComponentName != null &&
10794                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10795            setUpCustomResolverActivity(pkg);
10796        }
10797
10798        if (pkg.packageName.equals("android")) {
10799            synchronized (mPackages) {
10800                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10801                    // Set up information for our fall-back user intent resolution activity.
10802                    mPlatformPackage = pkg;
10803                    pkg.mVersionCode = mSdkVersion;
10804                    mAndroidApplication = pkg.applicationInfo;
10805                    if (!mResolverReplaced) {
10806                        mResolveActivity.applicationInfo = mAndroidApplication;
10807                        mResolveActivity.name = ResolverActivity.class.getName();
10808                        mResolveActivity.packageName = mAndroidApplication.packageName;
10809                        mResolveActivity.processName = "system:ui";
10810                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10811                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10812                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10813                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10814                        mResolveActivity.exported = true;
10815                        mResolveActivity.enabled = true;
10816                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10817                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10818                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10819                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10820                                | ActivityInfo.CONFIG_ORIENTATION
10821                                | ActivityInfo.CONFIG_KEYBOARD
10822                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10823                        mResolveInfo.activityInfo = mResolveActivity;
10824                        mResolveInfo.priority = 0;
10825                        mResolveInfo.preferredOrder = 0;
10826                        mResolveInfo.match = 0;
10827                        mResolveComponentName = new ComponentName(
10828                                mAndroidApplication.packageName, mResolveActivity.name);
10829                    }
10830                }
10831            }
10832        }
10833
10834        ArrayList<PackageParser.Package> clientLibPkgs = null;
10835        // writer
10836        synchronized (mPackages) {
10837            boolean hasStaticSharedLibs = false;
10838
10839            // Any app can add new static shared libraries
10840            if (pkg.staticSharedLibName != null) {
10841                // Static shared libs don't allow renaming as they have synthetic package
10842                // names to allow install of multiple versions, so use name from manifest.
10843                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10844                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10845                        pkg.manifestPackageName, pkg.mVersionCode)) {
10846                    hasStaticSharedLibs = true;
10847                } else {
10848                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10849                                + pkg.staticSharedLibName + " already exists; skipping");
10850                }
10851                // Static shared libs cannot be updated once installed since they
10852                // use synthetic package name which includes the version code, so
10853                // not need to update other packages's shared lib dependencies.
10854            }
10855
10856            if (!hasStaticSharedLibs
10857                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10858                // Only system apps can add new dynamic shared libraries.
10859                if (pkg.libraryNames != null) {
10860                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10861                        String name = pkg.libraryNames.get(i);
10862                        boolean allowed = false;
10863                        if (pkg.isUpdatedSystemApp()) {
10864                            // New library entries can only be added through the
10865                            // system image.  This is important to get rid of a lot
10866                            // of nasty edge cases: for example if we allowed a non-
10867                            // system update of the app to add a library, then uninstalling
10868                            // the update would make the library go away, and assumptions
10869                            // we made such as through app install filtering would now
10870                            // have allowed apps on the device which aren't compatible
10871                            // with it.  Better to just have the restriction here, be
10872                            // conservative, and create many fewer cases that can negatively
10873                            // impact the user experience.
10874                            final PackageSetting sysPs = mSettings
10875                                    .getDisabledSystemPkgLPr(pkg.packageName);
10876                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10877                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10878                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10879                                        allowed = true;
10880                                        break;
10881                                    }
10882                                }
10883                            }
10884                        } else {
10885                            allowed = true;
10886                        }
10887                        if (allowed) {
10888                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10889                                    SharedLibraryInfo.VERSION_UNDEFINED,
10890                                    SharedLibraryInfo.TYPE_DYNAMIC,
10891                                    pkg.packageName, pkg.mVersionCode)) {
10892                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10893                                        + name + " already exists; skipping");
10894                            }
10895                        } else {
10896                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10897                                    + name + " that is not declared on system image; skipping");
10898                        }
10899                    }
10900
10901                    if ((scanFlags & SCAN_BOOTING) == 0) {
10902                        // If we are not booting, we need to update any applications
10903                        // that are clients of our shared library.  If we are booting,
10904                        // this will all be done once the scan is complete.
10905                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10906                    }
10907                }
10908            }
10909        }
10910
10911        if ((scanFlags & SCAN_BOOTING) != 0) {
10912            // No apps can run during boot scan, so they don't need to be frozen
10913        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10914            // Caller asked to not kill app, so it's probably not frozen
10915        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10916            // Caller asked us to ignore frozen check for some reason; they
10917            // probably didn't know the package name
10918        } else {
10919            // We're doing major surgery on this package, so it better be frozen
10920            // right now to keep it from launching
10921            checkPackageFrozen(pkgName);
10922        }
10923
10924        // Also need to kill any apps that are dependent on the library.
10925        if (clientLibPkgs != null) {
10926            for (int i=0; i<clientLibPkgs.size(); i++) {
10927                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10928                killApplication(clientPkg.applicationInfo.packageName,
10929                        clientPkg.applicationInfo.uid, "update lib");
10930            }
10931        }
10932
10933        // writer
10934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10935
10936        synchronized (mPackages) {
10937            // We don't expect installation to fail beyond this point
10938
10939            // Add the new setting to mSettings
10940            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10941            // Add the new setting to mPackages
10942            mPackages.put(pkg.applicationInfo.packageName, pkg);
10943            // Make sure we don't accidentally delete its data.
10944            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10945            while (iter.hasNext()) {
10946                PackageCleanItem item = iter.next();
10947                if (pkgName.equals(item.packageName)) {
10948                    iter.remove();
10949                }
10950            }
10951
10952            // Add the package's KeySets to the global KeySetManagerService
10953            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10954            ksms.addScannedPackageLPw(pkg);
10955
10956            int N = pkg.providers.size();
10957            StringBuilder r = null;
10958            int i;
10959            for (i=0; i<N; i++) {
10960                PackageParser.Provider p = pkg.providers.get(i);
10961                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10962                        p.info.processName);
10963                mProviders.addProvider(p);
10964                p.syncable = p.info.isSyncable;
10965                if (p.info.authority != null) {
10966                    String names[] = p.info.authority.split(";");
10967                    p.info.authority = null;
10968                    for (int j = 0; j < names.length; j++) {
10969                        if (j == 1 && p.syncable) {
10970                            // We only want the first authority for a provider to possibly be
10971                            // syncable, so if we already added this provider using a different
10972                            // authority clear the syncable flag. We copy the provider before
10973                            // changing it because the mProviders object contains a reference
10974                            // to a provider that we don't want to change.
10975                            // Only do this for the second authority since the resulting provider
10976                            // object can be the same for all future authorities for this provider.
10977                            p = new PackageParser.Provider(p);
10978                            p.syncable = false;
10979                        }
10980                        if (!mProvidersByAuthority.containsKey(names[j])) {
10981                            mProvidersByAuthority.put(names[j], p);
10982                            if (p.info.authority == null) {
10983                                p.info.authority = names[j];
10984                            } else {
10985                                p.info.authority = p.info.authority + ";" + names[j];
10986                            }
10987                            if (DEBUG_PACKAGE_SCANNING) {
10988                                if (chatty)
10989                                    Log.d(TAG, "Registered content provider: " + names[j]
10990                                            + ", className = " + p.info.name + ", isSyncable = "
10991                                            + p.info.isSyncable);
10992                            }
10993                        } else {
10994                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10995                            Slog.w(TAG, "Skipping provider name " + names[j] +
10996                                    " (in package " + pkg.applicationInfo.packageName +
10997                                    "): name already used by "
10998                                    + ((other != null && other.getComponentName() != null)
10999                                            ? other.getComponentName().getPackageName() : "?"));
11000                        }
11001                    }
11002                }
11003                if (chatty) {
11004                    if (r == null) {
11005                        r = new StringBuilder(256);
11006                    } else {
11007                        r.append(' ');
11008                    }
11009                    r.append(p.info.name);
11010                }
11011            }
11012            if (r != null) {
11013                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11014            }
11015
11016            N = pkg.services.size();
11017            r = null;
11018            for (i=0; i<N; i++) {
11019                PackageParser.Service s = pkg.services.get(i);
11020                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11021                        s.info.processName);
11022                mServices.addService(s);
11023                if (chatty) {
11024                    if (r == null) {
11025                        r = new StringBuilder(256);
11026                    } else {
11027                        r.append(' ');
11028                    }
11029                    r.append(s.info.name);
11030                }
11031            }
11032            if (r != null) {
11033                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11034            }
11035
11036            N = pkg.receivers.size();
11037            r = null;
11038            for (i=0; i<N; i++) {
11039                PackageParser.Activity a = pkg.receivers.get(i);
11040                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11041                        a.info.processName);
11042                mReceivers.addActivity(a, "receiver");
11043                if (chatty) {
11044                    if (r == null) {
11045                        r = new StringBuilder(256);
11046                    } else {
11047                        r.append(' ');
11048                    }
11049                    r.append(a.info.name);
11050                }
11051            }
11052            if (r != null) {
11053                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11054            }
11055
11056            N = pkg.activities.size();
11057            r = null;
11058            for (i=0; i<N; i++) {
11059                PackageParser.Activity a = pkg.activities.get(i);
11060                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11061                        a.info.processName);
11062                mActivities.addActivity(a, "activity");
11063                if (chatty) {
11064                    if (r == null) {
11065                        r = new StringBuilder(256);
11066                    } else {
11067                        r.append(' ');
11068                    }
11069                    r.append(a.info.name);
11070                }
11071            }
11072            if (r != null) {
11073                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11074            }
11075
11076            // Don't allow ephemeral applications to define new permissions groups.
11077            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11078                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11079                        + " ignored: instant apps cannot define new permission groups.");
11080            } else {
11081                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11082            }
11083
11084            // Don't allow ephemeral applications to define new permissions.
11085            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11086                Slog.w(TAG, "Permissions from package " + pkg.packageName
11087                        + " ignored: instant apps cannot define new permissions.");
11088            } else {
11089                mPermissionManager.addAllPermissions(pkg, chatty);
11090            }
11091
11092            N = pkg.instrumentation.size();
11093            r = null;
11094            for (i=0; i<N; i++) {
11095                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11096                a.info.packageName = pkg.applicationInfo.packageName;
11097                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11098                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11099                a.info.splitNames = pkg.splitNames;
11100                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11101                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11102                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11103                a.info.dataDir = pkg.applicationInfo.dataDir;
11104                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11105                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11106                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11107                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11108                mInstrumentation.put(a.getComponentName(), a);
11109                if (chatty) {
11110                    if (r == null) {
11111                        r = new StringBuilder(256);
11112                    } else {
11113                        r.append(' ');
11114                    }
11115                    r.append(a.info.name);
11116                }
11117            }
11118            if (r != null) {
11119                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11120            }
11121
11122            if (pkg.protectedBroadcasts != null) {
11123                N = pkg.protectedBroadcasts.size();
11124                synchronized (mProtectedBroadcasts) {
11125                    for (i = 0; i < N; i++) {
11126                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11127                    }
11128                }
11129            }
11130        }
11131
11132        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11133    }
11134
11135    /**
11136     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11137     * is derived purely on the basis of the contents of {@code scanFile} and
11138     * {@code cpuAbiOverride}.
11139     *
11140     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11141     */
11142    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11143                                 String cpuAbiOverride, boolean extractLibs,
11144                                 File appLib32InstallDir)
11145            throws PackageManagerException {
11146        // Give ourselves some initial paths; we'll come back for another
11147        // pass once we've determined ABI below.
11148        setNativeLibraryPaths(pkg, appLib32InstallDir);
11149
11150        // We would never need to extract libs for forward-locked and external packages,
11151        // since the container service will do it for us. We shouldn't attempt to
11152        // extract libs from system app when it was not updated.
11153        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11154                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11155            extractLibs = false;
11156        }
11157
11158        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11159        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11160
11161        NativeLibraryHelper.Handle handle = null;
11162        try {
11163            handle = NativeLibraryHelper.Handle.create(pkg);
11164            // TODO(multiArch): This can be null for apps that didn't go through the
11165            // usual installation process. We can calculate it again, like we
11166            // do during install time.
11167            //
11168            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11169            // unnecessary.
11170            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11171
11172            // Null out the abis so that they can be recalculated.
11173            pkg.applicationInfo.primaryCpuAbi = null;
11174            pkg.applicationInfo.secondaryCpuAbi = null;
11175            if (isMultiArch(pkg.applicationInfo)) {
11176                // Warn if we've set an abiOverride for multi-lib packages..
11177                // By definition, we need to copy both 32 and 64 bit libraries for
11178                // such packages.
11179                if (pkg.cpuAbiOverride != null
11180                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11181                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11182                }
11183
11184                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11185                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11186                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11187                    if (extractLibs) {
11188                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11189                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11190                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11191                                useIsaSpecificSubdirs);
11192                    } else {
11193                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11194                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11195                    }
11196                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11197                }
11198
11199                // Shared library native code should be in the APK zip aligned
11200                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11201                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11202                            "Shared library native lib extraction not supported");
11203                }
11204
11205                maybeThrowExceptionForMultiArchCopy(
11206                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11207
11208                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11209                    if (extractLibs) {
11210                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11211                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11212                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11213                                useIsaSpecificSubdirs);
11214                    } else {
11215                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11216                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11217                    }
11218                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11219                }
11220
11221                maybeThrowExceptionForMultiArchCopy(
11222                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11223
11224                if (abi64 >= 0) {
11225                    // Shared library native libs should be in the APK zip aligned
11226                    if (extractLibs && pkg.isLibrary()) {
11227                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11228                                "Shared library native lib extraction not supported");
11229                    }
11230                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11231                }
11232
11233                if (abi32 >= 0) {
11234                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11235                    if (abi64 >= 0) {
11236                        if (pkg.use32bitAbi) {
11237                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11238                            pkg.applicationInfo.primaryCpuAbi = abi;
11239                        } else {
11240                            pkg.applicationInfo.secondaryCpuAbi = abi;
11241                        }
11242                    } else {
11243                        pkg.applicationInfo.primaryCpuAbi = abi;
11244                    }
11245                }
11246            } else {
11247                String[] abiList = (cpuAbiOverride != null) ?
11248                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11249
11250                // Enable gross and lame hacks for apps that are built with old
11251                // SDK tools. We must scan their APKs for renderscript bitcode and
11252                // not launch them if it's present. Don't bother checking on devices
11253                // that don't have 64 bit support.
11254                boolean needsRenderScriptOverride = false;
11255                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11256                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11257                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11258                    needsRenderScriptOverride = true;
11259                }
11260
11261                final int copyRet;
11262                if (extractLibs) {
11263                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11264                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11265                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11266                } else {
11267                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11268                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11269                }
11270                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11271
11272                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11273                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11274                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11275                }
11276
11277                if (copyRet >= 0) {
11278                    // Shared libraries that have native libs must be multi-architecture
11279                    if (pkg.isLibrary()) {
11280                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11281                                "Shared library with native libs must be multiarch");
11282                    }
11283                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11284                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11285                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11286                } else if (needsRenderScriptOverride) {
11287                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11288                }
11289            }
11290        } catch (IOException ioe) {
11291            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11292        } finally {
11293            IoUtils.closeQuietly(handle);
11294        }
11295
11296        // Now that we've calculated the ABIs and determined if it's an internal app,
11297        // we will go ahead and populate the nativeLibraryPath.
11298        setNativeLibraryPaths(pkg, appLib32InstallDir);
11299    }
11300
11301    /**
11302     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11303     * i.e, so that all packages can be run inside a single process if required.
11304     *
11305     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11306     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11307     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11308     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11309     * updating a package that belongs to a shared user.
11310     *
11311     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11312     * adds unnecessary complexity.
11313     */
11314    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11315            PackageParser.Package scannedPackage) {
11316        String requiredInstructionSet = null;
11317        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11318            requiredInstructionSet = VMRuntime.getInstructionSet(
11319                     scannedPackage.applicationInfo.primaryCpuAbi);
11320        }
11321
11322        PackageSetting requirer = null;
11323        for (PackageSetting ps : packagesForUser) {
11324            // If packagesForUser contains scannedPackage, we skip it. This will happen
11325            // when scannedPackage is an update of an existing package. Without this check,
11326            // we will never be able to change the ABI of any package belonging to a shared
11327            // user, even if it's compatible with other packages.
11328            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11329                if (ps.primaryCpuAbiString == null) {
11330                    continue;
11331                }
11332
11333                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11334                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11335                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11336                    // this but there's not much we can do.
11337                    String errorMessage = "Instruction set mismatch, "
11338                            + ((requirer == null) ? "[caller]" : requirer)
11339                            + " requires " + requiredInstructionSet + " whereas " + ps
11340                            + " requires " + instructionSet;
11341                    Slog.w(TAG, errorMessage);
11342                }
11343
11344                if (requiredInstructionSet == null) {
11345                    requiredInstructionSet = instructionSet;
11346                    requirer = ps;
11347                }
11348            }
11349        }
11350
11351        if (requiredInstructionSet != null) {
11352            String adjustedAbi;
11353            if (requirer != null) {
11354                // requirer != null implies that either scannedPackage was null or that scannedPackage
11355                // did not require an ABI, in which case we have to adjust scannedPackage to match
11356                // the ABI of the set (which is the same as requirer's ABI)
11357                adjustedAbi = requirer.primaryCpuAbiString;
11358                if (scannedPackage != null) {
11359                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11360                }
11361            } else {
11362                // requirer == null implies that we're updating all ABIs in the set to
11363                // match scannedPackage.
11364                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11365            }
11366
11367            for (PackageSetting ps : packagesForUser) {
11368                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11369                    if (ps.primaryCpuAbiString != null) {
11370                        continue;
11371                    }
11372
11373                    ps.primaryCpuAbiString = adjustedAbi;
11374                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11375                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11376                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11377                        if (DEBUG_ABI_SELECTION) {
11378                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11379                                    + " (requirer="
11380                                    + (requirer != null ? requirer.pkg : "null")
11381                                    + ", scannedPackage="
11382                                    + (scannedPackage != null ? scannedPackage : "null")
11383                                    + ")");
11384                        }
11385                        try {
11386                            mInstaller.rmdex(ps.codePathString,
11387                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11388                        } catch (InstallerException ignored) {
11389                        }
11390                    }
11391                }
11392            }
11393        }
11394    }
11395
11396    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11397        synchronized (mPackages) {
11398            mResolverReplaced = true;
11399            // Set up information for custom user intent resolution activity.
11400            mResolveActivity.applicationInfo = pkg.applicationInfo;
11401            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11402            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11403            mResolveActivity.processName = pkg.applicationInfo.packageName;
11404            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11405            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11406                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11407            mResolveActivity.theme = 0;
11408            mResolveActivity.exported = true;
11409            mResolveActivity.enabled = true;
11410            mResolveInfo.activityInfo = mResolveActivity;
11411            mResolveInfo.priority = 0;
11412            mResolveInfo.preferredOrder = 0;
11413            mResolveInfo.match = 0;
11414            mResolveComponentName = mCustomResolverComponentName;
11415            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11416                    mResolveComponentName);
11417        }
11418    }
11419
11420    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11421        if (installerActivity == null) {
11422            if (DEBUG_EPHEMERAL) {
11423                Slog.d(TAG, "Clear ephemeral installer activity");
11424            }
11425            mInstantAppInstallerActivity = null;
11426            return;
11427        }
11428
11429        if (DEBUG_EPHEMERAL) {
11430            Slog.d(TAG, "Set ephemeral installer activity: "
11431                    + installerActivity.getComponentName());
11432        }
11433        // Set up information for ephemeral installer activity
11434        mInstantAppInstallerActivity = installerActivity;
11435        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11436                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11437        mInstantAppInstallerActivity.exported = true;
11438        mInstantAppInstallerActivity.enabled = true;
11439        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11440        mInstantAppInstallerInfo.priority = 0;
11441        mInstantAppInstallerInfo.preferredOrder = 1;
11442        mInstantAppInstallerInfo.isDefault = true;
11443        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11444                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11445    }
11446
11447    private static String calculateBundledApkRoot(final String codePathString) {
11448        final File codePath = new File(codePathString);
11449        final File codeRoot;
11450        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11451            codeRoot = Environment.getRootDirectory();
11452        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11453            codeRoot = Environment.getOemDirectory();
11454        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11455            codeRoot = Environment.getVendorDirectory();
11456        } else {
11457            // Unrecognized code path; take its top real segment as the apk root:
11458            // e.g. /something/app/blah.apk => /something
11459            try {
11460                File f = codePath.getCanonicalFile();
11461                File parent = f.getParentFile();    // non-null because codePath is a file
11462                File tmp;
11463                while ((tmp = parent.getParentFile()) != null) {
11464                    f = parent;
11465                    parent = tmp;
11466                }
11467                codeRoot = f;
11468                Slog.w(TAG, "Unrecognized code path "
11469                        + codePath + " - using " + codeRoot);
11470            } catch (IOException e) {
11471                // Can't canonicalize the code path -- shenanigans?
11472                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11473                return Environment.getRootDirectory().getPath();
11474            }
11475        }
11476        return codeRoot.getPath();
11477    }
11478
11479    /**
11480     * Derive and set the location of native libraries for the given package,
11481     * which varies depending on where and how the package was installed.
11482     */
11483    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11484        final ApplicationInfo info = pkg.applicationInfo;
11485        final String codePath = pkg.codePath;
11486        final File codeFile = new File(codePath);
11487        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11488        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11489
11490        info.nativeLibraryRootDir = null;
11491        info.nativeLibraryRootRequiresIsa = false;
11492        info.nativeLibraryDir = null;
11493        info.secondaryNativeLibraryDir = null;
11494
11495        if (isApkFile(codeFile)) {
11496            // Monolithic install
11497            if (bundledApp) {
11498                // If "/system/lib64/apkname" exists, assume that is the per-package
11499                // native library directory to use; otherwise use "/system/lib/apkname".
11500                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11501                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11502                        getPrimaryInstructionSet(info));
11503
11504                // This is a bundled system app so choose the path based on the ABI.
11505                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11506                // is just the default path.
11507                final String apkName = deriveCodePathName(codePath);
11508                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11509                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11510                        apkName).getAbsolutePath();
11511
11512                if (info.secondaryCpuAbi != null) {
11513                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11514                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11515                            secondaryLibDir, apkName).getAbsolutePath();
11516                }
11517            } else if (asecApp) {
11518                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11519                        .getAbsolutePath();
11520            } else {
11521                final String apkName = deriveCodePathName(codePath);
11522                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11523                        .getAbsolutePath();
11524            }
11525
11526            info.nativeLibraryRootRequiresIsa = false;
11527            info.nativeLibraryDir = info.nativeLibraryRootDir;
11528        } else {
11529            // Cluster install
11530            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11531            info.nativeLibraryRootRequiresIsa = true;
11532
11533            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11534                    getPrimaryInstructionSet(info)).getAbsolutePath();
11535
11536            if (info.secondaryCpuAbi != null) {
11537                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11538                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11539            }
11540        }
11541    }
11542
11543    /**
11544     * Calculate the abis and roots for a bundled app. These can uniquely
11545     * be determined from the contents of the system partition, i.e whether
11546     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11547     * of this information, and instead assume that the system was built
11548     * sensibly.
11549     */
11550    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11551                                           PackageSetting pkgSetting) {
11552        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11553
11554        // If "/system/lib64/apkname" exists, assume that is the per-package
11555        // native library directory to use; otherwise use "/system/lib/apkname".
11556        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11557        setBundledAppAbi(pkg, apkRoot, apkName);
11558        // pkgSetting might be null during rescan following uninstall of updates
11559        // to a bundled app, so accommodate that possibility.  The settings in
11560        // that case will be established later from the parsed package.
11561        //
11562        // If the settings aren't null, sync them up with what we've just derived.
11563        // note that apkRoot isn't stored in the package settings.
11564        if (pkgSetting != null) {
11565            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11566            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11567        }
11568    }
11569
11570    /**
11571     * Deduces the ABI of a bundled app and sets the relevant fields on the
11572     * parsed pkg object.
11573     *
11574     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11575     *        under which system libraries are installed.
11576     * @param apkName the name of the installed package.
11577     */
11578    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11579        final File codeFile = new File(pkg.codePath);
11580
11581        final boolean has64BitLibs;
11582        final boolean has32BitLibs;
11583        if (isApkFile(codeFile)) {
11584            // Monolithic install
11585            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11586            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11587        } else {
11588            // Cluster install
11589            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11590            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11591                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11592                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11593                has64BitLibs = (new File(rootDir, isa)).exists();
11594            } else {
11595                has64BitLibs = false;
11596            }
11597            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11598                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11599                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11600                has32BitLibs = (new File(rootDir, isa)).exists();
11601            } else {
11602                has32BitLibs = false;
11603            }
11604        }
11605
11606        if (has64BitLibs && !has32BitLibs) {
11607            // The package has 64 bit libs, but not 32 bit libs. Its primary
11608            // ABI should be 64 bit. We can safely assume here that the bundled
11609            // native libraries correspond to the most preferred ABI in the list.
11610
11611            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11612            pkg.applicationInfo.secondaryCpuAbi = null;
11613        } else if (has32BitLibs && !has64BitLibs) {
11614            // The package has 32 bit libs but not 64 bit libs. Its primary
11615            // ABI should be 32 bit.
11616
11617            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11618            pkg.applicationInfo.secondaryCpuAbi = null;
11619        } else if (has32BitLibs && has64BitLibs) {
11620            // The application has both 64 and 32 bit bundled libraries. We check
11621            // here that the app declares multiArch support, and warn if it doesn't.
11622            //
11623            // We will be lenient here and record both ABIs. The primary will be the
11624            // ABI that's higher on the list, i.e, a device that's configured to prefer
11625            // 64 bit apps will see a 64 bit primary ABI,
11626
11627            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11628                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11629            }
11630
11631            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11632                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11633                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11634            } else {
11635                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11636                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11637            }
11638        } else {
11639            pkg.applicationInfo.primaryCpuAbi = null;
11640            pkg.applicationInfo.secondaryCpuAbi = null;
11641        }
11642    }
11643
11644    private void killApplication(String pkgName, int appId, String reason) {
11645        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11646    }
11647
11648    private void killApplication(String pkgName, int appId, int userId, String reason) {
11649        // Request the ActivityManager to kill the process(only for existing packages)
11650        // so that we do not end up in a confused state while the user is still using the older
11651        // version of the application while the new one gets installed.
11652        final long token = Binder.clearCallingIdentity();
11653        try {
11654            IActivityManager am = ActivityManager.getService();
11655            if (am != null) {
11656                try {
11657                    am.killApplication(pkgName, appId, userId, reason);
11658                } catch (RemoteException e) {
11659                }
11660            }
11661        } finally {
11662            Binder.restoreCallingIdentity(token);
11663        }
11664    }
11665
11666    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11667        // Remove the parent package setting
11668        PackageSetting ps = (PackageSetting) pkg.mExtras;
11669        if (ps != null) {
11670            removePackageLI(ps, chatty);
11671        }
11672        // Remove the child package setting
11673        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11674        for (int i = 0; i < childCount; i++) {
11675            PackageParser.Package childPkg = pkg.childPackages.get(i);
11676            ps = (PackageSetting) childPkg.mExtras;
11677            if (ps != null) {
11678                removePackageLI(ps, chatty);
11679            }
11680        }
11681    }
11682
11683    void removePackageLI(PackageSetting ps, boolean chatty) {
11684        if (DEBUG_INSTALL) {
11685            if (chatty)
11686                Log.d(TAG, "Removing package " + ps.name);
11687        }
11688
11689        // writer
11690        synchronized (mPackages) {
11691            mPackages.remove(ps.name);
11692            final PackageParser.Package pkg = ps.pkg;
11693            if (pkg != null) {
11694                cleanPackageDataStructuresLILPw(pkg, chatty);
11695            }
11696        }
11697    }
11698
11699    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11700        if (DEBUG_INSTALL) {
11701            if (chatty)
11702                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11703        }
11704
11705        // writer
11706        synchronized (mPackages) {
11707            // Remove the parent package
11708            mPackages.remove(pkg.applicationInfo.packageName);
11709            cleanPackageDataStructuresLILPw(pkg, chatty);
11710
11711            // Remove the child packages
11712            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11713            for (int i = 0; i < childCount; i++) {
11714                PackageParser.Package childPkg = pkg.childPackages.get(i);
11715                mPackages.remove(childPkg.applicationInfo.packageName);
11716                cleanPackageDataStructuresLILPw(childPkg, chatty);
11717            }
11718        }
11719    }
11720
11721    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11722        int N = pkg.providers.size();
11723        StringBuilder r = null;
11724        int i;
11725        for (i=0; i<N; i++) {
11726            PackageParser.Provider p = pkg.providers.get(i);
11727            mProviders.removeProvider(p);
11728            if (p.info.authority == null) {
11729
11730                /* There was another ContentProvider with this authority when
11731                 * this app was installed so this authority is null,
11732                 * Ignore it as we don't have to unregister the provider.
11733                 */
11734                continue;
11735            }
11736            String names[] = p.info.authority.split(";");
11737            for (int j = 0; j < names.length; j++) {
11738                if (mProvidersByAuthority.get(names[j]) == p) {
11739                    mProvidersByAuthority.remove(names[j]);
11740                    if (DEBUG_REMOVE) {
11741                        if (chatty)
11742                            Log.d(TAG, "Unregistered content provider: " + names[j]
11743                                    + ", className = " + p.info.name + ", isSyncable = "
11744                                    + p.info.isSyncable);
11745                    }
11746                }
11747            }
11748            if (DEBUG_REMOVE && chatty) {
11749                if (r == null) {
11750                    r = new StringBuilder(256);
11751                } else {
11752                    r.append(' ');
11753                }
11754                r.append(p.info.name);
11755            }
11756        }
11757        if (r != null) {
11758            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11759        }
11760
11761        N = pkg.services.size();
11762        r = null;
11763        for (i=0; i<N; i++) {
11764            PackageParser.Service s = pkg.services.get(i);
11765            mServices.removeService(s);
11766            if (chatty) {
11767                if (r == null) {
11768                    r = new StringBuilder(256);
11769                } else {
11770                    r.append(' ');
11771                }
11772                r.append(s.info.name);
11773            }
11774        }
11775        if (r != null) {
11776            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11777        }
11778
11779        N = pkg.receivers.size();
11780        r = null;
11781        for (i=0; i<N; i++) {
11782            PackageParser.Activity a = pkg.receivers.get(i);
11783            mReceivers.removeActivity(a, "receiver");
11784            if (DEBUG_REMOVE && chatty) {
11785                if (r == null) {
11786                    r = new StringBuilder(256);
11787                } else {
11788                    r.append(' ');
11789                }
11790                r.append(a.info.name);
11791            }
11792        }
11793        if (r != null) {
11794            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11795        }
11796
11797        N = pkg.activities.size();
11798        r = null;
11799        for (i=0; i<N; i++) {
11800            PackageParser.Activity a = pkg.activities.get(i);
11801            mActivities.removeActivity(a, "activity");
11802            if (DEBUG_REMOVE && chatty) {
11803                if (r == null) {
11804                    r = new StringBuilder(256);
11805                } else {
11806                    r.append(' ');
11807                }
11808                r.append(a.info.name);
11809            }
11810        }
11811        if (r != null) {
11812            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11813        }
11814
11815        mPermissionManager.removeAllPermissions(pkg, chatty);
11816
11817        N = pkg.instrumentation.size();
11818        r = null;
11819        for (i=0; i<N; i++) {
11820            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11821            mInstrumentation.remove(a.getComponentName());
11822            if (DEBUG_REMOVE && chatty) {
11823                if (r == null) {
11824                    r = new StringBuilder(256);
11825                } else {
11826                    r.append(' ');
11827                }
11828                r.append(a.info.name);
11829            }
11830        }
11831        if (r != null) {
11832            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11833        }
11834
11835        r = null;
11836        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11837            // Only system apps can hold shared libraries.
11838            if (pkg.libraryNames != null) {
11839                for (i = 0; i < pkg.libraryNames.size(); i++) {
11840                    String name = pkg.libraryNames.get(i);
11841                    if (removeSharedLibraryLPw(name, 0)) {
11842                        if (DEBUG_REMOVE && chatty) {
11843                            if (r == null) {
11844                                r = new StringBuilder(256);
11845                            } else {
11846                                r.append(' ');
11847                            }
11848                            r.append(name);
11849                        }
11850                    }
11851                }
11852            }
11853        }
11854
11855        r = null;
11856
11857        // Any package can hold static shared libraries.
11858        if (pkg.staticSharedLibName != null) {
11859            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11860                if (DEBUG_REMOVE && chatty) {
11861                    if (r == null) {
11862                        r = new StringBuilder(256);
11863                    } else {
11864                        r.append(' ');
11865                    }
11866                    r.append(pkg.staticSharedLibName);
11867                }
11868            }
11869        }
11870
11871        if (r != null) {
11872            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11873        }
11874    }
11875
11876    public static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11877    public static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11878    public static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11879
11880    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11881        // Update the parent permissions
11882        updatePermissionsLPw(pkg.packageName, pkg, flags);
11883        // Update the child permissions
11884        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11885        for (int i = 0; i < childCount; i++) {
11886            PackageParser.Package childPkg = pkg.childPackages.get(i);
11887            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11888        }
11889    }
11890
11891    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11892            int flags) {
11893        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11894        updatePermissionsLocked(changingPkg, pkgInfo, volumeUuid, flags);
11895    }
11896
11897    private void updatePermissionsLocked(String changingPkg,
11898            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11899        // TODO: Most of the methods exposing BasePermission internals [source package name,
11900        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
11901        // have package settings, we should make note of it elsewhere [map between
11902        // source package name and BasePermission] and cycle through that here. Then we
11903        // define a single method on BasePermission that takes a PackageSetting, changing
11904        // package name and a package.
11905        // NOTE: With this approach, we also don't need to tree trees differently than
11906        // normal permissions. Today, we need two separate loops because these BasePermission
11907        // objects are stored separately.
11908        // Make sure there are no dangling permission trees.
11909        flags = mPermissionManager.updatePermissionTrees(changingPkg, pkgInfo, flags);
11910
11911        // Make sure all dynamic permissions have been assigned to a package,
11912        // and make sure there are no dangling permissions.
11913        flags = mPermissionManager.updatePermissions(changingPkg, pkgInfo, flags);
11914
11915        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11916        // Now update the permissions for all packages, in particular
11917        // replace the granted permissions of the system packages.
11918        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11919            for (PackageParser.Package pkg : mPackages.values()) {
11920                if (pkg != pkgInfo) {
11921                    // Only replace for packages on requested volume
11922                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11923                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11924                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11925                    grantPermissionsLPw(pkg, replace, changingPkg);
11926                }
11927            }
11928        }
11929
11930        if (pkgInfo != null) {
11931            // Only replace for packages on requested volume
11932            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11933            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11934                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11935            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11936        }
11937        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11938    }
11939
11940    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11941            String packageOfInterest) {
11942        // IMPORTANT: There are two types of permissions: install and runtime.
11943        // Install time permissions are granted when the app is installed to
11944        // all device users and users added in the future. Runtime permissions
11945        // are granted at runtime explicitly to specific users. Normal and signature
11946        // protected permissions are install time permissions. Dangerous permissions
11947        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11948        // otherwise they are runtime permissions. This function does not manage
11949        // runtime permissions except for the case an app targeting Lollipop MR1
11950        // being upgraded to target a newer SDK, in which case dangerous permissions
11951        // are transformed from install time to runtime ones.
11952
11953        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11954        if (ps == null) {
11955            return;
11956        }
11957
11958        PermissionsState permissionsState = ps.getPermissionsState();
11959        PermissionsState origPermissions = permissionsState;
11960
11961        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11962
11963        boolean runtimePermissionsRevoked = false;
11964        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11965
11966        boolean changedInstallPermission = false;
11967
11968        if (replace) {
11969            ps.installPermissionsFixed = false;
11970            if (!ps.isSharedUser()) {
11971                origPermissions = new PermissionsState(permissionsState);
11972                permissionsState.reset();
11973            } else {
11974                // We need to know only about runtime permission changes since the
11975                // calling code always writes the install permissions state but
11976                // the runtime ones are written only if changed. The only cases of
11977                // changed runtime permissions here are promotion of an install to
11978                // runtime and revocation of a runtime from a shared user.
11979                changedRuntimePermissionUserIds =
11980                        mPermissionManager.revokeUnusedSharedUserPermissions(
11981                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
11982                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11983                    runtimePermissionsRevoked = true;
11984                }
11985            }
11986        }
11987
11988        permissionsState.setGlobalGids(mPermissionManager.getGlobalGidsTEMP());
11989
11990        final int N = pkg.requestedPermissions.size();
11991        for (int i=0; i<N; i++) {
11992            final String name = pkg.requestedPermissions.get(i);
11993            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
11994            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11995                    >= Build.VERSION_CODES.M;
11996
11997            if (DEBUG_INSTALL) {
11998                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11999            }
12000
12001            if (bp == null || bp.getSourcePackageSetting() == null) {
12002                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12003                    if (DEBUG_PERMISSIONS) {
12004                        Slog.i(TAG, "Unknown permission " + name
12005                                + " in package " + pkg.packageName);
12006                    }
12007                }
12008                continue;
12009            }
12010
12011
12012            // Limit ephemeral apps to ephemeral allowed permissions.
12013            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12014                if (DEBUG_PERMISSIONS) {
12015                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12016                            + pkg.packageName);
12017                }
12018                continue;
12019            }
12020
12021            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12022                if (DEBUG_PERMISSIONS) {
12023                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12024                            + pkg.packageName);
12025                }
12026                continue;
12027            }
12028
12029            final String perm = bp.getName();
12030            boolean allowedSig = false;
12031            int grant = GRANT_DENIED;
12032
12033            // Keep track of app op permissions.
12034            if (bp.isAppOp()) {
12035                mSettings.addAppOpPackage(perm, pkg.packageName);
12036            }
12037
12038            if (bp.isNormal()) {
12039                // For all apps normal permissions are install time ones.
12040                grant = GRANT_INSTALL;
12041            } else if (bp.isRuntime()) {
12042                // If a permission review is required for legacy apps we represent
12043                // their permissions as always granted runtime ones since we need
12044                // to keep the review required permission flag per user while an
12045                // install permission's state is shared across all users.
12046                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12047                    // For legacy apps dangerous permissions are install time ones.
12048                    grant = GRANT_INSTALL;
12049                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12050                    // For legacy apps that became modern, install becomes runtime.
12051                    grant = GRANT_UPGRADE;
12052                } else if (mPromoteSystemApps
12053                        && isSystemApp(ps)
12054                        && mExistingSystemPackages.contains(ps.name)) {
12055                    // For legacy system apps, install becomes runtime.
12056                    // We cannot check hasInstallPermission() for system apps since those
12057                    // permissions were granted implicitly and not persisted pre-M.
12058                    grant = GRANT_UPGRADE;
12059                } else {
12060                    // For modern apps keep runtime permissions unchanged.
12061                    grant = GRANT_RUNTIME;
12062                }
12063            } else if (bp.isSignature()) {
12064                // For all apps signature permissions are install time ones.
12065                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12066                if (allowedSig) {
12067                    grant = GRANT_INSTALL;
12068                }
12069            }
12070
12071            if (DEBUG_PERMISSIONS) {
12072                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12073            }
12074
12075            if (grant != GRANT_DENIED) {
12076                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12077                    // If this is an existing, non-system package, then
12078                    // we can't add any new permissions to it.
12079                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12080                        // Except...  if this is a permission that was added
12081                        // to the platform (note: need to only do this when
12082                        // updating the platform).
12083                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12084                            grant = GRANT_DENIED;
12085                        }
12086                    }
12087                }
12088
12089                switch (grant) {
12090                    case GRANT_INSTALL: {
12091                        // Revoke this as runtime permission to handle the case of
12092                        // a runtime permission being downgraded to an install one.
12093                        // Also in permission review mode we keep dangerous permissions
12094                        // for legacy apps
12095                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12096                            if (origPermissions.getRuntimePermissionState(
12097                                    perm, userId) != null) {
12098                                // Revoke the runtime permission and clear the flags.
12099                                origPermissions.revokeRuntimePermission(bp, userId);
12100                                origPermissions.updatePermissionFlags(bp, userId,
12101                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12102                                // If we revoked a permission permission, we have to write.
12103                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12104                                        changedRuntimePermissionUserIds, userId);
12105                            }
12106                        }
12107                        // Grant an install permission.
12108                        if (permissionsState.grantInstallPermission(bp) !=
12109                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12110                            changedInstallPermission = true;
12111                        }
12112                    } break;
12113
12114                    case GRANT_RUNTIME: {
12115                        // Grant previously granted runtime permissions.
12116                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12117                            PermissionState permissionState = origPermissions
12118                                    .getRuntimePermissionState(perm, userId);
12119                            int flags = permissionState != null
12120                                    ? permissionState.getFlags() : 0;
12121                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12122                                // Don't propagate the permission in a permission review mode if
12123                                // the former was revoked, i.e. marked to not propagate on upgrade.
12124                                // Note that in a permission review mode install permissions are
12125                                // represented as constantly granted runtime ones since we need to
12126                                // keep a per user state associated with the permission. Also the
12127                                // revoke on upgrade flag is no longer applicable and is reset.
12128                                final boolean revokeOnUpgrade = (flags & PackageManager
12129                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12130                                if (revokeOnUpgrade) {
12131                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12132                                    // Since we changed the flags, we have to write.
12133                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12134                                            changedRuntimePermissionUserIds, userId);
12135                                }
12136                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12137                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12138                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12139                                        // If we cannot put the permission as it was,
12140                                        // we have to write.
12141                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12142                                                changedRuntimePermissionUserIds, userId);
12143                                    }
12144                                }
12145
12146                                // If the app supports runtime permissions no need for a review.
12147                                if (mPermissionReviewRequired
12148                                        && appSupportsRuntimePermissions
12149                                        && (flags & PackageManager
12150                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12151                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12152                                    // Since we changed the flags, we have to write.
12153                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12154                                            changedRuntimePermissionUserIds, userId);
12155                                }
12156                            } else if (mPermissionReviewRequired
12157                                    && !appSupportsRuntimePermissions) {
12158                                // For legacy apps that need a permission review, every new
12159                                // runtime permission is granted but it is pending a review.
12160                                // We also need to review only platform defined runtime
12161                                // permissions as these are the only ones the platform knows
12162                                // how to disable the API to simulate revocation as legacy
12163                                // apps don't expect to run with revoked permissions.
12164                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12165                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12166                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12167                                        // We changed the flags, hence have to write.
12168                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12169                                                changedRuntimePermissionUserIds, userId);
12170                                    }
12171                                }
12172                                if (permissionsState.grantRuntimePermission(bp, userId)
12173                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12174                                    // We changed the permission, hence have to write.
12175                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12176                                            changedRuntimePermissionUserIds, userId);
12177                                }
12178                            }
12179                            // Propagate the permission flags.
12180                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12181                        }
12182                    } break;
12183
12184                    case GRANT_UPGRADE: {
12185                        // Grant runtime permissions for a previously held install permission.
12186                        PermissionState permissionState = origPermissions
12187                                .getInstallPermissionState(perm);
12188                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12189
12190                        if (origPermissions.revokeInstallPermission(bp)
12191                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12192                            // We will be transferring the permission flags, so clear them.
12193                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12194                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12195                            changedInstallPermission = true;
12196                        }
12197
12198                        // If the permission is not to be promoted to runtime we ignore it and
12199                        // also its other flags as they are not applicable to install permissions.
12200                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12201                            for (int userId : currentUserIds) {
12202                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12203                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12204                                    // Transfer the permission flags.
12205                                    permissionsState.updatePermissionFlags(bp, userId,
12206                                            flags, flags);
12207                                    // If we granted the permission, we have to write.
12208                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12209                                            changedRuntimePermissionUserIds, userId);
12210                                }
12211                            }
12212                        }
12213                    } break;
12214
12215                    default: {
12216                        if (packageOfInterest == null
12217                                || packageOfInterest.equals(pkg.packageName)) {
12218                            if (DEBUG_PERMISSIONS) {
12219                                Slog.i(TAG, "Not granting permission " + perm
12220                                        + " to package " + pkg.packageName
12221                                        + " because it was previously installed without");
12222                            }
12223                        }
12224                    } break;
12225                }
12226            } else {
12227                if (permissionsState.revokeInstallPermission(bp) !=
12228                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12229                    // Also drop the permission flags.
12230                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12231                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12232                    changedInstallPermission = true;
12233                    Slog.i(TAG, "Un-granting permission " + perm
12234                            + " from package " + pkg.packageName
12235                            + " (protectionLevel=" + bp.getProtectionLevel()
12236                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12237                            + ")");
12238                } else if (bp.isAppOp()) {
12239                    // Don't print warning for app op permissions, since it is fine for them
12240                    // not to be granted, there is a UI for the user to decide.
12241                    if (DEBUG_PERMISSIONS
12242                            && (packageOfInterest == null
12243                                    || packageOfInterest.equals(pkg.packageName))) {
12244                        Slog.i(TAG, "Not granting permission " + perm
12245                                + " to package " + pkg.packageName
12246                                + " (protectionLevel=" + bp.getProtectionLevel()
12247                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12248                                + ")");
12249                    }
12250                }
12251            }
12252        }
12253
12254        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12255                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12256            // This is the first that we have heard about this package, so the
12257            // permissions we have now selected are fixed until explicitly
12258            // changed.
12259            ps.installPermissionsFixed = true;
12260        }
12261
12262        // Persist the runtime permissions state for users with changes. If permissions
12263        // were revoked because no app in the shared user declares them we have to
12264        // write synchronously to avoid losing runtime permissions state.
12265        for (int userId : changedRuntimePermissionUserIds) {
12266            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12267        }
12268    }
12269
12270    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12271        boolean allowed = false;
12272        final int NP = PackageParser.NEW_PERMISSIONS.length;
12273        for (int ip=0; ip<NP; ip++) {
12274            final PackageParser.NewPermissionInfo npi
12275                    = PackageParser.NEW_PERMISSIONS[ip];
12276            if (npi.name.equals(perm)
12277                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12278                allowed = true;
12279                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12280                        + pkg.packageName);
12281                break;
12282            }
12283        }
12284        return allowed;
12285    }
12286
12287    /**
12288     * Determines whether a package is whitelisted for a particular privapp permission.
12289     *
12290     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12291     *
12292     * <p>This handles parent/child apps.
12293     */
12294    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12295        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12296                .getPrivAppPermissions(pkg.packageName);
12297        // Let's check if this package is whitelisted...
12298        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12299        // If it's not, we'll also tail-recurse to the parent.
12300        return whitelisted ||
12301                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12302    }
12303
12304    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12305            BasePermission bp, PermissionsState origPermissions) {
12306        boolean oemPermission = bp.isOEM();
12307        boolean privilegedPermission = bp.isPrivileged();
12308        boolean privappPermissionsDisable =
12309                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12310        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12311        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12312        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12313                && !platformPackage && platformPermission) {
12314            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12315                Slog.w(TAG, "Privileged permission " + perm + " for package "
12316                        + pkg.packageName + " - not in privapp-permissions whitelist");
12317                // Only report violations for apps on system image
12318                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12319                    // it's only a reportable violation if the permission isn't explicitly denied
12320                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12321                            .getPrivAppDenyPermissions(pkg.packageName);
12322                    final boolean permissionViolation =
12323                            deniedPermissions == null || !deniedPermissions.contains(perm);
12324                    if (permissionViolation
12325                            && RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12326                        if (mPrivappPermissionsViolations == null) {
12327                            mPrivappPermissionsViolations = new ArraySet<>();
12328                        }
12329                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12330                    } else {
12331                        return false;
12332                    }
12333                }
12334                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12335                    return false;
12336                }
12337            }
12338        }
12339        boolean allowed = (compareSignatures(
12340                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12341                        == PackageManager.SIGNATURE_MATCH)
12342                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12343                        == PackageManager.SIGNATURE_MATCH);
12344        if (!allowed && (privilegedPermission || oemPermission)) {
12345            if (isSystemApp(pkg)) {
12346                // For updated system applications, a privileged/oem permission
12347                // is granted only if it had been defined by the original application.
12348                if (pkg.isUpdatedSystemApp()) {
12349                    final PackageSetting sysPs = mSettings
12350                            .getDisabledSystemPkgLPr(pkg.packageName);
12351                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12352                        // If the original was granted this permission, we take
12353                        // that grant decision as read and propagate it to the
12354                        // update.
12355                        if ((privilegedPermission && sysPs.isPrivileged())
12356                                || (oemPermission && sysPs.isOem()
12357                                        && canGrantOemPermission(sysPs, perm))) {
12358                            allowed = true;
12359                        }
12360                    } else {
12361                        // The system apk may have been updated with an older
12362                        // version of the one on the data partition, but which
12363                        // granted a new system permission that it didn't have
12364                        // before.  In this case we do want to allow the app to
12365                        // now get the new permission if the ancestral apk is
12366                        // privileged to get it.
12367                        if (sysPs != null && sysPs.pkg != null
12368                                && isPackageRequestingPermission(sysPs.pkg, perm)
12369                                && ((privilegedPermission && sysPs.isPrivileged())
12370                                        || (oemPermission && sysPs.isOem()
12371                                                && canGrantOemPermission(sysPs, perm)))) {
12372                            allowed = true;
12373                        }
12374                        // Also if a privileged parent package on the system image or any of
12375                        // its children requested a privileged/oem permission, the updated child
12376                        // packages can also get the permission.
12377                        if (pkg.parentPackage != null) {
12378                            final PackageSetting disabledSysParentPs = mSettings
12379                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12380                            final PackageParser.Package disabledSysParentPkg =
12381                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12382                                    ? null : disabledSysParentPs.pkg;
12383                            if (disabledSysParentPkg != null
12384                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12385                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12386                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12387                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12388                                    allowed = true;
12389                                } else if (disabledSysParentPkg.childPackages != null) {
12390                                    final int count = disabledSysParentPkg.childPackages.size();
12391                                    for (int i = 0; i < count; i++) {
12392                                        final PackageParser.Package disabledSysChildPkg =
12393                                                disabledSysParentPkg.childPackages.get(i);
12394                                        final PackageSetting disabledSysChildPs =
12395                                                mSettings.getDisabledSystemPkgLPr(
12396                                                        disabledSysChildPkg.packageName);
12397                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12398                                                && canGrantOemPermission(
12399                                                        disabledSysChildPs, perm)) {
12400                                            allowed = true;
12401                                            break;
12402                                        }
12403                                    }
12404                                }
12405                            }
12406                        }
12407                    }
12408                } else {
12409                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12410                            || (oemPermission && isOemApp(pkg)
12411                                    && canGrantOemPermission(
12412                                            mSettings.getPackageLPr(pkg.packageName), perm));
12413                }
12414            }
12415        }
12416        if (!allowed) {
12417            if (!allowed
12418                    && bp.isPre23()
12419                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12420                // If this was a previously normal/dangerous permission that got moved
12421                // to a system permission as part of the runtime permission redesign, then
12422                // we still want to blindly grant it to old apps.
12423                allowed = true;
12424            }
12425            if (!allowed && bp.isInstaller()
12426                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12427                // If this permission is to be granted to the system installer and
12428                // this app is an installer, then it gets the permission.
12429                allowed = true;
12430            }
12431            if (!allowed && bp.isVerifier()
12432                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12433                // If this permission is to be granted to the system verifier and
12434                // this app is a verifier, then it gets the permission.
12435                allowed = true;
12436            }
12437            if (!allowed && bp.isPreInstalled()
12438                    && isSystemApp(pkg)) {
12439                // Any pre-installed system app is allowed to get this permission.
12440                allowed = true;
12441            }
12442            if (!allowed && bp.isDevelopment()) {
12443                // For development permissions, a development permission
12444                // is granted only if it was already granted.
12445                allowed = origPermissions.hasInstallPermission(perm);
12446            }
12447            if (!allowed && bp.isSetup()
12448                    && pkg.packageName.equals(mSetupWizardPackage)) {
12449                // If this permission is to be granted to the system setup wizard and
12450                // this app is a setup wizard, then it gets the permission.
12451                allowed = true;
12452            }
12453        }
12454        return allowed;
12455    }
12456
12457    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12458        if (!ps.isOem()) {
12459            return false;
12460        }
12461        // all oem permissions must explicitly be granted or denied
12462        final Boolean granted =
12463                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12464        if (granted == null) {
12465            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12466                    + ps.name + " must be explicitly declared granted or not");
12467        }
12468        return Boolean.TRUE == granted;
12469    }
12470
12471    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12472        final int permCount = pkg.requestedPermissions.size();
12473        for (int j = 0; j < permCount; j++) {
12474            String requestedPermission = pkg.requestedPermissions.get(j);
12475            if (permission.equals(requestedPermission)) {
12476                return true;
12477            }
12478        }
12479        return false;
12480    }
12481
12482    final class ActivityIntentResolver
12483            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12484        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12485                boolean defaultOnly, int userId) {
12486            if (!sUserManager.exists(userId)) return null;
12487            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12488            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12489        }
12490
12491        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12492                int userId) {
12493            if (!sUserManager.exists(userId)) return null;
12494            mFlags = flags;
12495            return super.queryIntent(intent, resolvedType,
12496                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12497                    userId);
12498        }
12499
12500        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12501                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12502            if (!sUserManager.exists(userId)) return null;
12503            if (packageActivities == null) {
12504                return null;
12505            }
12506            mFlags = flags;
12507            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12508            final int N = packageActivities.size();
12509            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12510                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12511
12512            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12513            for (int i = 0; i < N; ++i) {
12514                intentFilters = packageActivities.get(i).intents;
12515                if (intentFilters != null && intentFilters.size() > 0) {
12516                    PackageParser.ActivityIntentInfo[] array =
12517                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12518                    intentFilters.toArray(array);
12519                    listCut.add(array);
12520                }
12521            }
12522            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12523        }
12524
12525        /**
12526         * Finds a privileged activity that matches the specified activity names.
12527         */
12528        private PackageParser.Activity findMatchingActivity(
12529                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12530            for (PackageParser.Activity sysActivity : activityList) {
12531                if (sysActivity.info.name.equals(activityInfo.name)) {
12532                    return sysActivity;
12533                }
12534                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12535                    return sysActivity;
12536                }
12537                if (sysActivity.info.targetActivity != null) {
12538                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12539                        return sysActivity;
12540                    }
12541                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12542                        return sysActivity;
12543                    }
12544                }
12545            }
12546            return null;
12547        }
12548
12549        public class IterGenerator<E> {
12550            public Iterator<E> generate(ActivityIntentInfo info) {
12551                return null;
12552            }
12553        }
12554
12555        public class ActionIterGenerator extends IterGenerator<String> {
12556            @Override
12557            public Iterator<String> generate(ActivityIntentInfo info) {
12558                return info.actionsIterator();
12559            }
12560        }
12561
12562        public class CategoriesIterGenerator extends IterGenerator<String> {
12563            @Override
12564            public Iterator<String> generate(ActivityIntentInfo info) {
12565                return info.categoriesIterator();
12566            }
12567        }
12568
12569        public class SchemesIterGenerator extends IterGenerator<String> {
12570            @Override
12571            public Iterator<String> generate(ActivityIntentInfo info) {
12572                return info.schemesIterator();
12573            }
12574        }
12575
12576        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12577            @Override
12578            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12579                return info.authoritiesIterator();
12580            }
12581        }
12582
12583        /**
12584         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12585         * MODIFIED. Do not pass in a list that should not be changed.
12586         */
12587        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12588                IterGenerator<T> generator, Iterator<T> searchIterator) {
12589            // loop through the set of actions; every one must be found in the intent filter
12590            while (searchIterator.hasNext()) {
12591                // we must have at least one filter in the list to consider a match
12592                if (intentList.size() == 0) {
12593                    break;
12594                }
12595
12596                final T searchAction = searchIterator.next();
12597
12598                // loop through the set of intent filters
12599                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12600                while (intentIter.hasNext()) {
12601                    final ActivityIntentInfo intentInfo = intentIter.next();
12602                    boolean selectionFound = false;
12603
12604                    // loop through the intent filter's selection criteria; at least one
12605                    // of them must match the searched criteria
12606                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12607                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12608                        final T intentSelection = intentSelectionIter.next();
12609                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12610                            selectionFound = true;
12611                            break;
12612                        }
12613                    }
12614
12615                    // the selection criteria wasn't found in this filter's set; this filter
12616                    // is not a potential match
12617                    if (!selectionFound) {
12618                        intentIter.remove();
12619                    }
12620                }
12621            }
12622        }
12623
12624        private boolean isProtectedAction(ActivityIntentInfo filter) {
12625            final Iterator<String> actionsIter = filter.actionsIterator();
12626            while (actionsIter != null && actionsIter.hasNext()) {
12627                final String filterAction = actionsIter.next();
12628                if (PROTECTED_ACTIONS.contains(filterAction)) {
12629                    return true;
12630                }
12631            }
12632            return false;
12633        }
12634
12635        /**
12636         * Adjusts the priority of the given intent filter according to policy.
12637         * <p>
12638         * <ul>
12639         * <li>The priority for non privileged applications is capped to '0'</li>
12640         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12641         * <li>The priority for unbundled updates to privileged applications is capped to the
12642         *      priority defined on the system partition</li>
12643         * </ul>
12644         * <p>
12645         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12646         * allowed to obtain any priority on any action.
12647         */
12648        private void adjustPriority(
12649                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12650            // nothing to do; priority is fine as-is
12651            if (intent.getPriority() <= 0) {
12652                return;
12653            }
12654
12655            final ActivityInfo activityInfo = intent.activity.info;
12656            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12657
12658            final boolean privilegedApp =
12659                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12660            if (!privilegedApp) {
12661                // non-privileged applications can never define a priority >0
12662                if (DEBUG_FILTERS) {
12663                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12664                            + " package: " + applicationInfo.packageName
12665                            + " activity: " + intent.activity.className
12666                            + " origPrio: " + intent.getPriority());
12667                }
12668                intent.setPriority(0);
12669                return;
12670            }
12671
12672            if (systemActivities == null) {
12673                // the system package is not disabled; we're parsing the system partition
12674                if (isProtectedAction(intent)) {
12675                    if (mDeferProtectedFilters) {
12676                        // We can't deal with these just yet. No component should ever obtain a
12677                        // >0 priority for a protected actions, with ONE exception -- the setup
12678                        // wizard. The setup wizard, however, cannot be known until we're able to
12679                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12680                        // until all intent filters have been processed. Chicken, meet egg.
12681                        // Let the filter temporarily have a high priority and rectify the
12682                        // priorities after all system packages have been scanned.
12683                        mProtectedFilters.add(intent);
12684                        if (DEBUG_FILTERS) {
12685                            Slog.i(TAG, "Protected action; save for later;"
12686                                    + " package: " + applicationInfo.packageName
12687                                    + " activity: " + intent.activity.className
12688                                    + " origPrio: " + intent.getPriority());
12689                        }
12690                        return;
12691                    } else {
12692                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12693                            Slog.i(TAG, "No setup wizard;"
12694                                + " All protected intents capped to priority 0");
12695                        }
12696                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12697                            if (DEBUG_FILTERS) {
12698                                Slog.i(TAG, "Found setup wizard;"
12699                                    + " allow priority " + intent.getPriority() + ";"
12700                                    + " package: " + intent.activity.info.packageName
12701                                    + " activity: " + intent.activity.className
12702                                    + " priority: " + intent.getPriority());
12703                            }
12704                            // setup wizard gets whatever it wants
12705                            return;
12706                        }
12707                        if (DEBUG_FILTERS) {
12708                            Slog.i(TAG, "Protected action; cap priority to 0;"
12709                                    + " package: " + intent.activity.info.packageName
12710                                    + " activity: " + intent.activity.className
12711                                    + " origPrio: " + intent.getPriority());
12712                        }
12713                        intent.setPriority(0);
12714                        return;
12715                    }
12716                }
12717                // privileged apps on the system image get whatever priority they request
12718                return;
12719            }
12720
12721            // privileged app unbundled update ... try to find the same activity
12722            final PackageParser.Activity foundActivity =
12723                    findMatchingActivity(systemActivities, activityInfo);
12724            if (foundActivity == null) {
12725                // this is a new activity; it cannot obtain >0 priority
12726                if (DEBUG_FILTERS) {
12727                    Slog.i(TAG, "New activity; cap priority to 0;"
12728                            + " package: " + applicationInfo.packageName
12729                            + " activity: " + intent.activity.className
12730                            + " origPrio: " + intent.getPriority());
12731                }
12732                intent.setPriority(0);
12733                return;
12734            }
12735
12736            // found activity, now check for filter equivalence
12737
12738            // a shallow copy is enough; we modify the list, not its contents
12739            final List<ActivityIntentInfo> intentListCopy =
12740                    new ArrayList<>(foundActivity.intents);
12741            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12742
12743            // find matching action subsets
12744            final Iterator<String> actionsIterator = intent.actionsIterator();
12745            if (actionsIterator != null) {
12746                getIntentListSubset(
12747                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12748                if (intentListCopy.size() == 0) {
12749                    // no more intents to match; we're not equivalent
12750                    if (DEBUG_FILTERS) {
12751                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12752                                + " package: " + applicationInfo.packageName
12753                                + " activity: " + intent.activity.className
12754                                + " origPrio: " + intent.getPriority());
12755                    }
12756                    intent.setPriority(0);
12757                    return;
12758                }
12759            }
12760
12761            // find matching category subsets
12762            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12763            if (categoriesIterator != null) {
12764                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12765                        categoriesIterator);
12766                if (intentListCopy.size() == 0) {
12767                    // no more intents to match; we're not equivalent
12768                    if (DEBUG_FILTERS) {
12769                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12770                                + " package: " + applicationInfo.packageName
12771                                + " activity: " + intent.activity.className
12772                                + " origPrio: " + intent.getPriority());
12773                    }
12774                    intent.setPriority(0);
12775                    return;
12776                }
12777            }
12778
12779            // find matching schemes subsets
12780            final Iterator<String> schemesIterator = intent.schemesIterator();
12781            if (schemesIterator != null) {
12782                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12783                        schemesIterator);
12784                if (intentListCopy.size() == 0) {
12785                    // no more intents to match; we're not equivalent
12786                    if (DEBUG_FILTERS) {
12787                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12788                                + " package: " + applicationInfo.packageName
12789                                + " activity: " + intent.activity.className
12790                                + " origPrio: " + intent.getPriority());
12791                    }
12792                    intent.setPriority(0);
12793                    return;
12794                }
12795            }
12796
12797            // find matching authorities subsets
12798            final Iterator<IntentFilter.AuthorityEntry>
12799                    authoritiesIterator = intent.authoritiesIterator();
12800            if (authoritiesIterator != null) {
12801                getIntentListSubset(intentListCopy,
12802                        new AuthoritiesIterGenerator(),
12803                        authoritiesIterator);
12804                if (intentListCopy.size() == 0) {
12805                    // no more intents to match; we're not equivalent
12806                    if (DEBUG_FILTERS) {
12807                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12808                                + " package: " + applicationInfo.packageName
12809                                + " activity: " + intent.activity.className
12810                                + " origPrio: " + intent.getPriority());
12811                    }
12812                    intent.setPriority(0);
12813                    return;
12814                }
12815            }
12816
12817            // we found matching filter(s); app gets the max priority of all intents
12818            int cappedPriority = 0;
12819            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12820                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12821            }
12822            if (intent.getPriority() > cappedPriority) {
12823                if (DEBUG_FILTERS) {
12824                    Slog.i(TAG, "Found matching filter(s);"
12825                            + " cap priority to " + cappedPriority + ";"
12826                            + " package: " + applicationInfo.packageName
12827                            + " activity: " + intent.activity.className
12828                            + " origPrio: " + intent.getPriority());
12829                }
12830                intent.setPriority(cappedPriority);
12831                return;
12832            }
12833            // all this for nothing; the requested priority was <= what was on the system
12834        }
12835
12836        public final void addActivity(PackageParser.Activity a, String type) {
12837            mActivities.put(a.getComponentName(), a);
12838            if (DEBUG_SHOW_INFO)
12839                Log.v(
12840                TAG, "  " + type + " " +
12841                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12842            if (DEBUG_SHOW_INFO)
12843                Log.v(TAG, "    Class=" + a.info.name);
12844            final int NI = a.intents.size();
12845            for (int j=0; j<NI; j++) {
12846                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12847                if ("activity".equals(type)) {
12848                    final PackageSetting ps =
12849                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12850                    final List<PackageParser.Activity> systemActivities =
12851                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12852                    adjustPriority(systemActivities, intent);
12853                }
12854                if (DEBUG_SHOW_INFO) {
12855                    Log.v(TAG, "    IntentFilter:");
12856                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12857                }
12858                if (!intent.debugCheck()) {
12859                    Log.w(TAG, "==> For Activity " + a.info.name);
12860                }
12861                addFilter(intent);
12862            }
12863        }
12864
12865        public final void removeActivity(PackageParser.Activity a, String type) {
12866            mActivities.remove(a.getComponentName());
12867            if (DEBUG_SHOW_INFO) {
12868                Log.v(TAG, "  " + type + " "
12869                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12870                                : a.info.name) + ":");
12871                Log.v(TAG, "    Class=" + a.info.name);
12872            }
12873            final int NI = a.intents.size();
12874            for (int j=0; j<NI; j++) {
12875                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12876                if (DEBUG_SHOW_INFO) {
12877                    Log.v(TAG, "    IntentFilter:");
12878                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12879                }
12880                removeFilter(intent);
12881            }
12882        }
12883
12884        @Override
12885        protected boolean allowFilterResult(
12886                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12887            ActivityInfo filterAi = filter.activity.info;
12888            for (int i=dest.size()-1; i>=0; i--) {
12889                ActivityInfo destAi = dest.get(i).activityInfo;
12890                if (destAi.name == filterAi.name
12891                        && destAi.packageName == filterAi.packageName) {
12892                    return false;
12893                }
12894            }
12895            return true;
12896        }
12897
12898        @Override
12899        protected ActivityIntentInfo[] newArray(int size) {
12900            return new ActivityIntentInfo[size];
12901        }
12902
12903        @Override
12904        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12905            if (!sUserManager.exists(userId)) return true;
12906            PackageParser.Package p = filter.activity.owner;
12907            if (p != null) {
12908                PackageSetting ps = (PackageSetting)p.mExtras;
12909                if (ps != null) {
12910                    // System apps are never considered stopped for purposes of
12911                    // filtering, because there may be no way for the user to
12912                    // actually re-launch them.
12913                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12914                            && ps.getStopped(userId);
12915                }
12916            }
12917            return false;
12918        }
12919
12920        @Override
12921        protected boolean isPackageForFilter(String packageName,
12922                PackageParser.ActivityIntentInfo info) {
12923            return packageName.equals(info.activity.owner.packageName);
12924        }
12925
12926        @Override
12927        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12928                int match, int userId) {
12929            if (!sUserManager.exists(userId)) return null;
12930            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12931                return null;
12932            }
12933            final PackageParser.Activity activity = info.activity;
12934            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12935            if (ps == null) {
12936                return null;
12937            }
12938            final PackageUserState userState = ps.readUserState(userId);
12939            ActivityInfo ai =
12940                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12941            if (ai == null) {
12942                return null;
12943            }
12944            final boolean matchExplicitlyVisibleOnly =
12945                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12946            final boolean matchVisibleToInstantApp =
12947                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12948            final boolean componentVisible =
12949                    matchVisibleToInstantApp
12950                    && info.isVisibleToInstantApp()
12951                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12952            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12953            // throw out filters that aren't visible to ephemeral apps
12954            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12955                return null;
12956            }
12957            // throw out instant app filters if we're not explicitly requesting them
12958            if (!matchInstantApp && userState.instantApp) {
12959                return null;
12960            }
12961            // throw out instant app filters if updates are available; will trigger
12962            // instant app resolution
12963            if (userState.instantApp && ps.isUpdateAvailable()) {
12964                return null;
12965            }
12966            final ResolveInfo res = new ResolveInfo();
12967            res.activityInfo = ai;
12968            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12969                res.filter = info;
12970            }
12971            if (info != null) {
12972                res.handleAllWebDataURI = info.handleAllWebDataURI();
12973            }
12974            res.priority = info.getPriority();
12975            res.preferredOrder = activity.owner.mPreferredOrder;
12976            //System.out.println("Result: " + res.activityInfo.className +
12977            //                   " = " + res.priority);
12978            res.match = match;
12979            res.isDefault = info.hasDefault;
12980            res.labelRes = info.labelRes;
12981            res.nonLocalizedLabel = info.nonLocalizedLabel;
12982            if (userNeedsBadging(userId)) {
12983                res.noResourceId = true;
12984            } else {
12985                res.icon = info.icon;
12986            }
12987            res.iconResourceId = info.icon;
12988            res.system = res.activityInfo.applicationInfo.isSystemApp();
12989            res.isInstantAppAvailable = userState.instantApp;
12990            return res;
12991        }
12992
12993        @Override
12994        protected void sortResults(List<ResolveInfo> results) {
12995            Collections.sort(results, mResolvePrioritySorter);
12996        }
12997
12998        @Override
12999        protected void dumpFilter(PrintWriter out, String prefix,
13000                PackageParser.ActivityIntentInfo filter) {
13001            out.print(prefix); out.print(
13002                    Integer.toHexString(System.identityHashCode(filter.activity)));
13003                    out.print(' ');
13004                    filter.activity.printComponentShortName(out);
13005                    out.print(" filter ");
13006                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13007        }
13008
13009        @Override
13010        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13011            return filter.activity;
13012        }
13013
13014        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13015            PackageParser.Activity activity = (PackageParser.Activity)label;
13016            out.print(prefix); out.print(
13017                    Integer.toHexString(System.identityHashCode(activity)));
13018                    out.print(' ');
13019                    activity.printComponentShortName(out);
13020            if (count > 1) {
13021                out.print(" ("); out.print(count); out.print(" filters)");
13022            }
13023            out.println();
13024        }
13025
13026        // Keys are String (activity class name), values are Activity.
13027        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13028                = new ArrayMap<ComponentName, PackageParser.Activity>();
13029        private int mFlags;
13030    }
13031
13032    private final class ServiceIntentResolver
13033            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13034        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13035                boolean defaultOnly, int userId) {
13036            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13037            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13038        }
13039
13040        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13041                int userId) {
13042            if (!sUserManager.exists(userId)) return null;
13043            mFlags = flags;
13044            return super.queryIntent(intent, resolvedType,
13045                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13046                    userId);
13047        }
13048
13049        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13050                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13051            if (!sUserManager.exists(userId)) return null;
13052            if (packageServices == null) {
13053                return null;
13054            }
13055            mFlags = flags;
13056            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13057            final int N = packageServices.size();
13058            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13059                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13060
13061            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13062            for (int i = 0; i < N; ++i) {
13063                intentFilters = packageServices.get(i).intents;
13064                if (intentFilters != null && intentFilters.size() > 0) {
13065                    PackageParser.ServiceIntentInfo[] array =
13066                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13067                    intentFilters.toArray(array);
13068                    listCut.add(array);
13069                }
13070            }
13071            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13072        }
13073
13074        public final void addService(PackageParser.Service s) {
13075            mServices.put(s.getComponentName(), s);
13076            if (DEBUG_SHOW_INFO) {
13077                Log.v(TAG, "  "
13078                        + (s.info.nonLocalizedLabel != null
13079                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13080                Log.v(TAG, "    Class=" + s.info.name);
13081            }
13082            final int NI = s.intents.size();
13083            int j;
13084            for (j=0; j<NI; j++) {
13085                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13086                if (DEBUG_SHOW_INFO) {
13087                    Log.v(TAG, "    IntentFilter:");
13088                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13089                }
13090                if (!intent.debugCheck()) {
13091                    Log.w(TAG, "==> For Service " + s.info.name);
13092                }
13093                addFilter(intent);
13094            }
13095        }
13096
13097        public final void removeService(PackageParser.Service s) {
13098            mServices.remove(s.getComponentName());
13099            if (DEBUG_SHOW_INFO) {
13100                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13101                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13102                Log.v(TAG, "    Class=" + s.info.name);
13103            }
13104            final int NI = s.intents.size();
13105            int j;
13106            for (j=0; j<NI; j++) {
13107                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13108                if (DEBUG_SHOW_INFO) {
13109                    Log.v(TAG, "    IntentFilter:");
13110                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13111                }
13112                removeFilter(intent);
13113            }
13114        }
13115
13116        @Override
13117        protected boolean allowFilterResult(
13118                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13119            ServiceInfo filterSi = filter.service.info;
13120            for (int i=dest.size()-1; i>=0; i--) {
13121                ServiceInfo destAi = dest.get(i).serviceInfo;
13122                if (destAi.name == filterSi.name
13123                        && destAi.packageName == filterSi.packageName) {
13124                    return false;
13125                }
13126            }
13127            return true;
13128        }
13129
13130        @Override
13131        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13132            return new PackageParser.ServiceIntentInfo[size];
13133        }
13134
13135        @Override
13136        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13137            if (!sUserManager.exists(userId)) return true;
13138            PackageParser.Package p = filter.service.owner;
13139            if (p != null) {
13140                PackageSetting ps = (PackageSetting)p.mExtras;
13141                if (ps != null) {
13142                    // System apps are never considered stopped for purposes of
13143                    // filtering, because there may be no way for the user to
13144                    // actually re-launch them.
13145                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13146                            && ps.getStopped(userId);
13147                }
13148            }
13149            return false;
13150        }
13151
13152        @Override
13153        protected boolean isPackageForFilter(String packageName,
13154                PackageParser.ServiceIntentInfo info) {
13155            return packageName.equals(info.service.owner.packageName);
13156        }
13157
13158        @Override
13159        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13160                int match, int userId) {
13161            if (!sUserManager.exists(userId)) return null;
13162            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13163            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13164                return null;
13165            }
13166            final PackageParser.Service service = info.service;
13167            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13168            if (ps == null) {
13169                return null;
13170            }
13171            final PackageUserState userState = ps.readUserState(userId);
13172            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13173                    userState, userId);
13174            if (si == null) {
13175                return null;
13176            }
13177            final boolean matchVisibleToInstantApp =
13178                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13179            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13180            // throw out filters that aren't visible to ephemeral apps
13181            if (matchVisibleToInstantApp
13182                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13183                return null;
13184            }
13185            // throw out ephemeral filters if we're not explicitly requesting them
13186            if (!isInstantApp && userState.instantApp) {
13187                return null;
13188            }
13189            // throw out instant app filters if updates are available; will trigger
13190            // instant app resolution
13191            if (userState.instantApp && ps.isUpdateAvailable()) {
13192                return null;
13193            }
13194            final ResolveInfo res = new ResolveInfo();
13195            res.serviceInfo = si;
13196            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13197                res.filter = filter;
13198            }
13199            res.priority = info.getPriority();
13200            res.preferredOrder = service.owner.mPreferredOrder;
13201            res.match = match;
13202            res.isDefault = info.hasDefault;
13203            res.labelRes = info.labelRes;
13204            res.nonLocalizedLabel = info.nonLocalizedLabel;
13205            res.icon = info.icon;
13206            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13207            return res;
13208        }
13209
13210        @Override
13211        protected void sortResults(List<ResolveInfo> results) {
13212            Collections.sort(results, mResolvePrioritySorter);
13213        }
13214
13215        @Override
13216        protected void dumpFilter(PrintWriter out, String prefix,
13217                PackageParser.ServiceIntentInfo filter) {
13218            out.print(prefix); out.print(
13219                    Integer.toHexString(System.identityHashCode(filter.service)));
13220                    out.print(' ');
13221                    filter.service.printComponentShortName(out);
13222                    out.print(" filter ");
13223                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13224        }
13225
13226        @Override
13227        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13228            return filter.service;
13229        }
13230
13231        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13232            PackageParser.Service service = (PackageParser.Service)label;
13233            out.print(prefix); out.print(
13234                    Integer.toHexString(System.identityHashCode(service)));
13235                    out.print(' ');
13236                    service.printComponentShortName(out);
13237            if (count > 1) {
13238                out.print(" ("); out.print(count); out.print(" filters)");
13239            }
13240            out.println();
13241        }
13242
13243//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13244//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13245//            final List<ResolveInfo> retList = Lists.newArrayList();
13246//            while (i.hasNext()) {
13247//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13248//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13249//                    retList.add(resolveInfo);
13250//                }
13251//            }
13252//            return retList;
13253//        }
13254
13255        // Keys are String (activity class name), values are Activity.
13256        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13257                = new ArrayMap<ComponentName, PackageParser.Service>();
13258        private int mFlags;
13259    }
13260
13261    private final class ProviderIntentResolver
13262            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13263        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13264                boolean defaultOnly, int userId) {
13265            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13266            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13267        }
13268
13269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13270                int userId) {
13271            if (!sUserManager.exists(userId))
13272                return null;
13273            mFlags = flags;
13274            return super.queryIntent(intent, resolvedType,
13275                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13276                    userId);
13277        }
13278
13279        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13280                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13281            if (!sUserManager.exists(userId))
13282                return null;
13283            if (packageProviders == null) {
13284                return null;
13285            }
13286            mFlags = flags;
13287            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13288            final int N = packageProviders.size();
13289            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13290                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13291
13292            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13293            for (int i = 0; i < N; ++i) {
13294                intentFilters = packageProviders.get(i).intents;
13295                if (intentFilters != null && intentFilters.size() > 0) {
13296                    PackageParser.ProviderIntentInfo[] array =
13297                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13298                    intentFilters.toArray(array);
13299                    listCut.add(array);
13300                }
13301            }
13302            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13303        }
13304
13305        public final void addProvider(PackageParser.Provider p) {
13306            if (mProviders.containsKey(p.getComponentName())) {
13307                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13308                return;
13309            }
13310
13311            mProviders.put(p.getComponentName(), p);
13312            if (DEBUG_SHOW_INFO) {
13313                Log.v(TAG, "  "
13314                        + (p.info.nonLocalizedLabel != null
13315                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13316                Log.v(TAG, "    Class=" + p.info.name);
13317            }
13318            final int NI = p.intents.size();
13319            int j;
13320            for (j = 0; j < NI; j++) {
13321                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13322                if (DEBUG_SHOW_INFO) {
13323                    Log.v(TAG, "    IntentFilter:");
13324                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13325                }
13326                if (!intent.debugCheck()) {
13327                    Log.w(TAG, "==> For Provider " + p.info.name);
13328                }
13329                addFilter(intent);
13330            }
13331        }
13332
13333        public final void removeProvider(PackageParser.Provider p) {
13334            mProviders.remove(p.getComponentName());
13335            if (DEBUG_SHOW_INFO) {
13336                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13337                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13338                Log.v(TAG, "    Class=" + p.info.name);
13339            }
13340            final int NI = p.intents.size();
13341            int j;
13342            for (j = 0; j < NI; j++) {
13343                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13344                if (DEBUG_SHOW_INFO) {
13345                    Log.v(TAG, "    IntentFilter:");
13346                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13347                }
13348                removeFilter(intent);
13349            }
13350        }
13351
13352        @Override
13353        protected boolean allowFilterResult(
13354                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13355            ProviderInfo filterPi = filter.provider.info;
13356            for (int i = dest.size() - 1; i >= 0; i--) {
13357                ProviderInfo destPi = dest.get(i).providerInfo;
13358                if (destPi.name == filterPi.name
13359                        && destPi.packageName == filterPi.packageName) {
13360                    return false;
13361                }
13362            }
13363            return true;
13364        }
13365
13366        @Override
13367        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13368            return new PackageParser.ProviderIntentInfo[size];
13369        }
13370
13371        @Override
13372        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13373            if (!sUserManager.exists(userId))
13374                return true;
13375            PackageParser.Package p = filter.provider.owner;
13376            if (p != null) {
13377                PackageSetting ps = (PackageSetting) p.mExtras;
13378                if (ps != null) {
13379                    // System apps are never considered stopped for purposes of
13380                    // filtering, because there may be no way for the user to
13381                    // actually re-launch them.
13382                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13383                            && ps.getStopped(userId);
13384                }
13385            }
13386            return false;
13387        }
13388
13389        @Override
13390        protected boolean isPackageForFilter(String packageName,
13391                PackageParser.ProviderIntentInfo info) {
13392            return packageName.equals(info.provider.owner.packageName);
13393        }
13394
13395        @Override
13396        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13397                int match, int userId) {
13398            if (!sUserManager.exists(userId))
13399                return null;
13400            final PackageParser.ProviderIntentInfo info = filter;
13401            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13402                return null;
13403            }
13404            final PackageParser.Provider provider = info.provider;
13405            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13406            if (ps == null) {
13407                return null;
13408            }
13409            final PackageUserState userState = ps.readUserState(userId);
13410            final boolean matchVisibleToInstantApp =
13411                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13412            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13413            // throw out filters that aren't visible to instant applications
13414            if (matchVisibleToInstantApp
13415                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13416                return null;
13417            }
13418            // throw out instant application filters if we're not explicitly requesting them
13419            if (!isInstantApp && userState.instantApp) {
13420                return null;
13421            }
13422            // throw out instant application filters if updates are available; will trigger
13423            // instant application resolution
13424            if (userState.instantApp && ps.isUpdateAvailable()) {
13425                return null;
13426            }
13427            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13428                    userState, userId);
13429            if (pi == null) {
13430                return null;
13431            }
13432            final ResolveInfo res = new ResolveInfo();
13433            res.providerInfo = pi;
13434            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13435                res.filter = filter;
13436            }
13437            res.priority = info.getPriority();
13438            res.preferredOrder = provider.owner.mPreferredOrder;
13439            res.match = match;
13440            res.isDefault = info.hasDefault;
13441            res.labelRes = info.labelRes;
13442            res.nonLocalizedLabel = info.nonLocalizedLabel;
13443            res.icon = info.icon;
13444            res.system = res.providerInfo.applicationInfo.isSystemApp();
13445            return res;
13446        }
13447
13448        @Override
13449        protected void sortResults(List<ResolveInfo> results) {
13450            Collections.sort(results, mResolvePrioritySorter);
13451        }
13452
13453        @Override
13454        protected void dumpFilter(PrintWriter out, String prefix,
13455                PackageParser.ProviderIntentInfo filter) {
13456            out.print(prefix);
13457            out.print(
13458                    Integer.toHexString(System.identityHashCode(filter.provider)));
13459            out.print(' ');
13460            filter.provider.printComponentShortName(out);
13461            out.print(" filter ");
13462            out.println(Integer.toHexString(System.identityHashCode(filter)));
13463        }
13464
13465        @Override
13466        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13467            return filter.provider;
13468        }
13469
13470        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13471            PackageParser.Provider provider = (PackageParser.Provider)label;
13472            out.print(prefix); out.print(
13473                    Integer.toHexString(System.identityHashCode(provider)));
13474                    out.print(' ');
13475                    provider.printComponentShortName(out);
13476            if (count > 1) {
13477                out.print(" ("); out.print(count); out.print(" filters)");
13478            }
13479            out.println();
13480        }
13481
13482        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13483                = new ArrayMap<ComponentName, PackageParser.Provider>();
13484        private int mFlags;
13485    }
13486
13487    static final class EphemeralIntentResolver
13488            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13489        /**
13490         * The result that has the highest defined order. Ordering applies on a
13491         * per-package basis. Mapping is from package name to Pair of order and
13492         * EphemeralResolveInfo.
13493         * <p>
13494         * NOTE: This is implemented as a field variable for convenience and efficiency.
13495         * By having a field variable, we're able to track filter ordering as soon as
13496         * a non-zero order is defined. Otherwise, multiple loops across the result set
13497         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13498         * this needs to be contained entirely within {@link #filterResults}.
13499         */
13500        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13501
13502        @Override
13503        protected AuxiliaryResolveInfo[] newArray(int size) {
13504            return new AuxiliaryResolveInfo[size];
13505        }
13506
13507        @Override
13508        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13509            return true;
13510        }
13511
13512        @Override
13513        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13514                int userId) {
13515            if (!sUserManager.exists(userId)) {
13516                return null;
13517            }
13518            final String packageName = responseObj.resolveInfo.getPackageName();
13519            final Integer order = responseObj.getOrder();
13520            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13521                    mOrderResult.get(packageName);
13522            // ordering is enabled and this item's order isn't high enough
13523            if (lastOrderResult != null && lastOrderResult.first >= order) {
13524                return null;
13525            }
13526            final InstantAppResolveInfo res = responseObj.resolveInfo;
13527            if (order > 0) {
13528                // non-zero order, enable ordering
13529                mOrderResult.put(packageName, new Pair<>(order, res));
13530            }
13531            return responseObj;
13532        }
13533
13534        @Override
13535        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13536            // only do work if ordering is enabled [most of the time it won't be]
13537            if (mOrderResult.size() == 0) {
13538                return;
13539            }
13540            int resultSize = results.size();
13541            for (int i = 0; i < resultSize; i++) {
13542                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13543                final String packageName = info.getPackageName();
13544                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13545                if (savedInfo == null) {
13546                    // package doesn't having ordering
13547                    continue;
13548                }
13549                if (savedInfo.second == info) {
13550                    // circled back to the highest ordered item; remove from order list
13551                    mOrderResult.remove(packageName);
13552                    if (mOrderResult.size() == 0) {
13553                        // no more ordered items
13554                        break;
13555                    }
13556                    continue;
13557                }
13558                // item has a worse order, remove it from the result list
13559                results.remove(i);
13560                resultSize--;
13561                i--;
13562            }
13563        }
13564    }
13565
13566    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13567            new Comparator<ResolveInfo>() {
13568        public int compare(ResolveInfo r1, ResolveInfo r2) {
13569            int v1 = r1.priority;
13570            int v2 = r2.priority;
13571            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13572            if (v1 != v2) {
13573                return (v1 > v2) ? -1 : 1;
13574            }
13575            v1 = r1.preferredOrder;
13576            v2 = r2.preferredOrder;
13577            if (v1 != v2) {
13578                return (v1 > v2) ? -1 : 1;
13579            }
13580            if (r1.isDefault != r2.isDefault) {
13581                return r1.isDefault ? -1 : 1;
13582            }
13583            v1 = r1.match;
13584            v2 = r2.match;
13585            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13586            if (v1 != v2) {
13587                return (v1 > v2) ? -1 : 1;
13588            }
13589            if (r1.system != r2.system) {
13590                return r1.system ? -1 : 1;
13591            }
13592            if (r1.activityInfo != null) {
13593                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13594            }
13595            if (r1.serviceInfo != null) {
13596                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13597            }
13598            if (r1.providerInfo != null) {
13599                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13600            }
13601            return 0;
13602        }
13603    };
13604
13605    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13606            new Comparator<ProviderInfo>() {
13607        public int compare(ProviderInfo p1, ProviderInfo p2) {
13608            final int v1 = p1.initOrder;
13609            final int v2 = p2.initOrder;
13610            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13611        }
13612    };
13613
13614    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13615            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13616            final int[] userIds) {
13617        mHandler.post(new Runnable() {
13618            @Override
13619            public void run() {
13620                try {
13621                    final IActivityManager am = ActivityManager.getService();
13622                    if (am == null) return;
13623                    final int[] resolvedUserIds;
13624                    if (userIds == null) {
13625                        resolvedUserIds = am.getRunningUserIds();
13626                    } else {
13627                        resolvedUserIds = userIds;
13628                    }
13629                    for (int id : resolvedUserIds) {
13630                        final Intent intent = new Intent(action,
13631                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13632                        if (extras != null) {
13633                            intent.putExtras(extras);
13634                        }
13635                        if (targetPkg != null) {
13636                            intent.setPackage(targetPkg);
13637                        }
13638                        // Modify the UID when posting to other users
13639                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13640                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13641                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13642                            intent.putExtra(Intent.EXTRA_UID, uid);
13643                        }
13644                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13645                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13646                        if (DEBUG_BROADCASTS) {
13647                            RuntimeException here = new RuntimeException("here");
13648                            here.fillInStackTrace();
13649                            Slog.d(TAG, "Sending to user " + id + ": "
13650                                    + intent.toShortString(false, true, false, false)
13651                                    + " " + intent.getExtras(), here);
13652                        }
13653                        am.broadcastIntent(null, intent, null, finishedReceiver,
13654                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13655                                null, finishedReceiver != null, false, id);
13656                    }
13657                } catch (RemoteException ex) {
13658                }
13659            }
13660        });
13661    }
13662
13663    /**
13664     * Check if the external storage media is available. This is true if there
13665     * is a mounted external storage medium or if the external storage is
13666     * emulated.
13667     */
13668    private boolean isExternalMediaAvailable() {
13669        return mMediaMounted || Environment.isExternalStorageEmulated();
13670    }
13671
13672    @Override
13673    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13674        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13675            return null;
13676        }
13677        // writer
13678        synchronized (mPackages) {
13679            if (!isExternalMediaAvailable()) {
13680                // If the external storage is no longer mounted at this point,
13681                // the caller may not have been able to delete all of this
13682                // packages files and can not delete any more.  Bail.
13683                return null;
13684            }
13685            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13686            if (lastPackage != null) {
13687                pkgs.remove(lastPackage);
13688            }
13689            if (pkgs.size() > 0) {
13690                return pkgs.get(0);
13691            }
13692        }
13693        return null;
13694    }
13695
13696    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13697        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13698                userId, andCode ? 1 : 0, packageName);
13699        if (mSystemReady) {
13700            msg.sendToTarget();
13701        } else {
13702            if (mPostSystemReadyMessages == null) {
13703                mPostSystemReadyMessages = new ArrayList<>();
13704            }
13705            mPostSystemReadyMessages.add(msg);
13706        }
13707    }
13708
13709    void startCleaningPackages() {
13710        // reader
13711        if (!isExternalMediaAvailable()) {
13712            return;
13713        }
13714        synchronized (mPackages) {
13715            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13716                return;
13717            }
13718        }
13719        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13720        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13721        IActivityManager am = ActivityManager.getService();
13722        if (am != null) {
13723            int dcsUid = -1;
13724            synchronized (mPackages) {
13725                if (!mDefaultContainerWhitelisted) {
13726                    mDefaultContainerWhitelisted = true;
13727                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13728                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13729                }
13730            }
13731            try {
13732                if (dcsUid > 0) {
13733                    am.backgroundWhitelistUid(dcsUid);
13734                }
13735                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13736                        UserHandle.USER_SYSTEM);
13737            } catch (RemoteException e) {
13738            }
13739        }
13740    }
13741
13742    @Override
13743    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13744            int installFlags, String installerPackageName, int userId) {
13745        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13746
13747        final int callingUid = Binder.getCallingUid();
13748        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13749                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13750
13751        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13752            try {
13753                if (observer != null) {
13754                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13755                }
13756            } catch (RemoteException re) {
13757            }
13758            return;
13759        }
13760
13761        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13762            installFlags |= PackageManager.INSTALL_FROM_ADB;
13763
13764        } else {
13765            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13766            // about installerPackageName.
13767
13768            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13769            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13770        }
13771
13772        UserHandle user;
13773        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13774            user = UserHandle.ALL;
13775        } else {
13776            user = new UserHandle(userId);
13777        }
13778
13779        // Only system components can circumvent runtime permissions when installing.
13780        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13781                && mContext.checkCallingOrSelfPermission(Manifest.permission
13782                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13783            throw new SecurityException("You need the "
13784                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13785                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13786        }
13787
13788        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13789                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13790            throw new IllegalArgumentException(
13791                    "New installs into ASEC containers no longer supported");
13792        }
13793
13794        final File originFile = new File(originPath);
13795        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13796
13797        final Message msg = mHandler.obtainMessage(INIT_COPY);
13798        final VerificationInfo verificationInfo = new VerificationInfo(
13799                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13800        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13801                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13802                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13803                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13804        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13805        msg.obj = params;
13806
13807        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13808                System.identityHashCode(msg.obj));
13809        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13810                System.identityHashCode(msg.obj));
13811
13812        mHandler.sendMessage(msg);
13813    }
13814
13815
13816    /**
13817     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13818     * it is acting on behalf on an enterprise or the user).
13819     *
13820     * Note that the ordering of the conditionals in this method is important. The checks we perform
13821     * are as follows, in this order:
13822     *
13823     * 1) If the install is being performed by a system app, we can trust the app to have set the
13824     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13825     *    what it is.
13826     * 2) If the install is being performed by a device or profile owner app, the install reason
13827     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13828     *    set the install reason correctly. If the app targets an older SDK version where install
13829     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13830     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13831     * 3) In all other cases, the install is being performed by a regular app that is neither part
13832     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13833     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13834     *    set to enterprise policy and if so, change it to unknown instead.
13835     */
13836    private int fixUpInstallReason(String installerPackageName, int installerUid,
13837            int installReason) {
13838        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13839                == PERMISSION_GRANTED) {
13840            // If the install is being performed by a system app, we trust that app to have set the
13841            // install reason correctly.
13842            return installReason;
13843        }
13844
13845        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13846            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13847        if (dpm != null) {
13848            ComponentName owner = null;
13849            try {
13850                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13851                if (owner == null) {
13852                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13853                }
13854            } catch (RemoteException e) {
13855            }
13856            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13857                // If the install is being performed by a device or profile owner, the install
13858                // reason should be enterprise policy.
13859                return PackageManager.INSTALL_REASON_POLICY;
13860            }
13861        }
13862
13863        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13864            // If the install is being performed by a regular app (i.e. neither system app nor
13865            // device or profile owner), we have no reason to believe that the app is acting on
13866            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13867            // change it to unknown instead.
13868            return PackageManager.INSTALL_REASON_UNKNOWN;
13869        }
13870
13871        // If the install is being performed by a regular app and the install reason was set to any
13872        // value but enterprise policy, leave the install reason unchanged.
13873        return installReason;
13874    }
13875
13876    void installStage(String packageName, File stagedDir,
13877            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13878            String installerPackageName, int installerUid, UserHandle user,
13879            Certificate[][] certificates) {
13880        if (DEBUG_EPHEMERAL) {
13881            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13882                Slog.d(TAG, "Ephemeral install of " + packageName);
13883            }
13884        }
13885        final VerificationInfo verificationInfo = new VerificationInfo(
13886                sessionParams.originatingUri, sessionParams.referrerUri,
13887                sessionParams.originatingUid, installerUid);
13888
13889        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13890
13891        final Message msg = mHandler.obtainMessage(INIT_COPY);
13892        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13893                sessionParams.installReason);
13894        final InstallParams params = new InstallParams(origin, null, observer,
13895                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13896                verificationInfo, user, sessionParams.abiOverride,
13897                sessionParams.grantedRuntimePermissions, certificates, installReason);
13898        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13899        msg.obj = params;
13900
13901        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13902                System.identityHashCode(msg.obj));
13903        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13904                System.identityHashCode(msg.obj));
13905
13906        mHandler.sendMessage(msg);
13907    }
13908
13909    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13910            int userId) {
13911        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13912        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13913                false /*startReceiver*/, pkgSetting.appId, userId);
13914
13915        // Send a session commit broadcast
13916        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13917        info.installReason = pkgSetting.getInstallReason(userId);
13918        info.appPackageName = packageName;
13919        sendSessionCommitBroadcast(info, userId);
13920    }
13921
13922    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13923            boolean includeStopped, int appId, int... userIds) {
13924        if (ArrayUtils.isEmpty(userIds)) {
13925            return;
13926        }
13927        Bundle extras = new Bundle(1);
13928        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13929        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13930
13931        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13932                packageName, extras, 0, null, null, userIds);
13933        if (sendBootCompleted) {
13934            mHandler.post(() -> {
13935                        for (int userId : userIds) {
13936                            sendBootCompletedBroadcastToSystemApp(
13937                                    packageName, includeStopped, userId);
13938                        }
13939                    }
13940            );
13941        }
13942    }
13943
13944    /**
13945     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13946     * automatically without needing an explicit launch.
13947     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13948     */
13949    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13950            int userId) {
13951        // If user is not running, the app didn't miss any broadcast
13952        if (!mUserManagerInternal.isUserRunning(userId)) {
13953            return;
13954        }
13955        final IActivityManager am = ActivityManager.getService();
13956        try {
13957            // Deliver LOCKED_BOOT_COMPLETED first
13958            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13959                    .setPackage(packageName);
13960            if (includeStopped) {
13961                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13962            }
13963            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13964            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13965                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13966
13967            // Deliver BOOT_COMPLETED only if user is unlocked
13968            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13969                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13970                if (includeStopped) {
13971                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13972                }
13973                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13974                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13975            }
13976        } catch (RemoteException e) {
13977            throw e.rethrowFromSystemServer();
13978        }
13979    }
13980
13981    @Override
13982    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13983            int userId) {
13984        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13985        PackageSetting pkgSetting;
13986        final int callingUid = Binder.getCallingUid();
13987        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13988                true /* requireFullPermission */, true /* checkShell */,
13989                "setApplicationHiddenSetting for user " + userId);
13990
13991        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13992            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13993            return false;
13994        }
13995
13996        long callingId = Binder.clearCallingIdentity();
13997        try {
13998            boolean sendAdded = false;
13999            boolean sendRemoved = false;
14000            // writer
14001            synchronized (mPackages) {
14002                pkgSetting = mSettings.mPackages.get(packageName);
14003                if (pkgSetting == null) {
14004                    return false;
14005                }
14006                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14007                    return false;
14008                }
14009                // Do not allow "android" is being disabled
14010                if ("android".equals(packageName)) {
14011                    Slog.w(TAG, "Cannot hide package: android");
14012                    return false;
14013                }
14014                // Cannot hide static shared libs as they are considered
14015                // a part of the using app (emulating static linking). Also
14016                // static libs are installed always on internal storage.
14017                PackageParser.Package pkg = mPackages.get(packageName);
14018                if (pkg != null && pkg.staticSharedLibName != null) {
14019                    Slog.w(TAG, "Cannot hide package: " + packageName
14020                            + " providing static shared library: "
14021                            + pkg.staticSharedLibName);
14022                    return false;
14023                }
14024                // Only allow protected packages to hide themselves.
14025                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14026                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14027                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14028                    return false;
14029                }
14030
14031                if (pkgSetting.getHidden(userId) != hidden) {
14032                    pkgSetting.setHidden(hidden, userId);
14033                    mSettings.writePackageRestrictionsLPr(userId);
14034                    if (hidden) {
14035                        sendRemoved = true;
14036                    } else {
14037                        sendAdded = true;
14038                    }
14039                }
14040            }
14041            if (sendAdded) {
14042                sendPackageAddedForUser(packageName, pkgSetting, userId);
14043                return true;
14044            }
14045            if (sendRemoved) {
14046                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14047                        "hiding pkg");
14048                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14049                return true;
14050            }
14051        } finally {
14052            Binder.restoreCallingIdentity(callingId);
14053        }
14054        return false;
14055    }
14056
14057    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14058            int userId) {
14059        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14060        info.removedPackage = packageName;
14061        info.installerPackageName = pkgSetting.installerPackageName;
14062        info.removedUsers = new int[] {userId};
14063        info.broadcastUsers = new int[] {userId};
14064        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14065        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14066    }
14067
14068    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14069        if (pkgList.length > 0) {
14070            Bundle extras = new Bundle(1);
14071            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14072
14073            sendPackageBroadcast(
14074                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14075                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14076                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14077                    new int[] {userId});
14078        }
14079    }
14080
14081    /**
14082     * Returns true if application is not found or there was an error. Otherwise it returns
14083     * the hidden state of the package for the given user.
14084     */
14085    @Override
14086    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14088        final int callingUid = Binder.getCallingUid();
14089        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14090                true /* requireFullPermission */, false /* checkShell */,
14091                "getApplicationHidden for user " + userId);
14092        PackageSetting ps;
14093        long callingId = Binder.clearCallingIdentity();
14094        try {
14095            // writer
14096            synchronized (mPackages) {
14097                ps = mSettings.mPackages.get(packageName);
14098                if (ps == null) {
14099                    return true;
14100                }
14101                if (filterAppAccessLPr(ps, callingUid, userId)) {
14102                    return true;
14103                }
14104                return ps.getHidden(userId);
14105            }
14106        } finally {
14107            Binder.restoreCallingIdentity(callingId);
14108        }
14109    }
14110
14111    /**
14112     * @hide
14113     */
14114    @Override
14115    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14116            int installReason) {
14117        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14118                null);
14119        PackageSetting pkgSetting;
14120        final int callingUid = Binder.getCallingUid();
14121        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14122                true /* requireFullPermission */, true /* checkShell */,
14123                "installExistingPackage for user " + userId);
14124        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14125            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14126        }
14127
14128        long callingId = Binder.clearCallingIdentity();
14129        try {
14130            boolean installed = false;
14131            final boolean instantApp =
14132                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14133            final boolean fullApp =
14134                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14135
14136            // writer
14137            synchronized (mPackages) {
14138                pkgSetting = mSettings.mPackages.get(packageName);
14139                if (pkgSetting == null) {
14140                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14141                }
14142                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14143                    // only allow the existing package to be used if it's installed as a full
14144                    // application for at least one user
14145                    boolean installAllowed = false;
14146                    for (int checkUserId : sUserManager.getUserIds()) {
14147                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14148                        if (installAllowed) {
14149                            break;
14150                        }
14151                    }
14152                    if (!installAllowed) {
14153                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14154                    }
14155                }
14156                if (!pkgSetting.getInstalled(userId)) {
14157                    pkgSetting.setInstalled(true, userId);
14158                    pkgSetting.setHidden(false, userId);
14159                    pkgSetting.setInstallReason(installReason, userId);
14160                    mSettings.writePackageRestrictionsLPr(userId);
14161                    mSettings.writeKernelMappingLPr(pkgSetting);
14162                    installed = true;
14163                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14164                    // upgrade app from instant to full; we don't allow app downgrade
14165                    installed = true;
14166                }
14167                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14168            }
14169
14170            if (installed) {
14171                if (pkgSetting.pkg != null) {
14172                    synchronized (mInstallLock) {
14173                        // We don't need to freeze for a brand new install
14174                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14175                    }
14176                }
14177                sendPackageAddedForUser(packageName, pkgSetting, userId);
14178                synchronized (mPackages) {
14179                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14180                }
14181            }
14182        } finally {
14183            Binder.restoreCallingIdentity(callingId);
14184        }
14185
14186        return PackageManager.INSTALL_SUCCEEDED;
14187    }
14188
14189    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14190            boolean instantApp, boolean fullApp) {
14191        // no state specified; do nothing
14192        if (!instantApp && !fullApp) {
14193            return;
14194        }
14195        if (userId != UserHandle.USER_ALL) {
14196            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14197                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14198            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14199                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14200            }
14201        } else {
14202            for (int currentUserId : sUserManager.getUserIds()) {
14203                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14204                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14205                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14206                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14207                }
14208            }
14209        }
14210    }
14211
14212    boolean isUserRestricted(int userId, String restrictionKey) {
14213        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14214        if (restrictions.getBoolean(restrictionKey, false)) {
14215            Log.w(TAG, "User is restricted: " + restrictionKey);
14216            return true;
14217        }
14218        return false;
14219    }
14220
14221    @Override
14222    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14223            int userId) {
14224        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14225        final int callingUid = Binder.getCallingUid();
14226        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14227                true /* requireFullPermission */, true /* checkShell */,
14228                "setPackagesSuspended for user " + userId);
14229
14230        if (ArrayUtils.isEmpty(packageNames)) {
14231            return packageNames;
14232        }
14233
14234        // List of package names for whom the suspended state has changed.
14235        List<String> changedPackages = new ArrayList<>(packageNames.length);
14236        // List of package names for whom the suspended state is not set as requested in this
14237        // method.
14238        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14239        long callingId = Binder.clearCallingIdentity();
14240        try {
14241            for (int i = 0; i < packageNames.length; i++) {
14242                String packageName = packageNames[i];
14243                boolean changed = false;
14244                final int appId;
14245                synchronized (mPackages) {
14246                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14247                    if (pkgSetting == null
14248                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14249                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14250                                + "\". Skipping suspending/un-suspending.");
14251                        unactionedPackages.add(packageName);
14252                        continue;
14253                    }
14254                    appId = pkgSetting.appId;
14255                    if (pkgSetting.getSuspended(userId) != suspended) {
14256                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14257                            unactionedPackages.add(packageName);
14258                            continue;
14259                        }
14260                        pkgSetting.setSuspended(suspended, userId);
14261                        mSettings.writePackageRestrictionsLPr(userId);
14262                        changed = true;
14263                        changedPackages.add(packageName);
14264                    }
14265                }
14266
14267                if (changed && suspended) {
14268                    killApplication(packageName, UserHandle.getUid(userId, appId),
14269                            "suspending package");
14270                }
14271            }
14272        } finally {
14273            Binder.restoreCallingIdentity(callingId);
14274        }
14275
14276        if (!changedPackages.isEmpty()) {
14277            sendPackagesSuspendedForUser(changedPackages.toArray(
14278                    new String[changedPackages.size()]), userId, suspended);
14279        }
14280
14281        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14282    }
14283
14284    @Override
14285    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14286        final int callingUid = Binder.getCallingUid();
14287        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14288                true /* requireFullPermission */, false /* checkShell */,
14289                "isPackageSuspendedForUser for user " + userId);
14290        synchronized (mPackages) {
14291            final PackageSetting ps = mSettings.mPackages.get(packageName);
14292            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14293                throw new IllegalArgumentException("Unknown target package: " + packageName);
14294            }
14295            return ps.getSuspended(userId);
14296        }
14297    }
14298
14299    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14300        if (isPackageDeviceAdmin(packageName, userId)) {
14301            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14302                    + "\": has an active device admin");
14303            return false;
14304        }
14305
14306        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14307        if (packageName.equals(activeLauncherPackageName)) {
14308            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14309                    + "\": contains the active launcher");
14310            return false;
14311        }
14312
14313        if (packageName.equals(mRequiredInstallerPackage)) {
14314            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14315                    + "\": required for package installation");
14316            return false;
14317        }
14318
14319        if (packageName.equals(mRequiredUninstallerPackage)) {
14320            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14321                    + "\": required for package uninstallation");
14322            return false;
14323        }
14324
14325        if (packageName.equals(mRequiredVerifierPackage)) {
14326            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14327                    + "\": required for package verification");
14328            return false;
14329        }
14330
14331        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14332            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14333                    + "\": is the default dialer");
14334            return false;
14335        }
14336
14337        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14338            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14339                    + "\": protected package");
14340            return false;
14341        }
14342
14343        // Cannot suspend static shared libs as they are considered
14344        // a part of the using app (emulating static linking). Also
14345        // static libs are installed always on internal storage.
14346        PackageParser.Package pkg = mPackages.get(packageName);
14347        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14348            Slog.w(TAG, "Cannot suspend package: " + packageName
14349                    + " providing static shared library: "
14350                    + pkg.staticSharedLibName);
14351            return false;
14352        }
14353
14354        return true;
14355    }
14356
14357    private String getActiveLauncherPackageName(int userId) {
14358        Intent intent = new Intent(Intent.ACTION_MAIN);
14359        intent.addCategory(Intent.CATEGORY_HOME);
14360        ResolveInfo resolveInfo = resolveIntent(
14361                intent,
14362                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14363                PackageManager.MATCH_DEFAULT_ONLY,
14364                userId);
14365
14366        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14367    }
14368
14369    private String getDefaultDialerPackageName(int userId) {
14370        synchronized (mPackages) {
14371            return mSettings.getDefaultDialerPackageNameLPw(userId);
14372        }
14373    }
14374
14375    @Override
14376    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14377        mContext.enforceCallingOrSelfPermission(
14378                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14379                "Only package verification agents can verify applications");
14380
14381        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14382        final PackageVerificationResponse response = new PackageVerificationResponse(
14383                verificationCode, Binder.getCallingUid());
14384        msg.arg1 = id;
14385        msg.obj = response;
14386        mHandler.sendMessage(msg);
14387    }
14388
14389    @Override
14390    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14391            long millisecondsToDelay) {
14392        mContext.enforceCallingOrSelfPermission(
14393                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14394                "Only package verification agents can extend verification timeouts");
14395
14396        final PackageVerificationState state = mPendingVerification.get(id);
14397        final PackageVerificationResponse response = new PackageVerificationResponse(
14398                verificationCodeAtTimeout, Binder.getCallingUid());
14399
14400        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14401            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14402        }
14403        if (millisecondsToDelay < 0) {
14404            millisecondsToDelay = 0;
14405        }
14406        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14407                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14408            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14409        }
14410
14411        if ((state != null) && !state.timeoutExtended()) {
14412            state.extendTimeout();
14413
14414            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14415            msg.arg1 = id;
14416            msg.obj = response;
14417            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14418        }
14419    }
14420
14421    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14422            int verificationCode, UserHandle user) {
14423        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14424        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14425        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14426        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14427        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14428
14429        mContext.sendBroadcastAsUser(intent, user,
14430                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14431    }
14432
14433    private ComponentName matchComponentForVerifier(String packageName,
14434            List<ResolveInfo> receivers) {
14435        ActivityInfo targetReceiver = null;
14436
14437        final int NR = receivers.size();
14438        for (int i = 0; i < NR; i++) {
14439            final ResolveInfo info = receivers.get(i);
14440            if (info.activityInfo == null) {
14441                continue;
14442            }
14443
14444            if (packageName.equals(info.activityInfo.packageName)) {
14445                targetReceiver = info.activityInfo;
14446                break;
14447            }
14448        }
14449
14450        if (targetReceiver == null) {
14451            return null;
14452        }
14453
14454        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14455    }
14456
14457    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14458            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14459        if (pkgInfo.verifiers.length == 0) {
14460            return null;
14461        }
14462
14463        final int N = pkgInfo.verifiers.length;
14464        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14465        for (int i = 0; i < N; i++) {
14466            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14467
14468            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14469                    receivers);
14470            if (comp == null) {
14471                continue;
14472            }
14473
14474            final int verifierUid = getUidForVerifier(verifierInfo);
14475            if (verifierUid == -1) {
14476                continue;
14477            }
14478
14479            if (DEBUG_VERIFY) {
14480                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14481                        + " with the correct signature");
14482            }
14483            sufficientVerifiers.add(comp);
14484            verificationState.addSufficientVerifier(verifierUid);
14485        }
14486
14487        return sufficientVerifiers;
14488    }
14489
14490    private int getUidForVerifier(VerifierInfo verifierInfo) {
14491        synchronized (mPackages) {
14492            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14493            if (pkg == null) {
14494                return -1;
14495            } else if (pkg.mSignatures.length != 1) {
14496                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14497                        + " has more than one signature; ignoring");
14498                return -1;
14499            }
14500
14501            /*
14502             * If the public key of the package's signature does not match
14503             * our expected public key, then this is a different package and
14504             * we should skip.
14505             */
14506
14507            final byte[] expectedPublicKey;
14508            try {
14509                final Signature verifierSig = pkg.mSignatures[0];
14510                final PublicKey publicKey = verifierSig.getPublicKey();
14511                expectedPublicKey = publicKey.getEncoded();
14512            } catch (CertificateException e) {
14513                return -1;
14514            }
14515
14516            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14517
14518            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14519                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14520                        + " does not have the expected public key; ignoring");
14521                return -1;
14522            }
14523
14524            return pkg.applicationInfo.uid;
14525        }
14526    }
14527
14528    @Override
14529    public void finishPackageInstall(int token, boolean didLaunch) {
14530        enforceSystemOrRoot("Only the system is allowed to finish installs");
14531
14532        if (DEBUG_INSTALL) {
14533            Slog.v(TAG, "BM finishing package install for " + token);
14534        }
14535        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14536
14537        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14538        mHandler.sendMessage(msg);
14539    }
14540
14541    /**
14542     * Get the verification agent timeout.  Used for both the APK verifier and the
14543     * intent filter verifier.
14544     *
14545     * @return verification timeout in milliseconds
14546     */
14547    private long getVerificationTimeout() {
14548        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14549                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14550                DEFAULT_VERIFICATION_TIMEOUT);
14551    }
14552
14553    /**
14554     * Get the default verification agent response code.
14555     *
14556     * @return default verification response code
14557     */
14558    private int getDefaultVerificationResponse(UserHandle user) {
14559        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14560            return PackageManager.VERIFICATION_REJECT;
14561        }
14562        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14563                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14564                DEFAULT_VERIFICATION_RESPONSE);
14565    }
14566
14567    /**
14568     * Check whether or not package verification has been enabled.
14569     *
14570     * @return true if verification should be performed
14571     */
14572    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14573        if (!DEFAULT_VERIFY_ENABLE) {
14574            return false;
14575        }
14576
14577        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14578
14579        // Check if installing from ADB
14580        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14581            // Do not run verification in a test harness environment
14582            if (ActivityManager.isRunningInTestHarness()) {
14583                return false;
14584            }
14585            if (ensureVerifyAppsEnabled) {
14586                return true;
14587            }
14588            // Check if the developer does not want package verification for ADB installs
14589            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14590                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14591                return false;
14592            }
14593        } else {
14594            // only when not installed from ADB, skip verification for instant apps when
14595            // the installer and verifier are the same.
14596            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14597                if (mInstantAppInstallerActivity != null
14598                        && mInstantAppInstallerActivity.packageName.equals(
14599                                mRequiredVerifierPackage)) {
14600                    try {
14601                        mContext.getSystemService(AppOpsManager.class)
14602                                .checkPackage(installerUid, mRequiredVerifierPackage);
14603                        if (DEBUG_VERIFY) {
14604                            Slog.i(TAG, "disable verification for instant app");
14605                        }
14606                        return false;
14607                    } catch (SecurityException ignore) { }
14608                }
14609            }
14610        }
14611
14612        if (ensureVerifyAppsEnabled) {
14613            return true;
14614        }
14615
14616        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14617                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14618    }
14619
14620    @Override
14621    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14622            throws RemoteException {
14623        mContext.enforceCallingOrSelfPermission(
14624                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14625                "Only intentfilter verification agents can verify applications");
14626
14627        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14628        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14629                Binder.getCallingUid(), verificationCode, failedDomains);
14630        msg.arg1 = id;
14631        msg.obj = response;
14632        mHandler.sendMessage(msg);
14633    }
14634
14635    @Override
14636    public int getIntentVerificationStatus(String packageName, int userId) {
14637        final int callingUid = Binder.getCallingUid();
14638        if (UserHandle.getUserId(callingUid) != userId) {
14639            mContext.enforceCallingOrSelfPermission(
14640                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14641                    "getIntentVerificationStatus" + userId);
14642        }
14643        if (getInstantAppPackageName(callingUid) != null) {
14644            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14645        }
14646        synchronized (mPackages) {
14647            final PackageSetting ps = mSettings.mPackages.get(packageName);
14648            if (ps == null
14649                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14650                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14651            }
14652            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14653        }
14654    }
14655
14656    @Override
14657    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14658        mContext.enforceCallingOrSelfPermission(
14659                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14660
14661        boolean result = false;
14662        synchronized (mPackages) {
14663            final PackageSetting ps = mSettings.mPackages.get(packageName);
14664            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14665                return false;
14666            }
14667            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14668        }
14669        if (result) {
14670            scheduleWritePackageRestrictionsLocked(userId);
14671        }
14672        return result;
14673    }
14674
14675    @Override
14676    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14677            String packageName) {
14678        final int callingUid = Binder.getCallingUid();
14679        if (getInstantAppPackageName(callingUid) != null) {
14680            return ParceledListSlice.emptyList();
14681        }
14682        synchronized (mPackages) {
14683            final PackageSetting ps = mSettings.mPackages.get(packageName);
14684            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14685                return ParceledListSlice.emptyList();
14686            }
14687            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14688        }
14689    }
14690
14691    @Override
14692    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14693        if (TextUtils.isEmpty(packageName)) {
14694            return ParceledListSlice.emptyList();
14695        }
14696        final int callingUid = Binder.getCallingUid();
14697        final int callingUserId = UserHandle.getUserId(callingUid);
14698        synchronized (mPackages) {
14699            PackageParser.Package pkg = mPackages.get(packageName);
14700            if (pkg == null || pkg.activities == null) {
14701                return ParceledListSlice.emptyList();
14702            }
14703            if (pkg.mExtras == null) {
14704                return ParceledListSlice.emptyList();
14705            }
14706            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14707            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14708                return ParceledListSlice.emptyList();
14709            }
14710            final int count = pkg.activities.size();
14711            ArrayList<IntentFilter> result = new ArrayList<>();
14712            for (int n=0; n<count; n++) {
14713                PackageParser.Activity activity = pkg.activities.get(n);
14714                if (activity.intents != null && activity.intents.size() > 0) {
14715                    result.addAll(activity.intents);
14716                }
14717            }
14718            return new ParceledListSlice<>(result);
14719        }
14720    }
14721
14722    @Override
14723    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14724        mContext.enforceCallingOrSelfPermission(
14725                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14726        if (UserHandle.getCallingUserId() != userId) {
14727            mContext.enforceCallingOrSelfPermission(
14728                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14729        }
14730
14731        synchronized (mPackages) {
14732            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14733            if (packageName != null) {
14734                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14735                        packageName, userId);
14736            }
14737            return result;
14738        }
14739    }
14740
14741    @Override
14742    public String getDefaultBrowserPackageName(int userId) {
14743        if (UserHandle.getCallingUserId() != userId) {
14744            mContext.enforceCallingOrSelfPermission(
14745                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14746        }
14747        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14748            return null;
14749        }
14750        synchronized (mPackages) {
14751            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14752        }
14753    }
14754
14755    /**
14756     * Get the "allow unknown sources" setting.
14757     *
14758     * @return the current "allow unknown sources" setting
14759     */
14760    private int getUnknownSourcesSettings() {
14761        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14762                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14763                -1);
14764    }
14765
14766    @Override
14767    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14768        final int callingUid = Binder.getCallingUid();
14769        if (getInstantAppPackageName(callingUid) != null) {
14770            return;
14771        }
14772        // writer
14773        synchronized (mPackages) {
14774            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14775            if (targetPackageSetting == null
14776                    || filterAppAccessLPr(
14777                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14778                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14779            }
14780
14781            PackageSetting installerPackageSetting;
14782            if (installerPackageName != null) {
14783                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14784                if (installerPackageSetting == null) {
14785                    throw new IllegalArgumentException("Unknown installer package: "
14786                            + installerPackageName);
14787                }
14788            } else {
14789                installerPackageSetting = null;
14790            }
14791
14792            Signature[] callerSignature;
14793            Object obj = mSettings.getUserIdLPr(callingUid);
14794            if (obj != null) {
14795                if (obj instanceof SharedUserSetting) {
14796                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14797                } else if (obj instanceof PackageSetting) {
14798                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14799                } else {
14800                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14801                }
14802            } else {
14803                throw new SecurityException("Unknown calling UID: " + callingUid);
14804            }
14805
14806            // Verify: can't set installerPackageName to a package that is
14807            // not signed with the same cert as the caller.
14808            if (installerPackageSetting != null) {
14809                if (compareSignatures(callerSignature,
14810                        installerPackageSetting.signatures.mSignatures)
14811                        != PackageManager.SIGNATURE_MATCH) {
14812                    throw new SecurityException(
14813                            "Caller does not have same cert as new installer package "
14814                            + installerPackageName);
14815                }
14816            }
14817
14818            // Verify: if target already has an installer package, it must
14819            // be signed with the same cert as the caller.
14820            if (targetPackageSetting.installerPackageName != null) {
14821                PackageSetting setting = mSettings.mPackages.get(
14822                        targetPackageSetting.installerPackageName);
14823                // If the currently set package isn't valid, then it's always
14824                // okay to change it.
14825                if (setting != null) {
14826                    if (compareSignatures(callerSignature,
14827                            setting.signatures.mSignatures)
14828                            != PackageManager.SIGNATURE_MATCH) {
14829                        throw new SecurityException(
14830                                "Caller does not have same cert as old installer package "
14831                                + targetPackageSetting.installerPackageName);
14832                    }
14833                }
14834            }
14835
14836            // Okay!
14837            targetPackageSetting.installerPackageName = installerPackageName;
14838            if (installerPackageName != null) {
14839                mSettings.mInstallerPackages.add(installerPackageName);
14840            }
14841            scheduleWriteSettingsLocked();
14842        }
14843    }
14844
14845    @Override
14846    public void setApplicationCategoryHint(String packageName, int categoryHint,
14847            String callerPackageName) {
14848        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14849            throw new SecurityException("Instant applications don't have access to this method");
14850        }
14851        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14852                callerPackageName);
14853        synchronized (mPackages) {
14854            PackageSetting ps = mSettings.mPackages.get(packageName);
14855            if (ps == null) {
14856                throw new IllegalArgumentException("Unknown target package " + packageName);
14857            }
14858            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14859                throw new IllegalArgumentException("Unknown target package " + packageName);
14860            }
14861            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14862                throw new IllegalArgumentException("Calling package " + callerPackageName
14863                        + " is not installer for " + packageName);
14864            }
14865
14866            if (ps.categoryHint != categoryHint) {
14867                ps.categoryHint = categoryHint;
14868                scheduleWriteSettingsLocked();
14869            }
14870        }
14871    }
14872
14873    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14874        // Queue up an async operation since the package installation may take a little while.
14875        mHandler.post(new Runnable() {
14876            public void run() {
14877                mHandler.removeCallbacks(this);
14878                 // Result object to be returned
14879                PackageInstalledInfo res = new PackageInstalledInfo();
14880                res.setReturnCode(currentStatus);
14881                res.uid = -1;
14882                res.pkg = null;
14883                res.removedInfo = null;
14884                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14885                    args.doPreInstall(res.returnCode);
14886                    synchronized (mInstallLock) {
14887                        installPackageTracedLI(args, res);
14888                    }
14889                    args.doPostInstall(res.returnCode, res.uid);
14890                }
14891
14892                // A restore should be performed at this point if (a) the install
14893                // succeeded, (b) the operation is not an update, and (c) the new
14894                // package has not opted out of backup participation.
14895                final boolean update = res.removedInfo != null
14896                        && res.removedInfo.removedPackage != null;
14897                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14898                boolean doRestore = !update
14899                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14900
14901                // Set up the post-install work request bookkeeping.  This will be used
14902                // and cleaned up by the post-install event handling regardless of whether
14903                // there's a restore pass performed.  Token values are >= 1.
14904                int token;
14905                if (mNextInstallToken < 0) mNextInstallToken = 1;
14906                token = mNextInstallToken++;
14907
14908                PostInstallData data = new PostInstallData(args, res);
14909                mRunningInstalls.put(token, data);
14910                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14911
14912                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14913                    // Pass responsibility to the Backup Manager.  It will perform a
14914                    // restore if appropriate, then pass responsibility back to the
14915                    // Package Manager to run the post-install observer callbacks
14916                    // and broadcasts.
14917                    IBackupManager bm = IBackupManager.Stub.asInterface(
14918                            ServiceManager.getService(Context.BACKUP_SERVICE));
14919                    if (bm != null) {
14920                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14921                                + " to BM for possible restore");
14922                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14923                        try {
14924                            // TODO: http://b/22388012
14925                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14926                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14927                            } else {
14928                                doRestore = false;
14929                            }
14930                        } catch (RemoteException e) {
14931                            // can't happen; the backup manager is local
14932                        } catch (Exception e) {
14933                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14934                            doRestore = false;
14935                        }
14936                    } else {
14937                        Slog.e(TAG, "Backup Manager not found!");
14938                        doRestore = false;
14939                    }
14940                }
14941
14942                if (!doRestore) {
14943                    // No restore possible, or the Backup Manager was mysteriously not
14944                    // available -- just fire the post-install work request directly.
14945                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14946
14947                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14948
14949                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14950                    mHandler.sendMessage(msg);
14951                }
14952            }
14953        });
14954    }
14955
14956    /**
14957     * Callback from PackageSettings whenever an app is first transitioned out of the
14958     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14959     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14960     * here whether the app is the target of an ongoing install, and only send the
14961     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14962     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14963     * handling.
14964     */
14965    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14966        // Serialize this with the rest of the install-process message chain.  In the
14967        // restore-at-install case, this Runnable will necessarily run before the
14968        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14969        // are coherent.  In the non-restore case, the app has already completed install
14970        // and been launched through some other means, so it is not in a problematic
14971        // state for observers to see the FIRST_LAUNCH signal.
14972        mHandler.post(new Runnable() {
14973            @Override
14974            public void run() {
14975                for (int i = 0; i < mRunningInstalls.size(); i++) {
14976                    final PostInstallData data = mRunningInstalls.valueAt(i);
14977                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14978                        continue;
14979                    }
14980                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14981                        // right package; but is it for the right user?
14982                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14983                            if (userId == data.res.newUsers[uIndex]) {
14984                                if (DEBUG_BACKUP) {
14985                                    Slog.i(TAG, "Package " + pkgName
14986                                            + " being restored so deferring FIRST_LAUNCH");
14987                                }
14988                                return;
14989                            }
14990                        }
14991                    }
14992                }
14993                // didn't find it, so not being restored
14994                if (DEBUG_BACKUP) {
14995                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14996                }
14997                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14998            }
14999        });
15000    }
15001
15002    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15003        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15004                installerPkg, null, userIds);
15005    }
15006
15007    private abstract class HandlerParams {
15008        private static final int MAX_RETRIES = 4;
15009
15010        /**
15011         * Number of times startCopy() has been attempted and had a non-fatal
15012         * error.
15013         */
15014        private int mRetries = 0;
15015
15016        /** User handle for the user requesting the information or installation. */
15017        private final UserHandle mUser;
15018        String traceMethod;
15019        int traceCookie;
15020
15021        HandlerParams(UserHandle user) {
15022            mUser = user;
15023        }
15024
15025        UserHandle getUser() {
15026            return mUser;
15027        }
15028
15029        HandlerParams setTraceMethod(String traceMethod) {
15030            this.traceMethod = traceMethod;
15031            return this;
15032        }
15033
15034        HandlerParams setTraceCookie(int traceCookie) {
15035            this.traceCookie = traceCookie;
15036            return this;
15037        }
15038
15039        final boolean startCopy() {
15040            boolean res;
15041            try {
15042                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15043
15044                if (++mRetries > MAX_RETRIES) {
15045                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15046                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15047                    handleServiceError();
15048                    return false;
15049                } else {
15050                    handleStartCopy();
15051                    res = true;
15052                }
15053            } catch (RemoteException e) {
15054                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15055                mHandler.sendEmptyMessage(MCS_RECONNECT);
15056                res = false;
15057            }
15058            handleReturnCode();
15059            return res;
15060        }
15061
15062        final void serviceError() {
15063            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15064            handleServiceError();
15065            handleReturnCode();
15066        }
15067
15068        abstract void handleStartCopy() throws RemoteException;
15069        abstract void handleServiceError();
15070        abstract void handleReturnCode();
15071    }
15072
15073    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15074        for (File path : paths) {
15075            try {
15076                mcs.clearDirectory(path.getAbsolutePath());
15077            } catch (RemoteException e) {
15078            }
15079        }
15080    }
15081
15082    static class OriginInfo {
15083        /**
15084         * Location where install is coming from, before it has been
15085         * copied/renamed into place. This could be a single monolithic APK
15086         * file, or a cluster directory. This location may be untrusted.
15087         */
15088        final File file;
15089
15090        /**
15091         * Flag indicating that {@link #file} or {@link #cid} has already been
15092         * staged, meaning downstream users don't need to defensively copy the
15093         * contents.
15094         */
15095        final boolean staged;
15096
15097        /**
15098         * Flag indicating that {@link #file} or {@link #cid} is an already
15099         * installed app that is being moved.
15100         */
15101        final boolean existing;
15102
15103        final String resolvedPath;
15104        final File resolvedFile;
15105
15106        static OriginInfo fromNothing() {
15107            return new OriginInfo(null, false, false);
15108        }
15109
15110        static OriginInfo fromUntrustedFile(File file) {
15111            return new OriginInfo(file, false, false);
15112        }
15113
15114        static OriginInfo fromExistingFile(File file) {
15115            return new OriginInfo(file, false, true);
15116        }
15117
15118        static OriginInfo fromStagedFile(File file) {
15119            return new OriginInfo(file, true, false);
15120        }
15121
15122        private OriginInfo(File file, boolean staged, boolean existing) {
15123            this.file = file;
15124            this.staged = staged;
15125            this.existing = existing;
15126
15127            if (file != null) {
15128                resolvedPath = file.getAbsolutePath();
15129                resolvedFile = file;
15130            } else {
15131                resolvedPath = null;
15132                resolvedFile = null;
15133            }
15134        }
15135    }
15136
15137    static class MoveInfo {
15138        final int moveId;
15139        final String fromUuid;
15140        final String toUuid;
15141        final String packageName;
15142        final String dataAppName;
15143        final int appId;
15144        final String seinfo;
15145        final int targetSdkVersion;
15146
15147        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15148                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15149            this.moveId = moveId;
15150            this.fromUuid = fromUuid;
15151            this.toUuid = toUuid;
15152            this.packageName = packageName;
15153            this.dataAppName = dataAppName;
15154            this.appId = appId;
15155            this.seinfo = seinfo;
15156            this.targetSdkVersion = targetSdkVersion;
15157        }
15158    }
15159
15160    static class VerificationInfo {
15161        /** A constant used to indicate that a uid value is not present. */
15162        public static final int NO_UID = -1;
15163
15164        /** URI referencing where the package was downloaded from. */
15165        final Uri originatingUri;
15166
15167        /** HTTP referrer URI associated with the originatingURI. */
15168        final Uri referrer;
15169
15170        /** UID of the application that the install request originated from. */
15171        final int originatingUid;
15172
15173        /** UID of application requesting the install */
15174        final int installerUid;
15175
15176        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15177            this.originatingUri = originatingUri;
15178            this.referrer = referrer;
15179            this.originatingUid = originatingUid;
15180            this.installerUid = installerUid;
15181        }
15182    }
15183
15184    class InstallParams extends HandlerParams {
15185        final OriginInfo origin;
15186        final MoveInfo move;
15187        final IPackageInstallObserver2 observer;
15188        int installFlags;
15189        final String installerPackageName;
15190        final String volumeUuid;
15191        private InstallArgs mArgs;
15192        private int mRet;
15193        final String packageAbiOverride;
15194        final String[] grantedRuntimePermissions;
15195        final VerificationInfo verificationInfo;
15196        final Certificate[][] certificates;
15197        final int installReason;
15198
15199        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15200                int installFlags, String installerPackageName, String volumeUuid,
15201                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15202                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15203            super(user);
15204            this.origin = origin;
15205            this.move = move;
15206            this.observer = observer;
15207            this.installFlags = installFlags;
15208            this.installerPackageName = installerPackageName;
15209            this.volumeUuid = volumeUuid;
15210            this.verificationInfo = verificationInfo;
15211            this.packageAbiOverride = packageAbiOverride;
15212            this.grantedRuntimePermissions = grantedPermissions;
15213            this.certificates = certificates;
15214            this.installReason = installReason;
15215        }
15216
15217        @Override
15218        public String toString() {
15219            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15220                    + " file=" + origin.file + "}";
15221        }
15222
15223        private int installLocationPolicy(PackageInfoLite pkgLite) {
15224            String packageName = pkgLite.packageName;
15225            int installLocation = pkgLite.installLocation;
15226            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15227            // reader
15228            synchronized (mPackages) {
15229                // Currently installed package which the new package is attempting to replace or
15230                // null if no such package is installed.
15231                PackageParser.Package installedPkg = mPackages.get(packageName);
15232                // Package which currently owns the data which the new package will own if installed.
15233                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15234                // will be null whereas dataOwnerPkg will contain information about the package
15235                // which was uninstalled while keeping its data.
15236                PackageParser.Package dataOwnerPkg = installedPkg;
15237                if (dataOwnerPkg  == null) {
15238                    PackageSetting ps = mSettings.mPackages.get(packageName);
15239                    if (ps != null) {
15240                        dataOwnerPkg = ps.pkg;
15241                    }
15242                }
15243
15244                if (dataOwnerPkg != null) {
15245                    // If installed, the package will get access to data left on the device by its
15246                    // predecessor. As a security measure, this is permited only if this is not a
15247                    // version downgrade or if the predecessor package is marked as debuggable and
15248                    // a downgrade is explicitly requested.
15249                    //
15250                    // On debuggable platform builds, downgrades are permitted even for
15251                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15252                    // not offer security guarantees and thus it's OK to disable some security
15253                    // mechanisms to make debugging/testing easier on those builds. However, even on
15254                    // debuggable builds downgrades of packages are permitted only if requested via
15255                    // installFlags. This is because we aim to keep the behavior of debuggable
15256                    // platform builds as close as possible to the behavior of non-debuggable
15257                    // platform builds.
15258                    final boolean downgradeRequested =
15259                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15260                    final boolean packageDebuggable =
15261                                (dataOwnerPkg.applicationInfo.flags
15262                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15263                    final boolean downgradePermitted =
15264                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15265                    if (!downgradePermitted) {
15266                        try {
15267                            checkDowngrade(dataOwnerPkg, pkgLite);
15268                        } catch (PackageManagerException e) {
15269                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15270                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15271                        }
15272                    }
15273                }
15274
15275                if (installedPkg != null) {
15276                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15277                        // Check for updated system application.
15278                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15279                            if (onSd) {
15280                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15281                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15282                            }
15283                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15284                        } else {
15285                            if (onSd) {
15286                                // Install flag overrides everything.
15287                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15288                            }
15289                            // If current upgrade specifies particular preference
15290                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15291                                // Application explicitly specified internal.
15292                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15293                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15294                                // App explictly prefers external. Let policy decide
15295                            } else {
15296                                // Prefer previous location
15297                                if (isExternal(installedPkg)) {
15298                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15299                                }
15300                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15301                            }
15302                        }
15303                    } else {
15304                        // Invalid install. Return error code
15305                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15306                    }
15307                }
15308            }
15309            // All the special cases have been taken care of.
15310            // Return result based on recommended install location.
15311            if (onSd) {
15312                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15313            }
15314            return pkgLite.recommendedInstallLocation;
15315        }
15316
15317        /*
15318         * Invoke remote method to get package information and install
15319         * location values. Override install location based on default
15320         * policy if needed and then create install arguments based
15321         * on the install location.
15322         */
15323        public void handleStartCopy() throws RemoteException {
15324            int ret = PackageManager.INSTALL_SUCCEEDED;
15325
15326            // If we're already staged, we've firmly committed to an install location
15327            if (origin.staged) {
15328                if (origin.file != null) {
15329                    installFlags |= PackageManager.INSTALL_INTERNAL;
15330                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15331                } else {
15332                    throw new IllegalStateException("Invalid stage location");
15333                }
15334            }
15335
15336            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15337            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15338            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15339            PackageInfoLite pkgLite = null;
15340
15341            if (onInt && onSd) {
15342                // Check if both bits are set.
15343                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15344                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15345            } else if (onSd && ephemeral) {
15346                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15347                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15348            } else {
15349                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15350                        packageAbiOverride);
15351
15352                if (DEBUG_EPHEMERAL && ephemeral) {
15353                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15354                }
15355
15356                /*
15357                 * If we have too little free space, try to free cache
15358                 * before giving up.
15359                 */
15360                if (!origin.staged && pkgLite.recommendedInstallLocation
15361                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15362                    // TODO: focus freeing disk space on the target device
15363                    final StorageManager storage = StorageManager.from(mContext);
15364                    final long lowThreshold = storage.getStorageLowBytes(
15365                            Environment.getDataDirectory());
15366
15367                    final long sizeBytes = mContainerService.calculateInstalledSize(
15368                            origin.resolvedPath, packageAbiOverride);
15369
15370                    try {
15371                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15372                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15373                                installFlags, packageAbiOverride);
15374                    } catch (InstallerException e) {
15375                        Slog.w(TAG, "Failed to free cache", e);
15376                    }
15377
15378                    /*
15379                     * The cache free must have deleted the file we
15380                     * downloaded to install.
15381                     *
15382                     * TODO: fix the "freeCache" call to not delete
15383                     *       the file we care about.
15384                     */
15385                    if (pkgLite.recommendedInstallLocation
15386                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15387                        pkgLite.recommendedInstallLocation
15388                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15389                    }
15390                }
15391            }
15392
15393            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15394                int loc = pkgLite.recommendedInstallLocation;
15395                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15396                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15397                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15398                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15399                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15400                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15401                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15402                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15403                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15404                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15405                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15406                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15407                } else {
15408                    // Override with defaults if needed.
15409                    loc = installLocationPolicy(pkgLite);
15410                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15411                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15412                    } else if (!onSd && !onInt) {
15413                        // Override install location with flags
15414                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15415                            // Set the flag to install on external media.
15416                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15417                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15418                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15419                            if (DEBUG_EPHEMERAL) {
15420                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15421                            }
15422                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15423                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15424                                    |PackageManager.INSTALL_INTERNAL);
15425                        } else {
15426                            // Make sure the flag for installing on external
15427                            // media is unset
15428                            installFlags |= PackageManager.INSTALL_INTERNAL;
15429                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15430                        }
15431                    }
15432                }
15433            }
15434
15435            final InstallArgs args = createInstallArgs(this);
15436            mArgs = args;
15437
15438            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15439                // TODO: http://b/22976637
15440                // Apps installed for "all" users use the device owner to verify the app
15441                UserHandle verifierUser = getUser();
15442                if (verifierUser == UserHandle.ALL) {
15443                    verifierUser = UserHandle.SYSTEM;
15444                }
15445
15446                /*
15447                 * Determine if we have any installed package verifiers. If we
15448                 * do, then we'll defer to them to verify the packages.
15449                 */
15450                final int requiredUid = mRequiredVerifierPackage == null ? -1
15451                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15452                                verifierUser.getIdentifier());
15453                final int installerUid =
15454                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15455                if (!origin.existing && requiredUid != -1
15456                        && isVerificationEnabled(
15457                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15458                    final Intent verification = new Intent(
15459                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15460                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15461                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15462                            PACKAGE_MIME_TYPE);
15463                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15464
15465                    // Query all live verifiers based on current user state
15466                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15467                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15468                            false /*allowDynamicSplits*/);
15469
15470                    if (DEBUG_VERIFY) {
15471                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15472                                + verification.toString() + " with " + pkgLite.verifiers.length
15473                                + " optional verifiers");
15474                    }
15475
15476                    final int verificationId = mPendingVerificationToken++;
15477
15478                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15479
15480                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15481                            installerPackageName);
15482
15483                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15484                            installFlags);
15485
15486                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15487                            pkgLite.packageName);
15488
15489                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15490                            pkgLite.versionCode);
15491
15492                    if (verificationInfo != null) {
15493                        if (verificationInfo.originatingUri != null) {
15494                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15495                                    verificationInfo.originatingUri);
15496                        }
15497                        if (verificationInfo.referrer != null) {
15498                            verification.putExtra(Intent.EXTRA_REFERRER,
15499                                    verificationInfo.referrer);
15500                        }
15501                        if (verificationInfo.originatingUid >= 0) {
15502                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15503                                    verificationInfo.originatingUid);
15504                        }
15505                        if (verificationInfo.installerUid >= 0) {
15506                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15507                                    verificationInfo.installerUid);
15508                        }
15509                    }
15510
15511                    final PackageVerificationState verificationState = new PackageVerificationState(
15512                            requiredUid, args);
15513
15514                    mPendingVerification.append(verificationId, verificationState);
15515
15516                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15517                            receivers, verificationState);
15518
15519                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15520                    final long idleDuration = getVerificationTimeout();
15521
15522                    /*
15523                     * If any sufficient verifiers were listed in the package
15524                     * manifest, attempt to ask them.
15525                     */
15526                    if (sufficientVerifiers != null) {
15527                        final int N = sufficientVerifiers.size();
15528                        if (N == 0) {
15529                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15530                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15531                        } else {
15532                            for (int i = 0; i < N; i++) {
15533                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15534                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15535                                        verifierComponent.getPackageName(), idleDuration,
15536                                        verifierUser.getIdentifier(), false, "package verifier");
15537
15538                                final Intent sufficientIntent = new Intent(verification);
15539                                sufficientIntent.setComponent(verifierComponent);
15540                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15541                            }
15542                        }
15543                    }
15544
15545                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15546                            mRequiredVerifierPackage, receivers);
15547                    if (ret == PackageManager.INSTALL_SUCCEEDED
15548                            && mRequiredVerifierPackage != null) {
15549                        Trace.asyncTraceBegin(
15550                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15551                        /*
15552                         * Send the intent to the required verification agent,
15553                         * but only start the verification timeout after the
15554                         * target BroadcastReceivers have run.
15555                         */
15556                        verification.setComponent(requiredVerifierComponent);
15557                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15558                                mRequiredVerifierPackage, idleDuration,
15559                                verifierUser.getIdentifier(), false, "package verifier");
15560                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15561                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15562                                new BroadcastReceiver() {
15563                                    @Override
15564                                    public void onReceive(Context context, Intent intent) {
15565                                        final Message msg = mHandler
15566                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15567                                        msg.arg1 = verificationId;
15568                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15569                                    }
15570                                }, null, 0, null, null);
15571
15572                        /*
15573                         * We don't want the copy to proceed until verification
15574                         * succeeds, so null out this field.
15575                         */
15576                        mArgs = null;
15577                    }
15578                } else {
15579                    /*
15580                     * No package verification is enabled, so immediately start
15581                     * the remote call to initiate copy using temporary file.
15582                     */
15583                    ret = args.copyApk(mContainerService, true);
15584                }
15585            }
15586
15587            mRet = ret;
15588        }
15589
15590        @Override
15591        void handleReturnCode() {
15592            // If mArgs is null, then MCS couldn't be reached. When it
15593            // reconnects, it will try again to install. At that point, this
15594            // will succeed.
15595            if (mArgs != null) {
15596                processPendingInstall(mArgs, mRet);
15597            }
15598        }
15599
15600        @Override
15601        void handleServiceError() {
15602            mArgs = createInstallArgs(this);
15603            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15604        }
15605    }
15606
15607    private InstallArgs createInstallArgs(InstallParams params) {
15608        if (params.move != null) {
15609            return new MoveInstallArgs(params);
15610        } else {
15611            return new FileInstallArgs(params);
15612        }
15613    }
15614
15615    /**
15616     * Create args that describe an existing installed package. Typically used
15617     * when cleaning up old installs, or used as a move source.
15618     */
15619    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15620            String resourcePath, String[] instructionSets) {
15621        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15622    }
15623
15624    static abstract class InstallArgs {
15625        /** @see InstallParams#origin */
15626        final OriginInfo origin;
15627        /** @see InstallParams#move */
15628        final MoveInfo move;
15629
15630        final IPackageInstallObserver2 observer;
15631        // Always refers to PackageManager flags only
15632        final int installFlags;
15633        final String installerPackageName;
15634        final String volumeUuid;
15635        final UserHandle user;
15636        final String abiOverride;
15637        final String[] installGrantPermissions;
15638        /** If non-null, drop an async trace when the install completes */
15639        final String traceMethod;
15640        final int traceCookie;
15641        final Certificate[][] certificates;
15642        final int installReason;
15643
15644        // The list of instruction sets supported by this app. This is currently
15645        // only used during the rmdex() phase to clean up resources. We can get rid of this
15646        // if we move dex files under the common app path.
15647        /* nullable */ String[] instructionSets;
15648
15649        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15650                int installFlags, String installerPackageName, String volumeUuid,
15651                UserHandle user, String[] instructionSets,
15652                String abiOverride, String[] installGrantPermissions,
15653                String traceMethod, int traceCookie, Certificate[][] certificates,
15654                int installReason) {
15655            this.origin = origin;
15656            this.move = move;
15657            this.installFlags = installFlags;
15658            this.observer = observer;
15659            this.installerPackageName = installerPackageName;
15660            this.volumeUuid = volumeUuid;
15661            this.user = user;
15662            this.instructionSets = instructionSets;
15663            this.abiOverride = abiOverride;
15664            this.installGrantPermissions = installGrantPermissions;
15665            this.traceMethod = traceMethod;
15666            this.traceCookie = traceCookie;
15667            this.certificates = certificates;
15668            this.installReason = installReason;
15669        }
15670
15671        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15672        abstract int doPreInstall(int status);
15673
15674        /**
15675         * Rename package into final resting place. All paths on the given
15676         * scanned package should be updated to reflect the rename.
15677         */
15678        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15679        abstract int doPostInstall(int status, int uid);
15680
15681        /** @see PackageSettingBase#codePathString */
15682        abstract String getCodePath();
15683        /** @see PackageSettingBase#resourcePathString */
15684        abstract String getResourcePath();
15685
15686        // Need installer lock especially for dex file removal.
15687        abstract void cleanUpResourcesLI();
15688        abstract boolean doPostDeleteLI(boolean delete);
15689
15690        /**
15691         * Called before the source arguments are copied. This is used mostly
15692         * for MoveParams when it needs to read the source file to put it in the
15693         * destination.
15694         */
15695        int doPreCopy() {
15696            return PackageManager.INSTALL_SUCCEEDED;
15697        }
15698
15699        /**
15700         * Called after the source arguments are copied. This is used mostly for
15701         * MoveParams when it needs to read the source file to put it in the
15702         * destination.
15703         */
15704        int doPostCopy(int uid) {
15705            return PackageManager.INSTALL_SUCCEEDED;
15706        }
15707
15708        protected boolean isFwdLocked() {
15709            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15710        }
15711
15712        protected boolean isExternalAsec() {
15713            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15714        }
15715
15716        protected boolean isEphemeral() {
15717            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15718        }
15719
15720        UserHandle getUser() {
15721            return user;
15722        }
15723    }
15724
15725    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15726        if (!allCodePaths.isEmpty()) {
15727            if (instructionSets == null) {
15728                throw new IllegalStateException("instructionSet == null");
15729            }
15730            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15731            for (String codePath : allCodePaths) {
15732                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15733                    try {
15734                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15735                    } catch (InstallerException ignored) {
15736                    }
15737                }
15738            }
15739        }
15740    }
15741
15742    /**
15743     * Logic to handle installation of non-ASEC applications, including copying
15744     * and renaming logic.
15745     */
15746    class FileInstallArgs extends InstallArgs {
15747        private File codeFile;
15748        private File resourceFile;
15749
15750        // Example topology:
15751        // /data/app/com.example/base.apk
15752        // /data/app/com.example/split_foo.apk
15753        // /data/app/com.example/lib/arm/libfoo.so
15754        // /data/app/com.example/lib/arm64/libfoo.so
15755        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15756
15757        /** New install */
15758        FileInstallArgs(InstallParams params) {
15759            super(params.origin, params.move, params.observer, params.installFlags,
15760                    params.installerPackageName, params.volumeUuid,
15761                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15762                    params.grantedRuntimePermissions,
15763                    params.traceMethod, params.traceCookie, params.certificates,
15764                    params.installReason);
15765            if (isFwdLocked()) {
15766                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15767            }
15768        }
15769
15770        /** Existing install */
15771        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15772            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15773                    null, null, null, 0, null /*certificates*/,
15774                    PackageManager.INSTALL_REASON_UNKNOWN);
15775            this.codeFile = (codePath != null) ? new File(codePath) : null;
15776            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15777        }
15778
15779        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15780            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15781            try {
15782                return doCopyApk(imcs, temp);
15783            } finally {
15784                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15785            }
15786        }
15787
15788        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15789            if (origin.staged) {
15790                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15791                codeFile = origin.file;
15792                resourceFile = origin.file;
15793                return PackageManager.INSTALL_SUCCEEDED;
15794            }
15795
15796            try {
15797                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15798                final File tempDir =
15799                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15800                codeFile = tempDir;
15801                resourceFile = tempDir;
15802            } catch (IOException e) {
15803                Slog.w(TAG, "Failed to create copy file: " + e);
15804                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15805            }
15806
15807            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15808                @Override
15809                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15810                    if (!FileUtils.isValidExtFilename(name)) {
15811                        throw new IllegalArgumentException("Invalid filename: " + name);
15812                    }
15813                    try {
15814                        final File file = new File(codeFile, name);
15815                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15816                                O_RDWR | O_CREAT, 0644);
15817                        Os.chmod(file.getAbsolutePath(), 0644);
15818                        return new ParcelFileDescriptor(fd);
15819                    } catch (ErrnoException e) {
15820                        throw new RemoteException("Failed to open: " + e.getMessage());
15821                    }
15822                }
15823            };
15824
15825            int ret = PackageManager.INSTALL_SUCCEEDED;
15826            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15827            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15828                Slog.e(TAG, "Failed to copy package");
15829                return ret;
15830            }
15831
15832            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15833            NativeLibraryHelper.Handle handle = null;
15834            try {
15835                handle = NativeLibraryHelper.Handle.create(codeFile);
15836                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15837                        abiOverride);
15838            } catch (IOException e) {
15839                Slog.e(TAG, "Copying native libraries failed", e);
15840                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15841            } finally {
15842                IoUtils.closeQuietly(handle);
15843            }
15844
15845            return ret;
15846        }
15847
15848        int doPreInstall(int status) {
15849            if (status != PackageManager.INSTALL_SUCCEEDED) {
15850                cleanUp();
15851            }
15852            return status;
15853        }
15854
15855        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15856            if (status != PackageManager.INSTALL_SUCCEEDED) {
15857                cleanUp();
15858                return false;
15859            }
15860
15861            final File targetDir = codeFile.getParentFile();
15862            final File beforeCodeFile = codeFile;
15863            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15864
15865            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15866            try {
15867                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15868            } catch (ErrnoException e) {
15869                Slog.w(TAG, "Failed to rename", e);
15870                return false;
15871            }
15872
15873            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15874                Slog.w(TAG, "Failed to restorecon");
15875                return false;
15876            }
15877
15878            // Reflect the rename internally
15879            codeFile = afterCodeFile;
15880            resourceFile = afterCodeFile;
15881
15882            // Reflect the rename in scanned details
15883            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15884            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15885                    afterCodeFile, pkg.baseCodePath));
15886            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15887                    afterCodeFile, pkg.splitCodePaths));
15888
15889            // Reflect the rename in app info
15890            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15891            pkg.setApplicationInfoCodePath(pkg.codePath);
15892            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15893            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15894            pkg.setApplicationInfoResourcePath(pkg.codePath);
15895            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15896            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15897
15898            return true;
15899        }
15900
15901        int doPostInstall(int status, int uid) {
15902            if (status != PackageManager.INSTALL_SUCCEEDED) {
15903                cleanUp();
15904            }
15905            return status;
15906        }
15907
15908        @Override
15909        String getCodePath() {
15910            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15911        }
15912
15913        @Override
15914        String getResourcePath() {
15915            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15916        }
15917
15918        private boolean cleanUp() {
15919            if (codeFile == null || !codeFile.exists()) {
15920                return false;
15921            }
15922
15923            removeCodePathLI(codeFile);
15924
15925            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15926                resourceFile.delete();
15927            }
15928
15929            return true;
15930        }
15931
15932        void cleanUpResourcesLI() {
15933            // Try enumerating all code paths before deleting
15934            List<String> allCodePaths = Collections.EMPTY_LIST;
15935            if (codeFile != null && codeFile.exists()) {
15936                try {
15937                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15938                    allCodePaths = pkg.getAllCodePaths();
15939                } catch (PackageParserException e) {
15940                    // Ignored; we tried our best
15941                }
15942            }
15943
15944            cleanUp();
15945            removeDexFiles(allCodePaths, instructionSets);
15946        }
15947
15948        boolean doPostDeleteLI(boolean delete) {
15949            // XXX err, shouldn't we respect the delete flag?
15950            cleanUpResourcesLI();
15951            return true;
15952        }
15953    }
15954
15955    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15956            PackageManagerException {
15957        if (copyRet < 0) {
15958            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15959                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15960                throw new PackageManagerException(copyRet, message);
15961            }
15962        }
15963    }
15964
15965    /**
15966     * Extract the StorageManagerService "container ID" from the full code path of an
15967     * .apk.
15968     */
15969    static String cidFromCodePath(String fullCodePath) {
15970        int eidx = fullCodePath.lastIndexOf("/");
15971        String subStr1 = fullCodePath.substring(0, eidx);
15972        int sidx = subStr1.lastIndexOf("/");
15973        return subStr1.substring(sidx+1, eidx);
15974    }
15975
15976    /**
15977     * Logic to handle movement of existing installed applications.
15978     */
15979    class MoveInstallArgs extends InstallArgs {
15980        private File codeFile;
15981        private File resourceFile;
15982
15983        /** New install */
15984        MoveInstallArgs(InstallParams params) {
15985            super(params.origin, params.move, params.observer, params.installFlags,
15986                    params.installerPackageName, params.volumeUuid,
15987                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15988                    params.grantedRuntimePermissions,
15989                    params.traceMethod, params.traceCookie, params.certificates,
15990                    params.installReason);
15991        }
15992
15993        int copyApk(IMediaContainerService imcs, boolean temp) {
15994            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15995                    + move.fromUuid + " to " + move.toUuid);
15996            synchronized (mInstaller) {
15997                try {
15998                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15999                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16000                } catch (InstallerException e) {
16001                    Slog.w(TAG, "Failed to move app", e);
16002                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16003                }
16004            }
16005
16006            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16007            resourceFile = codeFile;
16008            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16009
16010            return PackageManager.INSTALL_SUCCEEDED;
16011        }
16012
16013        int doPreInstall(int status) {
16014            if (status != PackageManager.INSTALL_SUCCEEDED) {
16015                cleanUp(move.toUuid);
16016            }
16017            return status;
16018        }
16019
16020        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16021            if (status != PackageManager.INSTALL_SUCCEEDED) {
16022                cleanUp(move.toUuid);
16023                return false;
16024            }
16025
16026            // Reflect the move in app info
16027            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16028            pkg.setApplicationInfoCodePath(pkg.codePath);
16029            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16030            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16031            pkg.setApplicationInfoResourcePath(pkg.codePath);
16032            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16033            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16034
16035            return true;
16036        }
16037
16038        int doPostInstall(int status, int uid) {
16039            if (status == PackageManager.INSTALL_SUCCEEDED) {
16040                cleanUp(move.fromUuid);
16041            } else {
16042                cleanUp(move.toUuid);
16043            }
16044            return status;
16045        }
16046
16047        @Override
16048        String getCodePath() {
16049            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16050        }
16051
16052        @Override
16053        String getResourcePath() {
16054            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16055        }
16056
16057        private boolean cleanUp(String volumeUuid) {
16058            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16059                    move.dataAppName);
16060            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16061            final int[] userIds = sUserManager.getUserIds();
16062            synchronized (mInstallLock) {
16063                // Clean up both app data and code
16064                // All package moves are frozen until finished
16065                for (int userId : userIds) {
16066                    try {
16067                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16068                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16069                    } catch (InstallerException e) {
16070                        Slog.w(TAG, String.valueOf(e));
16071                    }
16072                }
16073                removeCodePathLI(codeFile);
16074            }
16075            return true;
16076        }
16077
16078        void cleanUpResourcesLI() {
16079            throw new UnsupportedOperationException();
16080        }
16081
16082        boolean doPostDeleteLI(boolean delete) {
16083            throw new UnsupportedOperationException();
16084        }
16085    }
16086
16087    static String getAsecPackageName(String packageCid) {
16088        int idx = packageCid.lastIndexOf("-");
16089        if (idx == -1) {
16090            return packageCid;
16091        }
16092        return packageCid.substring(0, idx);
16093    }
16094
16095    // Utility method used to create code paths based on package name and available index.
16096    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16097        String idxStr = "";
16098        int idx = 1;
16099        // Fall back to default value of idx=1 if prefix is not
16100        // part of oldCodePath
16101        if (oldCodePath != null) {
16102            String subStr = oldCodePath;
16103            // Drop the suffix right away
16104            if (suffix != null && subStr.endsWith(suffix)) {
16105                subStr = subStr.substring(0, subStr.length() - suffix.length());
16106            }
16107            // If oldCodePath already contains prefix find out the
16108            // ending index to either increment or decrement.
16109            int sidx = subStr.lastIndexOf(prefix);
16110            if (sidx != -1) {
16111                subStr = subStr.substring(sidx + prefix.length());
16112                if (subStr != null) {
16113                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16114                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16115                    }
16116                    try {
16117                        idx = Integer.parseInt(subStr);
16118                        if (idx <= 1) {
16119                            idx++;
16120                        } else {
16121                            idx--;
16122                        }
16123                    } catch(NumberFormatException e) {
16124                    }
16125                }
16126            }
16127        }
16128        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16129        return prefix + idxStr;
16130    }
16131
16132    private File getNextCodePath(File targetDir, String packageName) {
16133        File result;
16134        SecureRandom random = new SecureRandom();
16135        byte[] bytes = new byte[16];
16136        do {
16137            random.nextBytes(bytes);
16138            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16139            result = new File(targetDir, packageName + "-" + suffix);
16140        } while (result.exists());
16141        return result;
16142    }
16143
16144    // Utility method that returns the relative package path with respect
16145    // to the installation directory. Like say for /data/data/com.test-1.apk
16146    // string com.test-1 is returned.
16147    static String deriveCodePathName(String codePath) {
16148        if (codePath == null) {
16149            return null;
16150        }
16151        final File codeFile = new File(codePath);
16152        final String name = codeFile.getName();
16153        if (codeFile.isDirectory()) {
16154            return name;
16155        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16156            final int lastDot = name.lastIndexOf('.');
16157            return name.substring(0, lastDot);
16158        } else {
16159            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16160            return null;
16161        }
16162    }
16163
16164    static class PackageInstalledInfo {
16165        String name;
16166        int uid;
16167        // The set of users that originally had this package installed.
16168        int[] origUsers;
16169        // The set of users that now have this package installed.
16170        int[] newUsers;
16171        PackageParser.Package pkg;
16172        int returnCode;
16173        String returnMsg;
16174        String installerPackageName;
16175        PackageRemovedInfo removedInfo;
16176        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16177
16178        public void setError(int code, String msg) {
16179            setReturnCode(code);
16180            setReturnMessage(msg);
16181            Slog.w(TAG, msg);
16182        }
16183
16184        public void setError(String msg, PackageParserException e) {
16185            setReturnCode(e.error);
16186            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16187            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16188            for (int i = 0; i < childCount; i++) {
16189                addedChildPackages.valueAt(i).setError(msg, e);
16190            }
16191            Slog.w(TAG, msg, e);
16192        }
16193
16194        public void setError(String msg, PackageManagerException e) {
16195            returnCode = e.error;
16196            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16197            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16198            for (int i = 0; i < childCount; i++) {
16199                addedChildPackages.valueAt(i).setError(msg, e);
16200            }
16201            Slog.w(TAG, msg, e);
16202        }
16203
16204        public void setReturnCode(int returnCode) {
16205            this.returnCode = returnCode;
16206            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16207            for (int i = 0; i < childCount; i++) {
16208                addedChildPackages.valueAt(i).returnCode = returnCode;
16209            }
16210        }
16211
16212        private void setReturnMessage(String returnMsg) {
16213            this.returnMsg = returnMsg;
16214            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16215            for (int i = 0; i < childCount; i++) {
16216                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16217            }
16218        }
16219
16220        // In some error cases we want to convey more info back to the observer
16221        String origPackage;
16222        String origPermission;
16223    }
16224
16225    /*
16226     * Install a non-existing package.
16227     */
16228    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16229            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16230            PackageInstalledInfo res, int installReason) {
16231        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16232
16233        // Remember this for later, in case we need to rollback this install
16234        String pkgName = pkg.packageName;
16235
16236        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16237
16238        synchronized(mPackages) {
16239            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16240            if (renamedPackage != null) {
16241                // A package with the same name is already installed, though
16242                // it has been renamed to an older name.  The package we
16243                // are trying to install should be installed as an update to
16244                // the existing one, but that has not been requested, so bail.
16245                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16246                        + " without first uninstalling package running as "
16247                        + renamedPackage);
16248                return;
16249            }
16250            if (mPackages.containsKey(pkgName)) {
16251                // Don't allow installation over an existing package with the same name.
16252                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16253                        + " without first uninstalling.");
16254                return;
16255            }
16256        }
16257
16258        try {
16259            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16260                    System.currentTimeMillis(), user);
16261
16262            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16263
16264            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16265                prepareAppDataAfterInstallLIF(newPackage);
16266
16267            } else {
16268                // Remove package from internal structures, but keep around any
16269                // data that might have already existed
16270                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16271                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16272            }
16273        } catch (PackageManagerException e) {
16274            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16275        }
16276
16277        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16278    }
16279
16280    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16281        // Can't rotate keys during boot or if sharedUser.
16282        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16283                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16284            return false;
16285        }
16286        // app is using upgradeKeySets; make sure all are valid
16287        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16288        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16289        for (int i = 0; i < upgradeKeySets.length; i++) {
16290            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16291                Slog.wtf(TAG, "Package "
16292                         + (oldPs.name != null ? oldPs.name : "<null>")
16293                         + " contains upgrade-key-set reference to unknown key-set: "
16294                         + upgradeKeySets[i]
16295                         + " reverting to signatures check.");
16296                return false;
16297            }
16298        }
16299        return true;
16300    }
16301
16302    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16303        // Upgrade keysets are being used.  Determine if new package has a superset of the
16304        // required keys.
16305        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16306        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16307        for (int i = 0; i < upgradeKeySets.length; i++) {
16308            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16309            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16310                return true;
16311            }
16312        }
16313        return false;
16314    }
16315
16316    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16317        try (DigestInputStream digestStream =
16318                new DigestInputStream(new FileInputStream(file), digest)) {
16319            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16320        }
16321    }
16322
16323    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16324            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16325            int installReason) {
16326        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16327
16328        final PackageParser.Package oldPackage;
16329        final PackageSetting ps;
16330        final String pkgName = pkg.packageName;
16331        final int[] allUsers;
16332        final int[] installedUsers;
16333
16334        synchronized(mPackages) {
16335            oldPackage = mPackages.get(pkgName);
16336            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16337
16338            // don't allow upgrade to target a release SDK from a pre-release SDK
16339            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16340                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16341            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16342                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16343            if (oldTargetsPreRelease
16344                    && !newTargetsPreRelease
16345                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16346                Slog.w(TAG, "Can't install package targeting released sdk");
16347                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16348                return;
16349            }
16350
16351            ps = mSettings.mPackages.get(pkgName);
16352
16353            // verify signatures are valid
16354            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16355                if (!checkUpgradeKeySetLP(ps, pkg)) {
16356                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16357                            "New package not signed by keys specified by upgrade-keysets: "
16358                                    + pkgName);
16359                    return;
16360                }
16361            } else {
16362                // default to original signature matching
16363                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16364                        != PackageManager.SIGNATURE_MATCH) {
16365                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16366                            "New package has a different signature: " + pkgName);
16367                    return;
16368                }
16369            }
16370
16371            // don't allow a system upgrade unless the upgrade hash matches
16372            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16373                byte[] digestBytes = null;
16374                try {
16375                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16376                    updateDigest(digest, new File(pkg.baseCodePath));
16377                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16378                        for (String path : pkg.splitCodePaths) {
16379                            updateDigest(digest, new File(path));
16380                        }
16381                    }
16382                    digestBytes = digest.digest();
16383                } catch (NoSuchAlgorithmException | IOException e) {
16384                    res.setError(INSTALL_FAILED_INVALID_APK,
16385                            "Could not compute hash: " + pkgName);
16386                    return;
16387                }
16388                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16389                    res.setError(INSTALL_FAILED_INVALID_APK,
16390                            "New package fails restrict-update check: " + pkgName);
16391                    return;
16392                }
16393                // retain upgrade restriction
16394                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16395            }
16396
16397            // Check for shared user id changes
16398            String invalidPackageName =
16399                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16400            if (invalidPackageName != null) {
16401                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16402                        "Package " + invalidPackageName + " tried to change user "
16403                                + oldPackage.mSharedUserId);
16404                return;
16405            }
16406
16407            // In case of rollback, remember per-user/profile install state
16408            allUsers = sUserManager.getUserIds();
16409            installedUsers = ps.queryInstalledUsers(allUsers, true);
16410
16411            // don't allow an upgrade from full to ephemeral
16412            if (isInstantApp) {
16413                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16414                    for (int currentUser : allUsers) {
16415                        if (!ps.getInstantApp(currentUser)) {
16416                            // can't downgrade from full to instant
16417                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16418                                    + " for user: " + currentUser);
16419                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16420                            return;
16421                        }
16422                    }
16423                } else if (!ps.getInstantApp(user.getIdentifier())) {
16424                    // can't downgrade from full to instant
16425                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16426                            + " for user: " + user.getIdentifier());
16427                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16428                    return;
16429                }
16430            }
16431        }
16432
16433        // Update what is removed
16434        res.removedInfo = new PackageRemovedInfo(this);
16435        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16436        res.removedInfo.removedPackage = oldPackage.packageName;
16437        res.removedInfo.installerPackageName = ps.installerPackageName;
16438        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16439        res.removedInfo.isUpdate = true;
16440        res.removedInfo.origUsers = installedUsers;
16441        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16442        for (int i = 0; i < installedUsers.length; i++) {
16443            final int userId = installedUsers[i];
16444            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16445        }
16446
16447        final int childCount = (oldPackage.childPackages != null)
16448                ? oldPackage.childPackages.size() : 0;
16449        for (int i = 0; i < childCount; i++) {
16450            boolean childPackageUpdated = false;
16451            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16452            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16453            if (res.addedChildPackages != null) {
16454                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16455                if (childRes != null) {
16456                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16457                    childRes.removedInfo.removedPackage = childPkg.packageName;
16458                    if (childPs != null) {
16459                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16460                    }
16461                    childRes.removedInfo.isUpdate = true;
16462                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16463                    childPackageUpdated = true;
16464                }
16465            }
16466            if (!childPackageUpdated) {
16467                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16468                childRemovedRes.removedPackage = childPkg.packageName;
16469                if (childPs != null) {
16470                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16471                }
16472                childRemovedRes.isUpdate = false;
16473                childRemovedRes.dataRemoved = true;
16474                synchronized (mPackages) {
16475                    if (childPs != null) {
16476                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16477                    }
16478                }
16479                if (res.removedInfo.removedChildPackages == null) {
16480                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16481                }
16482                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16483            }
16484        }
16485
16486        boolean sysPkg = (isSystemApp(oldPackage));
16487        if (sysPkg) {
16488            // Set the system/privileged/oem flags as needed
16489            final boolean privileged =
16490                    (oldPackage.applicationInfo.privateFlags
16491                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16492            final boolean oem =
16493                    (oldPackage.applicationInfo.privateFlags
16494                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16495            final int systemPolicyFlags = policyFlags
16496                    | PackageParser.PARSE_IS_SYSTEM
16497                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16498                    | (oem ? PARSE_IS_OEM : 0);
16499
16500            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16501                    user, allUsers, installerPackageName, res, installReason);
16502        } else {
16503            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16504                    user, allUsers, installerPackageName, res, installReason);
16505        }
16506    }
16507
16508    @Override
16509    public List<String> getPreviousCodePaths(String packageName) {
16510        final int callingUid = Binder.getCallingUid();
16511        final List<String> result = new ArrayList<>();
16512        if (getInstantAppPackageName(callingUid) != null) {
16513            return result;
16514        }
16515        final PackageSetting ps = mSettings.mPackages.get(packageName);
16516        if (ps != null
16517                && ps.oldCodePaths != null
16518                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16519            result.addAll(ps.oldCodePaths);
16520        }
16521        return result;
16522    }
16523
16524    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16525            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16526            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16527            int installReason) {
16528        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16529                + deletedPackage);
16530
16531        String pkgName = deletedPackage.packageName;
16532        boolean deletedPkg = true;
16533        boolean addedPkg = false;
16534        boolean updatedSettings = false;
16535        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16536        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16537                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16538
16539        final long origUpdateTime = (pkg.mExtras != null)
16540                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16541
16542        // First delete the existing package while retaining the data directory
16543        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16544                res.removedInfo, true, pkg)) {
16545            // If the existing package wasn't successfully deleted
16546            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16547            deletedPkg = false;
16548        } else {
16549            // Successfully deleted the old package; proceed with replace.
16550
16551            // If deleted package lived in a container, give users a chance to
16552            // relinquish resources before killing.
16553            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16554                if (DEBUG_INSTALL) {
16555                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16556                }
16557                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16558                final ArrayList<String> pkgList = new ArrayList<String>(1);
16559                pkgList.add(deletedPackage.applicationInfo.packageName);
16560                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16561            }
16562
16563            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16564                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16565            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16566
16567            try {
16568                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16569                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16570                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16571                        installReason);
16572
16573                // Update the in-memory copy of the previous code paths.
16574                PackageSetting ps = mSettings.mPackages.get(pkgName);
16575                if (!killApp) {
16576                    if (ps.oldCodePaths == null) {
16577                        ps.oldCodePaths = new ArraySet<>();
16578                    }
16579                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16580                    if (deletedPackage.splitCodePaths != null) {
16581                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16582                    }
16583                } else {
16584                    ps.oldCodePaths = null;
16585                }
16586                if (ps.childPackageNames != null) {
16587                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16588                        final String childPkgName = ps.childPackageNames.get(i);
16589                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16590                        childPs.oldCodePaths = ps.oldCodePaths;
16591                    }
16592                }
16593                // set instant app status, but, only if it's explicitly specified
16594                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16595                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16596                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16597                prepareAppDataAfterInstallLIF(newPackage);
16598                addedPkg = true;
16599                mDexManager.notifyPackageUpdated(newPackage.packageName,
16600                        newPackage.baseCodePath, newPackage.splitCodePaths);
16601            } catch (PackageManagerException e) {
16602                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16603            }
16604        }
16605
16606        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16607            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16608
16609            // Revert all internal state mutations and added folders for the failed install
16610            if (addedPkg) {
16611                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16612                        res.removedInfo, true, null);
16613            }
16614
16615            // Restore the old package
16616            if (deletedPkg) {
16617                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16618                File restoreFile = new File(deletedPackage.codePath);
16619                // Parse old package
16620                boolean oldExternal = isExternal(deletedPackage);
16621                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16622                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16623                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16624                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16625                try {
16626                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16627                            null);
16628                } catch (PackageManagerException e) {
16629                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16630                            + e.getMessage());
16631                    return;
16632                }
16633
16634                synchronized (mPackages) {
16635                    // Ensure the installer package name up to date
16636                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16637
16638                    // Update permissions for restored package
16639                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16640
16641                    mSettings.writeLPr();
16642                }
16643
16644                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16645            }
16646        } else {
16647            synchronized (mPackages) {
16648                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16649                if (ps != null) {
16650                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16651                    if (res.removedInfo.removedChildPackages != null) {
16652                        final int childCount = res.removedInfo.removedChildPackages.size();
16653                        // Iterate in reverse as we may modify the collection
16654                        for (int i = childCount - 1; i >= 0; i--) {
16655                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16656                            if (res.addedChildPackages.containsKey(childPackageName)) {
16657                                res.removedInfo.removedChildPackages.removeAt(i);
16658                            } else {
16659                                PackageRemovedInfo childInfo = res.removedInfo
16660                                        .removedChildPackages.valueAt(i);
16661                                childInfo.removedForAllUsers = mPackages.get(
16662                                        childInfo.removedPackage) == null;
16663                            }
16664                        }
16665                    }
16666                }
16667            }
16668        }
16669    }
16670
16671    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16672            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16673            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16674            int installReason) {
16675        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16676                + ", old=" + deletedPackage);
16677
16678        final boolean disabledSystem;
16679
16680        // Remove existing system package
16681        removePackageLI(deletedPackage, true);
16682
16683        synchronized (mPackages) {
16684            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16685        }
16686        if (!disabledSystem) {
16687            // We didn't need to disable the .apk as a current system package,
16688            // which means we are replacing another update that is already
16689            // installed.  We need to make sure to delete the older one's .apk.
16690            res.removedInfo.args = createInstallArgsForExisting(0,
16691                    deletedPackage.applicationInfo.getCodePath(),
16692                    deletedPackage.applicationInfo.getResourcePath(),
16693                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16694        } else {
16695            res.removedInfo.args = null;
16696        }
16697
16698        // Successfully disabled the old package. Now proceed with re-installation
16699        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16700                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16701        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16702
16703        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16704        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16705                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16706
16707        PackageParser.Package newPackage = null;
16708        try {
16709            // Add the package to the internal data structures
16710            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16711
16712            // Set the update and install times
16713            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16714            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16715                    System.currentTimeMillis());
16716
16717            // Update the package dynamic state if succeeded
16718            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16719                // Now that the install succeeded make sure we remove data
16720                // directories for any child package the update removed.
16721                final int deletedChildCount = (deletedPackage.childPackages != null)
16722                        ? deletedPackage.childPackages.size() : 0;
16723                final int newChildCount = (newPackage.childPackages != null)
16724                        ? newPackage.childPackages.size() : 0;
16725                for (int i = 0; i < deletedChildCount; i++) {
16726                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16727                    boolean childPackageDeleted = true;
16728                    for (int j = 0; j < newChildCount; j++) {
16729                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16730                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16731                            childPackageDeleted = false;
16732                            break;
16733                        }
16734                    }
16735                    if (childPackageDeleted) {
16736                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16737                                deletedChildPkg.packageName);
16738                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16739                            PackageRemovedInfo removedChildRes = res.removedInfo
16740                                    .removedChildPackages.get(deletedChildPkg.packageName);
16741                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16742                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16743                        }
16744                    }
16745                }
16746
16747                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16748                        installReason);
16749                prepareAppDataAfterInstallLIF(newPackage);
16750
16751                mDexManager.notifyPackageUpdated(newPackage.packageName,
16752                            newPackage.baseCodePath, newPackage.splitCodePaths);
16753            }
16754        } catch (PackageManagerException e) {
16755            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16756            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16757        }
16758
16759        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16760            // Re installation failed. Restore old information
16761            // Remove new pkg information
16762            if (newPackage != null) {
16763                removeInstalledPackageLI(newPackage, true);
16764            }
16765            // Add back the old system package
16766            try {
16767                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16768            } catch (PackageManagerException e) {
16769                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16770            }
16771
16772            synchronized (mPackages) {
16773                if (disabledSystem) {
16774                    enableSystemPackageLPw(deletedPackage);
16775                }
16776
16777                // Ensure the installer package name up to date
16778                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16779
16780                // Update permissions for restored package
16781                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16782
16783                mSettings.writeLPr();
16784            }
16785
16786            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16787                    + " after failed upgrade");
16788        }
16789    }
16790
16791    /**
16792     * Checks whether the parent or any of the child packages have a change shared
16793     * user. For a package to be a valid update the shred users of the parent and
16794     * the children should match. We may later support changing child shared users.
16795     * @param oldPkg The updated package.
16796     * @param newPkg The update package.
16797     * @return The shared user that change between the versions.
16798     */
16799    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16800            PackageParser.Package newPkg) {
16801        // Check parent shared user
16802        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16803            return newPkg.packageName;
16804        }
16805        // Check child shared users
16806        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16807        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16808        for (int i = 0; i < newChildCount; i++) {
16809            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16810            // If this child was present, did it have the same shared user?
16811            for (int j = 0; j < oldChildCount; j++) {
16812                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16813                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16814                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16815                    return newChildPkg.packageName;
16816                }
16817            }
16818        }
16819        return null;
16820    }
16821
16822    private void removeNativeBinariesLI(PackageSetting ps) {
16823        // Remove the lib path for the parent package
16824        if (ps != null) {
16825            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16826            // Remove the lib path for the child packages
16827            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16828            for (int i = 0; i < childCount; i++) {
16829                PackageSetting childPs = null;
16830                synchronized (mPackages) {
16831                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16832                }
16833                if (childPs != null) {
16834                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16835                            .legacyNativeLibraryPathString);
16836                }
16837            }
16838        }
16839    }
16840
16841    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16842        // Enable the parent package
16843        mSettings.enableSystemPackageLPw(pkg.packageName);
16844        // Enable the child packages
16845        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16846        for (int i = 0; i < childCount; i++) {
16847            PackageParser.Package childPkg = pkg.childPackages.get(i);
16848            mSettings.enableSystemPackageLPw(childPkg.packageName);
16849        }
16850    }
16851
16852    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16853            PackageParser.Package newPkg) {
16854        // Disable the parent package (parent always replaced)
16855        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16856        // Disable the child packages
16857        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16858        for (int i = 0; i < childCount; i++) {
16859            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16860            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16861            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16862        }
16863        return disabled;
16864    }
16865
16866    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16867            String installerPackageName) {
16868        // Enable the parent package
16869        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16870        // Enable the child packages
16871        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16872        for (int i = 0; i < childCount; i++) {
16873            PackageParser.Package childPkg = pkg.childPackages.get(i);
16874            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16875        }
16876    }
16877
16878    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16879            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16880        // Update the parent package setting
16881        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16882                res, user, installReason);
16883        // Update the child packages setting
16884        final int childCount = (newPackage.childPackages != null)
16885                ? newPackage.childPackages.size() : 0;
16886        for (int i = 0; i < childCount; i++) {
16887            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16888            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16889            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16890                    childRes.origUsers, childRes, user, installReason);
16891        }
16892    }
16893
16894    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16895            String installerPackageName, int[] allUsers, int[] installedForUsers,
16896            PackageInstalledInfo res, UserHandle user, int installReason) {
16897        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16898
16899        String pkgName = newPackage.packageName;
16900        synchronized (mPackages) {
16901            //write settings. the installStatus will be incomplete at this stage.
16902            //note that the new package setting would have already been
16903            //added to mPackages. It hasn't been persisted yet.
16904            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16905            // TODO: Remove this write? It's also written at the end of this method
16906            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16907            mSettings.writeLPr();
16908            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16909        }
16910
16911        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16912        synchronized (mPackages) {
16913            updatePermissionsLPw(newPackage.packageName, newPackage,
16914                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16915                            ? UPDATE_PERMISSIONS_ALL : 0));
16916            // For system-bundled packages, we assume that installing an upgraded version
16917            // of the package implies that the user actually wants to run that new code,
16918            // so we enable the package.
16919            PackageSetting ps = mSettings.mPackages.get(pkgName);
16920            final int userId = user.getIdentifier();
16921            if (ps != null) {
16922                if (isSystemApp(newPackage)) {
16923                    if (DEBUG_INSTALL) {
16924                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16925                    }
16926                    // Enable system package for requested users
16927                    if (res.origUsers != null) {
16928                        for (int origUserId : res.origUsers) {
16929                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16930                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16931                                        origUserId, installerPackageName);
16932                            }
16933                        }
16934                    }
16935                    // Also convey the prior install/uninstall state
16936                    if (allUsers != null && installedForUsers != null) {
16937                        for (int currentUserId : allUsers) {
16938                            final boolean installed = ArrayUtils.contains(
16939                                    installedForUsers, currentUserId);
16940                            if (DEBUG_INSTALL) {
16941                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16942                            }
16943                            ps.setInstalled(installed, currentUserId);
16944                        }
16945                        // these install state changes will be persisted in the
16946                        // upcoming call to mSettings.writeLPr().
16947                    }
16948                }
16949                // It's implied that when a user requests installation, they want the app to be
16950                // installed and enabled.
16951                if (userId != UserHandle.USER_ALL) {
16952                    ps.setInstalled(true, userId);
16953                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16954                }
16955
16956                // When replacing an existing package, preserve the original install reason for all
16957                // users that had the package installed before.
16958                final Set<Integer> previousUserIds = new ArraySet<>();
16959                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16960                    final int installReasonCount = res.removedInfo.installReasons.size();
16961                    for (int i = 0; i < installReasonCount; i++) {
16962                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16963                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16964                        ps.setInstallReason(previousInstallReason, previousUserId);
16965                        previousUserIds.add(previousUserId);
16966                    }
16967                }
16968
16969                // Set install reason for users that are having the package newly installed.
16970                if (userId == UserHandle.USER_ALL) {
16971                    for (int currentUserId : sUserManager.getUserIds()) {
16972                        if (!previousUserIds.contains(currentUserId)) {
16973                            ps.setInstallReason(installReason, currentUserId);
16974                        }
16975                    }
16976                } else if (!previousUserIds.contains(userId)) {
16977                    ps.setInstallReason(installReason, userId);
16978                }
16979                mSettings.writeKernelMappingLPr(ps);
16980            }
16981            res.name = pkgName;
16982            res.uid = newPackage.applicationInfo.uid;
16983            res.pkg = newPackage;
16984            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16985            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16986            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16987            //to update install status
16988            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16989            mSettings.writeLPr();
16990            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16991        }
16992
16993        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16994    }
16995
16996    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16997        try {
16998            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16999            installPackageLI(args, res);
17000        } finally {
17001            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17002        }
17003    }
17004
17005    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17006        final int installFlags = args.installFlags;
17007        final String installerPackageName = args.installerPackageName;
17008        final String volumeUuid = args.volumeUuid;
17009        final File tmpPackageFile = new File(args.getCodePath());
17010        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17011        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17012                || (args.volumeUuid != null));
17013        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17014        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17015        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17016        final boolean virtualPreload =
17017                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17018        boolean replace = false;
17019        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17020        if (args.move != null) {
17021            // moving a complete application; perform an initial scan on the new install location
17022            scanFlags |= SCAN_INITIAL;
17023        }
17024        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17025            scanFlags |= SCAN_DONT_KILL_APP;
17026        }
17027        if (instantApp) {
17028            scanFlags |= SCAN_AS_INSTANT_APP;
17029        }
17030        if (fullApp) {
17031            scanFlags |= SCAN_AS_FULL_APP;
17032        }
17033        if (virtualPreload) {
17034            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17035        }
17036
17037        // Result object to be returned
17038        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17039        res.installerPackageName = installerPackageName;
17040
17041        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17042
17043        // Sanity check
17044        if (instantApp && (forwardLocked || onExternal)) {
17045            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17046                    + " external=" + onExternal);
17047            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17048            return;
17049        }
17050
17051        // Retrieve PackageSettings and parse package
17052        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17053                | PackageParser.PARSE_ENFORCE_CODE
17054                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17055                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17056                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17057                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17058        PackageParser pp = new PackageParser();
17059        pp.setSeparateProcesses(mSeparateProcesses);
17060        pp.setDisplayMetrics(mMetrics);
17061        pp.setCallback(mPackageParserCallback);
17062
17063        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17064        final PackageParser.Package pkg;
17065        try {
17066            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17067        } catch (PackageParserException e) {
17068            res.setError("Failed parse during installPackageLI", e);
17069            return;
17070        } finally {
17071            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17072        }
17073
17074        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17075        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17076            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17077            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17078                    "Instant app package must target O");
17079            return;
17080        }
17081        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17082            Slog.w(TAG, "Instant app package " + pkg.packageName
17083                    + " does not target targetSandboxVersion 2");
17084            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17085                    "Instant app package must use targetSanboxVersion 2");
17086            return;
17087        }
17088
17089        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17090            // Static shared libraries have synthetic package names
17091            renameStaticSharedLibraryPackage(pkg);
17092
17093            // No static shared libs on external storage
17094            if (onExternal) {
17095                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17096                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17097                        "Packages declaring static-shared libs cannot be updated");
17098                return;
17099            }
17100        }
17101
17102        // If we are installing a clustered package add results for the children
17103        if (pkg.childPackages != null) {
17104            synchronized (mPackages) {
17105                final int childCount = pkg.childPackages.size();
17106                for (int i = 0; i < childCount; i++) {
17107                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17108                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17109                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17110                    childRes.pkg = childPkg;
17111                    childRes.name = childPkg.packageName;
17112                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17113                    if (childPs != null) {
17114                        childRes.origUsers = childPs.queryInstalledUsers(
17115                                sUserManager.getUserIds(), true);
17116                    }
17117                    if ((mPackages.containsKey(childPkg.packageName))) {
17118                        childRes.removedInfo = new PackageRemovedInfo(this);
17119                        childRes.removedInfo.removedPackage = childPkg.packageName;
17120                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17121                    }
17122                    if (res.addedChildPackages == null) {
17123                        res.addedChildPackages = new ArrayMap<>();
17124                    }
17125                    res.addedChildPackages.put(childPkg.packageName, childRes);
17126                }
17127            }
17128        }
17129
17130        // If package doesn't declare API override, mark that we have an install
17131        // time CPU ABI override.
17132        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17133            pkg.cpuAbiOverride = args.abiOverride;
17134        }
17135
17136        String pkgName = res.name = pkg.packageName;
17137        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17138            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17139                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17140                return;
17141            }
17142        }
17143
17144        try {
17145            // either use what we've been given or parse directly from the APK
17146            if (args.certificates != null) {
17147                try {
17148                    PackageParser.populateCertificates(pkg, args.certificates);
17149                } catch (PackageParserException e) {
17150                    // there was something wrong with the certificates we were given;
17151                    // try to pull them from the APK
17152                    PackageParser.collectCertificates(pkg, parseFlags);
17153                }
17154            } else {
17155                PackageParser.collectCertificates(pkg, parseFlags);
17156            }
17157        } catch (PackageParserException e) {
17158            res.setError("Failed collect during installPackageLI", e);
17159            return;
17160        }
17161
17162        // Get rid of all references to package scan path via parser.
17163        pp = null;
17164        String oldCodePath = null;
17165        boolean systemApp = false;
17166        synchronized (mPackages) {
17167            // Check if installing already existing package
17168            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17169                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17170                if (pkg.mOriginalPackages != null
17171                        && pkg.mOriginalPackages.contains(oldName)
17172                        && mPackages.containsKey(oldName)) {
17173                    // This package is derived from an original package,
17174                    // and this device has been updating from that original
17175                    // name.  We must continue using the original name, so
17176                    // rename the new package here.
17177                    pkg.setPackageName(oldName);
17178                    pkgName = pkg.packageName;
17179                    replace = true;
17180                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17181                            + oldName + " pkgName=" + pkgName);
17182                } else if (mPackages.containsKey(pkgName)) {
17183                    // This package, under its official name, already exists
17184                    // on the device; we should replace it.
17185                    replace = true;
17186                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17187                }
17188
17189                // Child packages are installed through the parent package
17190                if (pkg.parentPackage != null) {
17191                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17192                            "Package " + pkg.packageName + " is child of package "
17193                                    + pkg.parentPackage.parentPackage + ". Child packages "
17194                                    + "can be updated only through the parent package.");
17195                    return;
17196                }
17197
17198                if (replace) {
17199                    // Prevent apps opting out from runtime permissions
17200                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17201                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17202                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17203                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17204                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17205                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17206                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17207                                        + " doesn't support runtime permissions but the old"
17208                                        + " target SDK " + oldTargetSdk + " does.");
17209                        return;
17210                    }
17211                    // Prevent apps from downgrading their targetSandbox.
17212                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17213                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17214                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17215                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17216                                "Package " + pkg.packageName + " new target sandbox "
17217                                + newTargetSandbox + " is incompatible with the previous value of"
17218                                + oldTargetSandbox + ".");
17219                        return;
17220                    }
17221
17222                    // Prevent installing of child packages
17223                    if (oldPackage.parentPackage != null) {
17224                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17225                                "Package " + pkg.packageName + " is child of package "
17226                                        + oldPackage.parentPackage + ". Child packages "
17227                                        + "can be updated only through the parent package.");
17228                        return;
17229                    }
17230                }
17231            }
17232
17233            PackageSetting ps = mSettings.mPackages.get(pkgName);
17234            if (ps != null) {
17235                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17236
17237                // Static shared libs have same package with different versions where
17238                // we internally use a synthetic package name to allow multiple versions
17239                // of the same package, therefore we need to compare signatures against
17240                // the package setting for the latest library version.
17241                PackageSetting signatureCheckPs = ps;
17242                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17243                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17244                    if (libraryEntry != null) {
17245                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17246                    }
17247                }
17248
17249                // Quick sanity check that we're signed correctly if updating;
17250                // we'll check this again later when scanning, but we want to
17251                // bail early here before tripping over redefined permissions.
17252                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17253                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17254                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17255                                + pkg.packageName + " upgrade keys do not match the "
17256                                + "previously installed version");
17257                        return;
17258                    }
17259                } else {
17260                    try {
17261                        verifySignaturesLP(signatureCheckPs, pkg);
17262                    } catch (PackageManagerException e) {
17263                        res.setError(e.error, e.getMessage());
17264                        return;
17265                    }
17266                }
17267
17268                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17269                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17270                    systemApp = (ps.pkg.applicationInfo.flags &
17271                            ApplicationInfo.FLAG_SYSTEM) != 0;
17272                }
17273                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17274            }
17275
17276            int N = pkg.permissions.size();
17277            for (int i = N-1; i >= 0; i--) {
17278                final PackageParser.Permission perm = pkg.permissions.get(i);
17279                final BasePermission bp =
17280                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17281
17282                // Don't allow anyone but the system to define ephemeral permissions.
17283                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17284                        && !systemApp) {
17285                    Slog.w(TAG, "Non-System package " + pkg.packageName
17286                            + " attempting to delcare ephemeral permission "
17287                            + perm.info.name + "; Removing ephemeral.");
17288                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17289                }
17290
17291                // Check whether the newly-scanned package wants to define an already-defined perm
17292                if (bp != null) {
17293                    // If the defining package is signed with our cert, it's okay.  This
17294                    // also includes the "updating the same package" case, of course.
17295                    // "updating same package" could also involve key-rotation.
17296                    final boolean sigsOk;
17297                    final String sourcePackageName = bp.getSourcePackageName();
17298                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17299                    if (sourcePackageName.equals(pkg.packageName)
17300                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17301                                    scanFlags))) {
17302                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17303                    } else {
17304                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17305                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17306                    }
17307                    if (!sigsOk) {
17308                        // If the owning package is the system itself, we log but allow
17309                        // install to proceed; we fail the install on all other permission
17310                        // redefinitions.
17311                        if (!sourcePackageName.equals("android")) {
17312                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17313                                    + pkg.packageName + " attempting to redeclare permission "
17314                                    + perm.info.name + " already owned by " + sourcePackageName);
17315                            res.origPermission = perm.info.name;
17316                            res.origPackage = sourcePackageName;
17317                            return;
17318                        } else {
17319                            Slog.w(TAG, "Package " + pkg.packageName
17320                                    + " attempting to redeclare system permission "
17321                                    + perm.info.name + "; ignoring new declaration");
17322                            pkg.permissions.remove(i);
17323                        }
17324                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17325                        // Prevent apps to change protection level to dangerous from any other
17326                        // type as this would allow a privilege escalation where an app adds a
17327                        // normal/signature permission in other app's group and later redefines
17328                        // it as dangerous leading to the group auto-grant.
17329                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17330                                == PermissionInfo.PROTECTION_DANGEROUS) {
17331                            if (bp != null && !bp.isRuntime()) {
17332                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17333                                        + "non-runtime permission " + perm.info.name
17334                                        + " to runtime; keeping old protection level");
17335                                perm.info.protectionLevel = bp.getProtectionLevel();
17336                            }
17337                        }
17338                    }
17339                }
17340            }
17341        }
17342
17343        if (systemApp) {
17344            if (onExternal) {
17345                // Abort update; system app can't be replaced with app on sdcard
17346                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17347                        "Cannot install updates to system apps on sdcard");
17348                return;
17349            } else if (instantApp) {
17350                // Abort update; system app can't be replaced with an instant app
17351                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17352                        "Cannot update a system app with an instant app");
17353                return;
17354            }
17355        }
17356
17357        if (args.move != null) {
17358            // We did an in-place move, so dex is ready to roll
17359            scanFlags |= SCAN_NO_DEX;
17360            scanFlags |= SCAN_MOVE;
17361
17362            synchronized (mPackages) {
17363                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17364                if (ps == null) {
17365                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17366                            "Missing settings for moved package " + pkgName);
17367                }
17368
17369                // We moved the entire application as-is, so bring over the
17370                // previously derived ABI information.
17371                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17372                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17373            }
17374
17375        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17376            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17377            scanFlags |= SCAN_NO_DEX;
17378
17379            try {
17380                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17381                    args.abiOverride : pkg.cpuAbiOverride);
17382                final boolean extractNativeLibs = !pkg.isLibrary();
17383                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17384                        extractNativeLibs, mAppLib32InstallDir);
17385            } catch (PackageManagerException pme) {
17386                Slog.e(TAG, "Error deriving application ABI", pme);
17387                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17388                return;
17389            }
17390
17391            // Shared libraries for the package need to be updated.
17392            synchronized (mPackages) {
17393                try {
17394                    updateSharedLibrariesLPr(pkg, null);
17395                } catch (PackageManagerException e) {
17396                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17397                }
17398            }
17399        }
17400
17401        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17402            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17403            return;
17404        }
17405
17406        // Verify if we need to dexopt the app.
17407        //
17408        // NOTE: it is *important* to call dexopt after doRename which will sync the
17409        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17410        //
17411        // We only need to dexopt if the package meets ALL of the following conditions:
17412        //   1) it is not forward locked.
17413        //   2) it is not on on an external ASEC container.
17414        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17415        //
17416        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17417        // complete, so we skip this step during installation. Instead, we'll take extra time
17418        // the first time the instant app starts. It's preferred to do it this way to provide
17419        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17420        // middle of running an instant app. The default behaviour can be overridden
17421        // via gservices.
17422        final boolean performDexopt = !forwardLocked
17423            && !pkg.applicationInfo.isExternalAsec()
17424            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17425                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17426
17427        if (performDexopt) {
17428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17429            // Do not run PackageDexOptimizer through the local performDexOpt
17430            // method because `pkg` may not be in `mPackages` yet.
17431            //
17432            // Also, don't fail application installs if the dexopt step fails.
17433            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17434                REASON_INSTALL,
17435                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17436            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17437                null /* instructionSets */,
17438                getOrCreateCompilerPackageStats(pkg),
17439                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17440                dexoptOptions);
17441            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17442        }
17443
17444        // Notify BackgroundDexOptService that the package has been changed.
17445        // If this is an update of a package which used to fail to compile,
17446        // BackgroundDexOptService will remove it from its blacklist.
17447        // TODO: Layering violation
17448        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17449
17450        if (!instantApp) {
17451            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17452        } else {
17453            if (DEBUG_DOMAIN_VERIFICATION) {
17454                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17455            }
17456        }
17457
17458        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17459                "installPackageLI")) {
17460            if (replace) {
17461                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17462                    // Static libs have a synthetic package name containing the version
17463                    // and cannot be updated as an update would get a new package name,
17464                    // unless this is the exact same version code which is useful for
17465                    // development.
17466                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17467                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17468                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17469                                + "static-shared libs cannot be updated");
17470                        return;
17471                    }
17472                }
17473                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17474                        installerPackageName, res, args.installReason);
17475            } else {
17476                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17477                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17478            }
17479        }
17480
17481        synchronized (mPackages) {
17482            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17483            if (ps != null) {
17484                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17485                ps.setUpdateAvailable(false /*updateAvailable*/);
17486            }
17487
17488            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17489            for (int i = 0; i < childCount; i++) {
17490                PackageParser.Package childPkg = pkg.childPackages.get(i);
17491                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17492                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17493                if (childPs != null) {
17494                    childRes.newUsers = childPs.queryInstalledUsers(
17495                            sUserManager.getUserIds(), true);
17496                }
17497            }
17498
17499            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17500                updateSequenceNumberLP(ps, res.newUsers);
17501                updateInstantAppInstallerLocked(pkgName);
17502            }
17503        }
17504    }
17505
17506    private void startIntentFilterVerifications(int userId, boolean replacing,
17507            PackageParser.Package pkg) {
17508        if (mIntentFilterVerifierComponent == null) {
17509            Slog.w(TAG, "No IntentFilter verification will not be done as "
17510                    + "there is no IntentFilterVerifier available!");
17511            return;
17512        }
17513
17514        final int verifierUid = getPackageUid(
17515                mIntentFilterVerifierComponent.getPackageName(),
17516                MATCH_DEBUG_TRIAGED_MISSING,
17517                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17518
17519        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17520        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17521        mHandler.sendMessage(msg);
17522
17523        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17524        for (int i = 0; i < childCount; i++) {
17525            PackageParser.Package childPkg = pkg.childPackages.get(i);
17526            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17527            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17528            mHandler.sendMessage(msg);
17529        }
17530    }
17531
17532    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17533            PackageParser.Package pkg) {
17534        int size = pkg.activities.size();
17535        if (size == 0) {
17536            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17537                    "No activity, so no need to verify any IntentFilter!");
17538            return;
17539        }
17540
17541        final boolean hasDomainURLs = hasDomainURLs(pkg);
17542        if (!hasDomainURLs) {
17543            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17544                    "No domain URLs, so no need to verify any IntentFilter!");
17545            return;
17546        }
17547
17548        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17549                + " if any IntentFilter from the " + size
17550                + " Activities needs verification ...");
17551
17552        int count = 0;
17553        final String packageName = pkg.packageName;
17554
17555        synchronized (mPackages) {
17556            // If this is a new install and we see that we've already run verification for this
17557            // package, we have nothing to do: it means the state was restored from backup.
17558            if (!replacing) {
17559                IntentFilterVerificationInfo ivi =
17560                        mSettings.getIntentFilterVerificationLPr(packageName);
17561                if (ivi != null) {
17562                    if (DEBUG_DOMAIN_VERIFICATION) {
17563                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17564                                + ivi.getStatusString());
17565                    }
17566                    return;
17567                }
17568            }
17569
17570            // If any filters need to be verified, then all need to be.
17571            boolean needToVerify = false;
17572            for (PackageParser.Activity a : pkg.activities) {
17573                for (ActivityIntentInfo filter : a.intents) {
17574                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17575                        if (DEBUG_DOMAIN_VERIFICATION) {
17576                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17577                        }
17578                        needToVerify = true;
17579                        break;
17580                    }
17581                }
17582            }
17583
17584            if (needToVerify) {
17585                final int verificationId = mIntentFilterVerificationToken++;
17586                for (PackageParser.Activity a : pkg.activities) {
17587                    for (ActivityIntentInfo filter : a.intents) {
17588                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17589                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17590                                    "Verification needed for IntentFilter:" + filter.toString());
17591                            mIntentFilterVerifier.addOneIntentFilterVerification(
17592                                    verifierUid, userId, verificationId, filter, packageName);
17593                            count++;
17594                        }
17595                    }
17596                }
17597            }
17598        }
17599
17600        if (count > 0) {
17601            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17602                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17603                    +  " for userId:" + userId);
17604            mIntentFilterVerifier.startVerifications(userId);
17605        } else {
17606            if (DEBUG_DOMAIN_VERIFICATION) {
17607                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17608            }
17609        }
17610    }
17611
17612    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17613        final ComponentName cn  = filter.activity.getComponentName();
17614        final String packageName = cn.getPackageName();
17615
17616        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17617                packageName);
17618        if (ivi == null) {
17619            return true;
17620        }
17621        int status = ivi.getStatus();
17622        switch (status) {
17623            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17624            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17625                return true;
17626
17627            default:
17628                // Nothing to do
17629                return false;
17630        }
17631    }
17632
17633    private static boolean isMultiArch(ApplicationInfo info) {
17634        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17635    }
17636
17637    private static boolean isExternal(PackageParser.Package pkg) {
17638        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17639    }
17640
17641    private static boolean isExternal(PackageSetting ps) {
17642        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17643    }
17644
17645    private static boolean isSystemApp(PackageParser.Package pkg) {
17646        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17647    }
17648
17649    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17650        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17651    }
17652
17653    private static boolean isOemApp(PackageParser.Package pkg) {
17654        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17655    }
17656
17657    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17658        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17659    }
17660
17661    private static boolean isSystemApp(PackageSetting ps) {
17662        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17663    }
17664
17665    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17666        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17667    }
17668
17669    private int packageFlagsToInstallFlags(PackageSetting ps) {
17670        int installFlags = 0;
17671        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17672            // This existing package was an external ASEC install when we have
17673            // the external flag without a UUID
17674            installFlags |= PackageManager.INSTALL_EXTERNAL;
17675        }
17676        if (ps.isForwardLocked()) {
17677            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17678        }
17679        return installFlags;
17680    }
17681
17682    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17683        if (isExternal(pkg)) {
17684            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17685                return StorageManager.UUID_PRIMARY_PHYSICAL;
17686            } else {
17687                return pkg.volumeUuid;
17688            }
17689        } else {
17690            return StorageManager.UUID_PRIVATE_INTERNAL;
17691        }
17692    }
17693
17694    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17695        if (isExternal(pkg)) {
17696            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17697                return mSettings.getExternalVersion();
17698            } else {
17699                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17700            }
17701        } else {
17702            return mSettings.getInternalVersion();
17703        }
17704    }
17705
17706    private void deleteTempPackageFiles() {
17707        final FilenameFilter filter = new FilenameFilter() {
17708            public boolean accept(File dir, String name) {
17709                return name.startsWith("vmdl") && name.endsWith(".tmp");
17710            }
17711        };
17712        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17713            file.delete();
17714        }
17715    }
17716
17717    @Override
17718    public void deletePackageAsUser(String packageName, int versionCode,
17719            IPackageDeleteObserver observer, int userId, int flags) {
17720        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17721                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17722    }
17723
17724    @Override
17725    public void deletePackageVersioned(VersionedPackage versionedPackage,
17726            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17727        final int callingUid = Binder.getCallingUid();
17728        mContext.enforceCallingOrSelfPermission(
17729                android.Manifest.permission.DELETE_PACKAGES, null);
17730        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17731        Preconditions.checkNotNull(versionedPackage);
17732        Preconditions.checkNotNull(observer);
17733        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17734                PackageManager.VERSION_CODE_HIGHEST,
17735                Integer.MAX_VALUE, "versionCode must be >= -1");
17736
17737        final String packageName = versionedPackage.getPackageName();
17738        final int versionCode = versionedPackage.getVersionCode();
17739        final String internalPackageName;
17740        synchronized (mPackages) {
17741            // Normalize package name to handle renamed packages and static libs
17742            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17743                    versionedPackage.getVersionCode());
17744        }
17745
17746        final int uid = Binder.getCallingUid();
17747        if (!isOrphaned(internalPackageName)
17748                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17749            try {
17750                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17751                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17752                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17753                observer.onUserActionRequired(intent);
17754            } catch (RemoteException re) {
17755            }
17756            return;
17757        }
17758        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17759        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17760        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17761            mContext.enforceCallingOrSelfPermission(
17762                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17763                    "deletePackage for user " + userId);
17764        }
17765
17766        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17767            try {
17768                observer.onPackageDeleted(packageName,
17769                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17770            } catch (RemoteException re) {
17771            }
17772            return;
17773        }
17774
17775        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17776            try {
17777                observer.onPackageDeleted(packageName,
17778                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17779            } catch (RemoteException re) {
17780            }
17781            return;
17782        }
17783
17784        if (DEBUG_REMOVE) {
17785            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17786                    + " deleteAllUsers: " + deleteAllUsers + " version="
17787                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17788                    ? "VERSION_CODE_HIGHEST" : versionCode));
17789        }
17790        // Queue up an async operation since the package deletion may take a little while.
17791        mHandler.post(new Runnable() {
17792            public void run() {
17793                mHandler.removeCallbacks(this);
17794                int returnCode;
17795                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17796                boolean doDeletePackage = true;
17797                if (ps != null) {
17798                    final boolean targetIsInstantApp =
17799                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17800                    doDeletePackage = !targetIsInstantApp
17801                            || canViewInstantApps;
17802                }
17803                if (doDeletePackage) {
17804                    if (!deleteAllUsers) {
17805                        returnCode = deletePackageX(internalPackageName, versionCode,
17806                                userId, deleteFlags);
17807                    } else {
17808                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17809                                internalPackageName, users);
17810                        // If nobody is blocking uninstall, proceed with delete for all users
17811                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17812                            returnCode = deletePackageX(internalPackageName, versionCode,
17813                                    userId, deleteFlags);
17814                        } else {
17815                            // Otherwise uninstall individually for users with blockUninstalls=false
17816                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17817                            for (int userId : users) {
17818                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17819                                    returnCode = deletePackageX(internalPackageName, versionCode,
17820                                            userId, userFlags);
17821                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17822                                        Slog.w(TAG, "Package delete failed for user " + userId
17823                                                + ", returnCode " + returnCode);
17824                                    }
17825                                }
17826                            }
17827                            // The app has only been marked uninstalled for certain users.
17828                            // We still need to report that delete was blocked
17829                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17830                        }
17831                    }
17832                } else {
17833                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17834                }
17835                try {
17836                    observer.onPackageDeleted(packageName, returnCode, null);
17837                } catch (RemoteException e) {
17838                    Log.i(TAG, "Observer no longer exists.");
17839                } //end catch
17840            } //end run
17841        });
17842    }
17843
17844    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17845        if (pkg.staticSharedLibName != null) {
17846            return pkg.manifestPackageName;
17847        }
17848        return pkg.packageName;
17849    }
17850
17851    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17852        // Handle renamed packages
17853        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17854        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17855
17856        // Is this a static library?
17857        SparseArray<SharedLibraryEntry> versionedLib =
17858                mStaticLibsByDeclaringPackage.get(packageName);
17859        if (versionedLib == null || versionedLib.size() <= 0) {
17860            return packageName;
17861        }
17862
17863        // Figure out which lib versions the caller can see
17864        SparseIntArray versionsCallerCanSee = null;
17865        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17866        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17867                && callingAppId != Process.ROOT_UID) {
17868            versionsCallerCanSee = new SparseIntArray();
17869            String libName = versionedLib.valueAt(0).info.getName();
17870            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17871            if (uidPackages != null) {
17872                for (String uidPackage : uidPackages) {
17873                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17874                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17875                    if (libIdx >= 0) {
17876                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17877                        versionsCallerCanSee.append(libVersion, libVersion);
17878                    }
17879                }
17880            }
17881        }
17882
17883        // Caller can see nothing - done
17884        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17885            return packageName;
17886        }
17887
17888        // Find the version the caller can see and the app version code
17889        SharedLibraryEntry highestVersion = null;
17890        final int versionCount = versionedLib.size();
17891        for (int i = 0; i < versionCount; i++) {
17892            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17893            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17894                    libEntry.info.getVersion()) < 0) {
17895                continue;
17896            }
17897            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
17898            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17899                if (libVersionCode == versionCode) {
17900                    return libEntry.apk;
17901                }
17902            } else if (highestVersion == null) {
17903                highestVersion = libEntry;
17904            } else if (libVersionCode  > highestVersion.info
17905                    .getDeclaringPackage().getVersionCode()) {
17906                highestVersion = libEntry;
17907            }
17908        }
17909
17910        if (highestVersion != null) {
17911            return highestVersion.apk;
17912        }
17913
17914        return packageName;
17915    }
17916
17917    boolean isCallerVerifier(int callingUid) {
17918        final int callingUserId = UserHandle.getUserId(callingUid);
17919        return mRequiredVerifierPackage != null &&
17920                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17921    }
17922
17923    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17924        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17925              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17926            return true;
17927        }
17928        final int callingUserId = UserHandle.getUserId(callingUid);
17929        // If the caller installed the pkgName, then allow it to silently uninstall.
17930        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17931            return true;
17932        }
17933
17934        // Allow package verifier to silently uninstall.
17935        if (mRequiredVerifierPackage != null &&
17936                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17937            return true;
17938        }
17939
17940        // Allow package uninstaller to silently uninstall.
17941        if (mRequiredUninstallerPackage != null &&
17942                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17943            return true;
17944        }
17945
17946        // Allow storage manager to silently uninstall.
17947        if (mStorageManagerPackage != null &&
17948                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17949            return true;
17950        }
17951
17952        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17953        // uninstall for device owner provisioning.
17954        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17955                == PERMISSION_GRANTED) {
17956            return true;
17957        }
17958
17959        return false;
17960    }
17961
17962    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17963        int[] result = EMPTY_INT_ARRAY;
17964        for (int userId : userIds) {
17965            if (getBlockUninstallForUser(packageName, userId)) {
17966                result = ArrayUtils.appendInt(result, userId);
17967            }
17968        }
17969        return result;
17970    }
17971
17972    @Override
17973    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17974        final int callingUid = Binder.getCallingUid();
17975        if (getInstantAppPackageName(callingUid) != null
17976                && !isCallerSameApp(packageName, callingUid)) {
17977            return false;
17978        }
17979        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17980    }
17981
17982    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17983        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17984                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17985        try {
17986            if (dpm != null) {
17987                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17988                        /* callingUserOnly =*/ false);
17989                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17990                        : deviceOwnerComponentName.getPackageName();
17991                // Does the package contains the device owner?
17992                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17993                // this check is probably not needed, since DO should be registered as a device
17994                // admin on some user too. (Original bug for this: b/17657954)
17995                if (packageName.equals(deviceOwnerPackageName)) {
17996                    return true;
17997                }
17998                // Does it contain a device admin for any user?
17999                int[] users;
18000                if (userId == UserHandle.USER_ALL) {
18001                    users = sUserManager.getUserIds();
18002                } else {
18003                    users = new int[]{userId};
18004                }
18005                for (int i = 0; i < users.length; ++i) {
18006                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18007                        return true;
18008                    }
18009                }
18010            }
18011        } catch (RemoteException e) {
18012        }
18013        return false;
18014    }
18015
18016    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18017        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18018    }
18019
18020    /**
18021     *  This method is an internal method that could be get invoked either
18022     *  to delete an installed package or to clean up a failed installation.
18023     *  After deleting an installed package, a broadcast is sent to notify any
18024     *  listeners that the package has been removed. For cleaning up a failed
18025     *  installation, the broadcast is not necessary since the package's
18026     *  installation wouldn't have sent the initial broadcast either
18027     *  The key steps in deleting a package are
18028     *  deleting the package information in internal structures like mPackages,
18029     *  deleting the packages base directories through installd
18030     *  updating mSettings to reflect current status
18031     *  persisting settings for later use
18032     *  sending a broadcast if necessary
18033     */
18034    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18035        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18036        final boolean res;
18037
18038        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18039                ? UserHandle.USER_ALL : userId;
18040
18041        if (isPackageDeviceAdmin(packageName, removeUser)) {
18042            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18043            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18044        }
18045
18046        PackageSetting uninstalledPs = null;
18047        PackageParser.Package pkg = null;
18048
18049        // for the uninstall-updates case and restricted profiles, remember the per-
18050        // user handle installed state
18051        int[] allUsers;
18052        synchronized (mPackages) {
18053            uninstalledPs = mSettings.mPackages.get(packageName);
18054            if (uninstalledPs == null) {
18055                Slog.w(TAG, "Not removing non-existent package " + packageName);
18056                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18057            }
18058
18059            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18060                    && uninstalledPs.versionCode != versionCode) {
18061                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18062                        + uninstalledPs.versionCode + " != " + versionCode);
18063                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18064            }
18065
18066            // Static shared libs can be declared by any package, so let us not
18067            // allow removing a package if it provides a lib others depend on.
18068            pkg = mPackages.get(packageName);
18069
18070            allUsers = sUserManager.getUserIds();
18071
18072            if (pkg != null && pkg.staticSharedLibName != null) {
18073                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18074                        pkg.staticSharedLibVersion);
18075                if (libEntry != null) {
18076                    for (int currUserId : allUsers) {
18077                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18078                            continue;
18079                        }
18080                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18081                                libEntry.info, 0, currUserId);
18082                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18083                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18084                                    + " hosting lib " + libEntry.info.getName() + " version "
18085                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18086                                    + " for user " + currUserId);
18087                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18088                        }
18089                    }
18090                }
18091            }
18092
18093            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18094        }
18095
18096        final int freezeUser;
18097        if (isUpdatedSystemApp(uninstalledPs)
18098                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18099            // We're downgrading a system app, which will apply to all users, so
18100            // freeze them all during the downgrade
18101            freezeUser = UserHandle.USER_ALL;
18102        } else {
18103            freezeUser = removeUser;
18104        }
18105
18106        synchronized (mInstallLock) {
18107            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18108            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18109                    deleteFlags, "deletePackageX")) {
18110                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18111                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18112            }
18113            synchronized (mPackages) {
18114                if (res) {
18115                    if (pkg != null) {
18116                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18117                    }
18118                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18119                    updateInstantAppInstallerLocked(packageName);
18120                }
18121            }
18122        }
18123
18124        if (res) {
18125            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18126            info.sendPackageRemovedBroadcasts(killApp);
18127            info.sendSystemPackageUpdatedBroadcasts();
18128            info.sendSystemPackageAppearedBroadcasts();
18129        }
18130        // Force a gc here.
18131        Runtime.getRuntime().gc();
18132        // Delete the resources here after sending the broadcast to let
18133        // other processes clean up before deleting resources.
18134        if (info.args != null) {
18135            synchronized (mInstallLock) {
18136                info.args.doPostDeleteLI(true);
18137            }
18138        }
18139
18140        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18141    }
18142
18143    static class PackageRemovedInfo {
18144        final PackageSender packageSender;
18145        String removedPackage;
18146        String installerPackageName;
18147        int uid = -1;
18148        int removedAppId = -1;
18149        int[] origUsers;
18150        int[] removedUsers = null;
18151        int[] broadcastUsers = null;
18152        SparseArray<Integer> installReasons;
18153        boolean isRemovedPackageSystemUpdate = false;
18154        boolean isUpdate;
18155        boolean dataRemoved;
18156        boolean removedForAllUsers;
18157        boolean isStaticSharedLib;
18158        // Clean up resources deleted packages.
18159        InstallArgs args = null;
18160        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18161        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18162
18163        PackageRemovedInfo(PackageSender packageSender) {
18164            this.packageSender = packageSender;
18165        }
18166
18167        void sendPackageRemovedBroadcasts(boolean killApp) {
18168            sendPackageRemovedBroadcastInternal(killApp);
18169            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18170            for (int i = 0; i < childCount; i++) {
18171                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18172                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18173            }
18174        }
18175
18176        void sendSystemPackageUpdatedBroadcasts() {
18177            if (isRemovedPackageSystemUpdate) {
18178                sendSystemPackageUpdatedBroadcastsInternal();
18179                final int childCount = (removedChildPackages != null)
18180                        ? removedChildPackages.size() : 0;
18181                for (int i = 0; i < childCount; i++) {
18182                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18183                    if (childInfo.isRemovedPackageSystemUpdate) {
18184                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18185                    }
18186                }
18187            }
18188        }
18189
18190        void sendSystemPackageAppearedBroadcasts() {
18191            final int packageCount = (appearedChildPackages != null)
18192                    ? appearedChildPackages.size() : 0;
18193            for (int i = 0; i < packageCount; i++) {
18194                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18195                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18196                    true /*sendBootCompleted*/, false /*startReceiver*/,
18197                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18198            }
18199        }
18200
18201        private void sendSystemPackageUpdatedBroadcastsInternal() {
18202            Bundle extras = new Bundle(2);
18203            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18204            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18205            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18206                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18207            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18208                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18209            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18210                null, null, 0, removedPackage, null, null);
18211            if (installerPackageName != null) {
18212                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18213                        removedPackage, extras, 0 /*flags*/,
18214                        installerPackageName, null, null);
18215                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18216                        removedPackage, extras, 0 /*flags*/,
18217                        installerPackageName, null, null);
18218            }
18219        }
18220
18221        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18222            // Don't send static shared library removal broadcasts as these
18223            // libs are visible only the the apps that depend on them an one
18224            // cannot remove the library if it has a dependency.
18225            if (isStaticSharedLib) {
18226                return;
18227            }
18228            Bundle extras = new Bundle(2);
18229            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18230            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18231            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18232            if (isUpdate || isRemovedPackageSystemUpdate) {
18233                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18234            }
18235            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18236            if (removedPackage != null) {
18237                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18238                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18239                if (installerPackageName != null) {
18240                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18241                            removedPackage, extras, 0 /*flags*/,
18242                            installerPackageName, null, broadcastUsers);
18243                }
18244                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18245                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18246                        removedPackage, extras,
18247                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18248                        null, null, broadcastUsers);
18249                }
18250            }
18251            if (removedAppId >= 0) {
18252                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18253                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18254                    null, null, broadcastUsers);
18255            }
18256        }
18257
18258        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18259            removedUsers = userIds;
18260            if (removedUsers == null) {
18261                broadcastUsers = null;
18262                return;
18263            }
18264
18265            broadcastUsers = EMPTY_INT_ARRAY;
18266            for (int i = userIds.length - 1; i >= 0; --i) {
18267                final int userId = userIds[i];
18268                if (deletedPackageSetting.getInstantApp(userId)) {
18269                    continue;
18270                }
18271                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18272            }
18273        }
18274    }
18275
18276    /*
18277     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18278     * flag is not set, the data directory is removed as well.
18279     * make sure this flag is set for partially installed apps. If not its meaningless to
18280     * delete a partially installed application.
18281     */
18282    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18283            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18284        String packageName = ps.name;
18285        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18286        // Retrieve object to delete permissions for shared user later on
18287        final PackageParser.Package deletedPkg;
18288        final PackageSetting deletedPs;
18289        // reader
18290        synchronized (mPackages) {
18291            deletedPkg = mPackages.get(packageName);
18292            deletedPs = mSettings.mPackages.get(packageName);
18293            if (outInfo != null) {
18294                outInfo.removedPackage = packageName;
18295                outInfo.installerPackageName = ps.installerPackageName;
18296                outInfo.isStaticSharedLib = deletedPkg != null
18297                        && deletedPkg.staticSharedLibName != null;
18298                outInfo.populateUsers(deletedPs == null ? null
18299                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18300            }
18301        }
18302
18303        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18304
18305        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18306            final PackageParser.Package resolvedPkg;
18307            if (deletedPkg != null) {
18308                resolvedPkg = deletedPkg;
18309            } else {
18310                // We don't have a parsed package when it lives on an ejected
18311                // adopted storage device, so fake something together
18312                resolvedPkg = new PackageParser.Package(ps.name);
18313                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18314            }
18315            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18316                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18317            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18318            if (outInfo != null) {
18319                outInfo.dataRemoved = true;
18320            }
18321            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18322        }
18323
18324        int removedAppId = -1;
18325
18326        // writer
18327        synchronized (mPackages) {
18328            boolean installedStateChanged = false;
18329            if (deletedPs != null) {
18330                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18331                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18332                    clearDefaultBrowserIfNeeded(packageName);
18333                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18334                    removedAppId = mSettings.removePackageLPw(packageName);
18335                    if (outInfo != null) {
18336                        outInfo.removedAppId = removedAppId;
18337                    }
18338                    updatePermissionsLPw(deletedPs.name, null, 0);
18339                    if (deletedPs.sharedUser != null) {
18340                        // Remove permissions associated with package. Since runtime
18341                        // permissions are per user we have to kill the removed package
18342                        // or packages running under the shared user of the removed
18343                        // package if revoking the permissions requested only by the removed
18344                        // package is successful and this causes a change in gids.
18345                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18346                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18347                                    userId);
18348                            if (userIdToKill == UserHandle.USER_ALL
18349                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18350                                // If gids changed for this user, kill all affected packages.
18351                                mHandler.post(new Runnable() {
18352                                    @Override
18353                                    public void run() {
18354                                        // This has to happen with no lock held.
18355                                        killApplication(deletedPs.name, deletedPs.appId,
18356                                                KILL_APP_REASON_GIDS_CHANGED);
18357                                    }
18358                                });
18359                                break;
18360                            }
18361                        }
18362                    }
18363                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18364                }
18365                // make sure to preserve per-user disabled state if this removal was just
18366                // a downgrade of a system app to the factory package
18367                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18368                    if (DEBUG_REMOVE) {
18369                        Slog.d(TAG, "Propagating install state across downgrade");
18370                    }
18371                    for (int userId : allUserHandles) {
18372                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18373                        if (DEBUG_REMOVE) {
18374                            Slog.d(TAG, "    user " + userId + " => " + installed);
18375                        }
18376                        if (installed != ps.getInstalled(userId)) {
18377                            installedStateChanged = true;
18378                        }
18379                        ps.setInstalled(installed, userId);
18380                    }
18381                }
18382            }
18383            // can downgrade to reader
18384            if (writeSettings) {
18385                // Save settings now
18386                mSettings.writeLPr();
18387            }
18388            if (installedStateChanged) {
18389                mSettings.writeKernelMappingLPr(ps);
18390            }
18391        }
18392        if (removedAppId != -1) {
18393            // A user ID was deleted here. Go through all users and remove it
18394            // from KeyStore.
18395            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18396        }
18397    }
18398
18399    static boolean locationIsPrivileged(File path) {
18400        try {
18401            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18402                    .getCanonicalPath();
18403            return path.getCanonicalPath().startsWith(privilegedAppDir);
18404        } catch (IOException e) {
18405            Slog.e(TAG, "Unable to access code path " + path);
18406        }
18407        return false;
18408    }
18409
18410    static boolean locationIsOem(File path) {
18411        try {
18412            return path.getCanonicalPath().startsWith(
18413                    Environment.getOemDirectory().getCanonicalPath());
18414        } catch (IOException e) {
18415            Slog.e(TAG, "Unable to access code path " + path);
18416        }
18417        return false;
18418    }
18419
18420    /*
18421     * Tries to delete system package.
18422     */
18423    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18424            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18425            boolean writeSettings) {
18426        if (deletedPs.parentPackageName != null) {
18427            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18428            return false;
18429        }
18430
18431        final boolean applyUserRestrictions
18432                = (allUserHandles != null) && (outInfo.origUsers != null);
18433        final PackageSetting disabledPs;
18434        // Confirm if the system package has been updated
18435        // An updated system app can be deleted. This will also have to restore
18436        // the system pkg from system partition
18437        // reader
18438        synchronized (mPackages) {
18439            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18440        }
18441
18442        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18443                + " disabledPs=" + disabledPs);
18444
18445        if (disabledPs == null) {
18446            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18447            return false;
18448        } else if (DEBUG_REMOVE) {
18449            Slog.d(TAG, "Deleting system pkg from data partition");
18450        }
18451
18452        if (DEBUG_REMOVE) {
18453            if (applyUserRestrictions) {
18454                Slog.d(TAG, "Remembering install states:");
18455                for (int userId : allUserHandles) {
18456                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18457                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18458                }
18459            }
18460        }
18461
18462        // Delete the updated package
18463        outInfo.isRemovedPackageSystemUpdate = true;
18464        if (outInfo.removedChildPackages != null) {
18465            final int childCount = (deletedPs.childPackageNames != null)
18466                    ? deletedPs.childPackageNames.size() : 0;
18467            for (int i = 0; i < childCount; i++) {
18468                String childPackageName = deletedPs.childPackageNames.get(i);
18469                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18470                        .contains(childPackageName)) {
18471                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18472                            childPackageName);
18473                    if (childInfo != null) {
18474                        childInfo.isRemovedPackageSystemUpdate = true;
18475                    }
18476                }
18477            }
18478        }
18479
18480        if (disabledPs.versionCode < deletedPs.versionCode) {
18481            // Delete data for downgrades
18482            flags &= ~PackageManager.DELETE_KEEP_DATA;
18483        } else {
18484            // Preserve data by setting flag
18485            flags |= PackageManager.DELETE_KEEP_DATA;
18486        }
18487
18488        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18489                outInfo, writeSettings, disabledPs.pkg);
18490        if (!ret) {
18491            return false;
18492        }
18493
18494        // writer
18495        synchronized (mPackages) {
18496            // NOTE: The system package always needs to be enabled; even if it's for
18497            // a compressed stub. If we don't, installing the system package fails
18498            // during scan [scanning checks the disabled packages]. We will reverse
18499            // this later, after we've "installed" the stub.
18500            // Reinstate the old system package
18501            enableSystemPackageLPw(disabledPs.pkg);
18502            // Remove any native libraries from the upgraded package.
18503            removeNativeBinariesLI(deletedPs);
18504        }
18505
18506        // Install the system package
18507        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18508        try {
18509            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18510                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18511        } catch (PackageManagerException e) {
18512            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18513                    + e.getMessage());
18514            return false;
18515        } finally {
18516            if (disabledPs.pkg.isStub) {
18517                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18518            }
18519        }
18520        return true;
18521    }
18522
18523    /**
18524     * Installs a package that's already on the system partition.
18525     */
18526    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18527            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18528            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18529                    throws PackageManagerException {
18530        int parseFlags = mDefParseFlags
18531                | PackageParser.PARSE_MUST_BE_APK
18532                | PackageParser.PARSE_IS_SYSTEM
18533                | PackageParser.PARSE_IS_SYSTEM_DIR;
18534        if (isPrivileged || locationIsPrivileged(codePath)) {
18535            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18536        }
18537        if (locationIsOem(codePath)) {
18538            parseFlags |= PackageParser.PARSE_IS_OEM;
18539        }
18540
18541        final PackageParser.Package newPkg =
18542                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18543
18544        try {
18545            // update shared libraries for the newly re-installed system package
18546            updateSharedLibrariesLPr(newPkg, null);
18547        } catch (PackageManagerException e) {
18548            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18549        }
18550
18551        prepareAppDataAfterInstallLIF(newPkg);
18552
18553        // writer
18554        synchronized (mPackages) {
18555            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18556
18557            // Propagate the permissions state as we do not want to drop on the floor
18558            // runtime permissions. The update permissions method below will take
18559            // care of removing obsolete permissions and grant install permissions.
18560            if (origPermissionState != null) {
18561                ps.getPermissionsState().copyFrom(origPermissionState);
18562            }
18563            updatePermissionsLPw(newPkg.packageName, newPkg,
18564                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18565
18566            final boolean applyUserRestrictions
18567                    = (allUserHandles != null) && (origUserHandles != null);
18568            if (applyUserRestrictions) {
18569                boolean installedStateChanged = false;
18570                if (DEBUG_REMOVE) {
18571                    Slog.d(TAG, "Propagating install state across reinstall");
18572                }
18573                for (int userId : allUserHandles) {
18574                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18575                    if (DEBUG_REMOVE) {
18576                        Slog.d(TAG, "    user " + userId + " => " + installed);
18577                    }
18578                    if (installed != ps.getInstalled(userId)) {
18579                        installedStateChanged = true;
18580                    }
18581                    ps.setInstalled(installed, userId);
18582
18583                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18584                }
18585                // Regardless of writeSettings we need to ensure that this restriction
18586                // state propagation is persisted
18587                mSettings.writeAllUsersPackageRestrictionsLPr();
18588                if (installedStateChanged) {
18589                    mSettings.writeKernelMappingLPr(ps);
18590                }
18591            }
18592            // can downgrade to reader here
18593            if (writeSettings) {
18594                mSettings.writeLPr();
18595            }
18596        }
18597        return newPkg;
18598    }
18599
18600    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18601            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18602            PackageRemovedInfo outInfo, boolean writeSettings,
18603            PackageParser.Package replacingPackage) {
18604        synchronized (mPackages) {
18605            if (outInfo != null) {
18606                outInfo.uid = ps.appId;
18607            }
18608
18609            if (outInfo != null && outInfo.removedChildPackages != null) {
18610                final int childCount = (ps.childPackageNames != null)
18611                        ? ps.childPackageNames.size() : 0;
18612                for (int i = 0; i < childCount; i++) {
18613                    String childPackageName = ps.childPackageNames.get(i);
18614                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18615                    if (childPs == null) {
18616                        return false;
18617                    }
18618                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18619                            childPackageName);
18620                    if (childInfo != null) {
18621                        childInfo.uid = childPs.appId;
18622                    }
18623                }
18624            }
18625        }
18626
18627        // Delete package data from internal structures and also remove data if flag is set
18628        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18629
18630        // Delete the child packages data
18631        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18632        for (int i = 0; i < childCount; i++) {
18633            PackageSetting childPs;
18634            synchronized (mPackages) {
18635                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18636            }
18637            if (childPs != null) {
18638                PackageRemovedInfo childOutInfo = (outInfo != null
18639                        && outInfo.removedChildPackages != null)
18640                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18641                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18642                        && (replacingPackage != null
18643                        && !replacingPackage.hasChildPackage(childPs.name))
18644                        ? flags & ~DELETE_KEEP_DATA : flags;
18645                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18646                        deleteFlags, writeSettings);
18647            }
18648        }
18649
18650        // Delete application code and resources only for parent packages
18651        if (ps.parentPackageName == null) {
18652            if (deleteCodeAndResources && (outInfo != null)) {
18653                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18654                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18655                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18656            }
18657        }
18658
18659        return true;
18660    }
18661
18662    @Override
18663    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18664            int userId) {
18665        mContext.enforceCallingOrSelfPermission(
18666                android.Manifest.permission.DELETE_PACKAGES, null);
18667        synchronized (mPackages) {
18668            // Cannot block uninstall of static shared libs as they are
18669            // considered a part of the using app (emulating static linking).
18670            // Also static libs are installed always on internal storage.
18671            PackageParser.Package pkg = mPackages.get(packageName);
18672            if (pkg != null && pkg.staticSharedLibName != null) {
18673                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18674                        + " providing static shared library: " + pkg.staticSharedLibName);
18675                return false;
18676            }
18677            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18678            mSettings.writePackageRestrictionsLPr(userId);
18679        }
18680        return true;
18681    }
18682
18683    @Override
18684    public boolean getBlockUninstallForUser(String packageName, int userId) {
18685        synchronized (mPackages) {
18686            final PackageSetting ps = mSettings.mPackages.get(packageName);
18687            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18688                return false;
18689            }
18690            return mSettings.getBlockUninstallLPr(userId, packageName);
18691        }
18692    }
18693
18694    @Override
18695    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18696        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18697        synchronized (mPackages) {
18698            PackageSetting ps = mSettings.mPackages.get(packageName);
18699            if (ps == null) {
18700                Log.w(TAG, "Package doesn't exist: " + packageName);
18701                return false;
18702            }
18703            if (systemUserApp) {
18704                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18705            } else {
18706                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18707            }
18708            mSettings.writeLPr();
18709        }
18710        return true;
18711    }
18712
18713    /*
18714     * This method handles package deletion in general
18715     */
18716    private boolean deletePackageLIF(String packageName, UserHandle user,
18717            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18718            PackageRemovedInfo outInfo, boolean writeSettings,
18719            PackageParser.Package replacingPackage) {
18720        if (packageName == null) {
18721            Slog.w(TAG, "Attempt to delete null packageName.");
18722            return false;
18723        }
18724
18725        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18726
18727        PackageSetting ps;
18728        synchronized (mPackages) {
18729            ps = mSettings.mPackages.get(packageName);
18730            if (ps == null) {
18731                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18732                return false;
18733            }
18734
18735            if (ps.parentPackageName != null && (!isSystemApp(ps)
18736                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18737                if (DEBUG_REMOVE) {
18738                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18739                            + ((user == null) ? UserHandle.USER_ALL : user));
18740                }
18741                final int removedUserId = (user != null) ? user.getIdentifier()
18742                        : UserHandle.USER_ALL;
18743                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18744                    return false;
18745                }
18746                markPackageUninstalledForUserLPw(ps, user);
18747                scheduleWritePackageRestrictionsLocked(user);
18748                return true;
18749            }
18750        }
18751
18752        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18753                && user.getIdentifier() != UserHandle.USER_ALL)) {
18754            // The caller is asking that the package only be deleted for a single
18755            // user.  To do this, we just mark its uninstalled state and delete
18756            // its data. If this is a system app, we only allow this to happen if
18757            // they have set the special DELETE_SYSTEM_APP which requests different
18758            // semantics than normal for uninstalling system apps.
18759            markPackageUninstalledForUserLPw(ps, user);
18760
18761            if (!isSystemApp(ps)) {
18762                // Do not uninstall the APK if an app should be cached
18763                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18764                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18765                    // Other user still have this package installed, so all
18766                    // we need to do is clear this user's data and save that
18767                    // it is uninstalled.
18768                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18769                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18770                        return false;
18771                    }
18772                    scheduleWritePackageRestrictionsLocked(user);
18773                    return true;
18774                } else {
18775                    // We need to set it back to 'installed' so the uninstall
18776                    // broadcasts will be sent correctly.
18777                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18778                    ps.setInstalled(true, user.getIdentifier());
18779                    mSettings.writeKernelMappingLPr(ps);
18780                }
18781            } else {
18782                // This is a system app, so we assume that the
18783                // other users still have this package installed, so all
18784                // we need to do is clear this user's data and save that
18785                // it is uninstalled.
18786                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18787                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18788                    return false;
18789                }
18790                scheduleWritePackageRestrictionsLocked(user);
18791                return true;
18792            }
18793        }
18794
18795        // If we are deleting a composite package for all users, keep track
18796        // of result for each child.
18797        if (ps.childPackageNames != null && outInfo != null) {
18798            synchronized (mPackages) {
18799                final int childCount = ps.childPackageNames.size();
18800                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18801                for (int i = 0; i < childCount; i++) {
18802                    String childPackageName = ps.childPackageNames.get(i);
18803                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18804                    childInfo.removedPackage = childPackageName;
18805                    childInfo.installerPackageName = ps.installerPackageName;
18806                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18807                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18808                    if (childPs != null) {
18809                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18810                    }
18811                }
18812            }
18813        }
18814
18815        boolean ret = false;
18816        if (isSystemApp(ps)) {
18817            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18818            // When an updated system application is deleted we delete the existing resources
18819            // as well and fall back to existing code in system partition
18820            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18821        } else {
18822            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18823            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18824                    outInfo, writeSettings, replacingPackage);
18825        }
18826
18827        // Take a note whether we deleted the package for all users
18828        if (outInfo != null) {
18829            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18830            if (outInfo.removedChildPackages != null) {
18831                synchronized (mPackages) {
18832                    final int childCount = outInfo.removedChildPackages.size();
18833                    for (int i = 0; i < childCount; i++) {
18834                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18835                        if (childInfo != null) {
18836                            childInfo.removedForAllUsers = mPackages.get(
18837                                    childInfo.removedPackage) == null;
18838                        }
18839                    }
18840                }
18841            }
18842            // If we uninstalled an update to a system app there may be some
18843            // child packages that appeared as they are declared in the system
18844            // app but were not declared in the update.
18845            if (isSystemApp(ps)) {
18846                synchronized (mPackages) {
18847                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18848                    final int childCount = (updatedPs.childPackageNames != null)
18849                            ? updatedPs.childPackageNames.size() : 0;
18850                    for (int i = 0; i < childCount; i++) {
18851                        String childPackageName = updatedPs.childPackageNames.get(i);
18852                        if (outInfo.removedChildPackages == null
18853                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18854                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18855                            if (childPs == null) {
18856                                continue;
18857                            }
18858                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18859                            installRes.name = childPackageName;
18860                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18861                            installRes.pkg = mPackages.get(childPackageName);
18862                            installRes.uid = childPs.pkg.applicationInfo.uid;
18863                            if (outInfo.appearedChildPackages == null) {
18864                                outInfo.appearedChildPackages = new ArrayMap<>();
18865                            }
18866                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18867                        }
18868                    }
18869                }
18870            }
18871        }
18872
18873        return ret;
18874    }
18875
18876    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18877        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18878                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18879        for (int nextUserId : userIds) {
18880            if (DEBUG_REMOVE) {
18881                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18882            }
18883            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18884                    false /*installed*/,
18885                    true /*stopped*/,
18886                    true /*notLaunched*/,
18887                    false /*hidden*/,
18888                    false /*suspended*/,
18889                    false /*instantApp*/,
18890                    false /*virtualPreload*/,
18891                    null /*lastDisableAppCaller*/,
18892                    null /*enabledComponents*/,
18893                    null /*disabledComponents*/,
18894                    ps.readUserState(nextUserId).domainVerificationStatus,
18895                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18896        }
18897        mSettings.writeKernelMappingLPr(ps);
18898    }
18899
18900    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18901            PackageRemovedInfo outInfo) {
18902        final PackageParser.Package pkg;
18903        synchronized (mPackages) {
18904            pkg = mPackages.get(ps.name);
18905        }
18906
18907        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18908                : new int[] {userId};
18909        for (int nextUserId : userIds) {
18910            if (DEBUG_REMOVE) {
18911                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18912                        + nextUserId);
18913            }
18914
18915            destroyAppDataLIF(pkg, userId,
18916                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18917            destroyAppProfilesLIF(pkg, userId);
18918            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18919            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18920            schedulePackageCleaning(ps.name, nextUserId, false);
18921            synchronized (mPackages) {
18922                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18923                    scheduleWritePackageRestrictionsLocked(nextUserId);
18924                }
18925                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18926            }
18927        }
18928
18929        if (outInfo != null) {
18930            outInfo.removedPackage = ps.name;
18931            outInfo.installerPackageName = ps.installerPackageName;
18932            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18933            outInfo.removedAppId = ps.appId;
18934            outInfo.removedUsers = userIds;
18935            outInfo.broadcastUsers = userIds;
18936        }
18937
18938        return true;
18939    }
18940
18941    private final class ClearStorageConnection implements ServiceConnection {
18942        IMediaContainerService mContainerService;
18943
18944        @Override
18945        public void onServiceConnected(ComponentName name, IBinder service) {
18946            synchronized (this) {
18947                mContainerService = IMediaContainerService.Stub
18948                        .asInterface(Binder.allowBlocking(service));
18949                notifyAll();
18950            }
18951        }
18952
18953        @Override
18954        public void onServiceDisconnected(ComponentName name) {
18955        }
18956    }
18957
18958    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18959        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18960
18961        final boolean mounted;
18962        if (Environment.isExternalStorageEmulated()) {
18963            mounted = true;
18964        } else {
18965            final String status = Environment.getExternalStorageState();
18966
18967            mounted = status.equals(Environment.MEDIA_MOUNTED)
18968                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18969        }
18970
18971        if (!mounted) {
18972            return;
18973        }
18974
18975        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18976        int[] users;
18977        if (userId == UserHandle.USER_ALL) {
18978            users = sUserManager.getUserIds();
18979        } else {
18980            users = new int[] { userId };
18981        }
18982        final ClearStorageConnection conn = new ClearStorageConnection();
18983        if (mContext.bindServiceAsUser(
18984                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18985            try {
18986                for (int curUser : users) {
18987                    long timeout = SystemClock.uptimeMillis() + 5000;
18988                    synchronized (conn) {
18989                        long now;
18990                        while (conn.mContainerService == null &&
18991                                (now = SystemClock.uptimeMillis()) < timeout) {
18992                            try {
18993                                conn.wait(timeout - now);
18994                            } catch (InterruptedException e) {
18995                            }
18996                        }
18997                    }
18998                    if (conn.mContainerService == null) {
18999                        return;
19000                    }
19001
19002                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19003                    clearDirectory(conn.mContainerService,
19004                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19005                    if (allData) {
19006                        clearDirectory(conn.mContainerService,
19007                                userEnv.buildExternalStorageAppDataDirs(packageName));
19008                        clearDirectory(conn.mContainerService,
19009                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19010                    }
19011                }
19012            } finally {
19013                mContext.unbindService(conn);
19014            }
19015        }
19016    }
19017
19018    @Override
19019    public void clearApplicationProfileData(String packageName) {
19020        enforceSystemOrRoot("Only the system can clear all profile data");
19021
19022        final PackageParser.Package pkg;
19023        synchronized (mPackages) {
19024            pkg = mPackages.get(packageName);
19025        }
19026
19027        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19028            synchronized (mInstallLock) {
19029                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19030            }
19031        }
19032    }
19033
19034    @Override
19035    public void clearApplicationUserData(final String packageName,
19036            final IPackageDataObserver observer, final int userId) {
19037        mContext.enforceCallingOrSelfPermission(
19038                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19039
19040        final int callingUid = Binder.getCallingUid();
19041        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19042                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19043
19044        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19045        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19046        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19047            throw new SecurityException("Cannot clear data for a protected package: "
19048                    + packageName);
19049        }
19050        // Queue up an async operation since the package deletion may take a little while.
19051        mHandler.post(new Runnable() {
19052            public void run() {
19053                mHandler.removeCallbacks(this);
19054                final boolean succeeded;
19055                if (!filterApp) {
19056                    try (PackageFreezer freezer = freezePackage(packageName,
19057                            "clearApplicationUserData")) {
19058                        synchronized (mInstallLock) {
19059                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19060                        }
19061                        clearExternalStorageDataSync(packageName, userId, true);
19062                        synchronized (mPackages) {
19063                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19064                                    packageName, userId);
19065                        }
19066                    }
19067                    if (succeeded) {
19068                        // invoke DeviceStorageMonitor's update method to clear any notifications
19069                        DeviceStorageMonitorInternal dsm = LocalServices
19070                                .getService(DeviceStorageMonitorInternal.class);
19071                        if (dsm != null) {
19072                            dsm.checkMemory();
19073                        }
19074                    }
19075                } else {
19076                    succeeded = false;
19077                }
19078                if (observer != null) {
19079                    try {
19080                        observer.onRemoveCompleted(packageName, succeeded);
19081                    } catch (RemoteException e) {
19082                        Log.i(TAG, "Observer no longer exists.");
19083                    }
19084                } //end if observer
19085            } //end run
19086        });
19087    }
19088
19089    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19090        if (packageName == null) {
19091            Slog.w(TAG, "Attempt to delete null packageName.");
19092            return false;
19093        }
19094
19095        // Try finding details about the requested package
19096        PackageParser.Package pkg;
19097        synchronized (mPackages) {
19098            pkg = mPackages.get(packageName);
19099            if (pkg == null) {
19100                final PackageSetting ps = mSettings.mPackages.get(packageName);
19101                if (ps != null) {
19102                    pkg = ps.pkg;
19103                }
19104            }
19105
19106            if (pkg == null) {
19107                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19108                return false;
19109            }
19110
19111            PackageSetting ps = (PackageSetting) pkg.mExtras;
19112            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19113        }
19114
19115        clearAppDataLIF(pkg, userId,
19116                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19117
19118        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19119        removeKeystoreDataIfNeeded(userId, appId);
19120
19121        UserManagerInternal umInternal = getUserManagerInternal();
19122        final int flags;
19123        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19124            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19125        } else if (umInternal.isUserRunning(userId)) {
19126            flags = StorageManager.FLAG_STORAGE_DE;
19127        } else {
19128            flags = 0;
19129        }
19130        prepareAppDataContentsLIF(pkg, userId, flags);
19131
19132        return true;
19133    }
19134
19135    /**
19136     * Reverts user permission state changes (permissions and flags) in
19137     * all packages for a given user.
19138     *
19139     * @param userId The device user for which to do a reset.
19140     */
19141    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19142        final int packageCount = mPackages.size();
19143        for (int i = 0; i < packageCount; i++) {
19144            PackageParser.Package pkg = mPackages.valueAt(i);
19145            PackageSetting ps = (PackageSetting) pkg.mExtras;
19146            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19147        }
19148    }
19149
19150    private void resetNetworkPolicies(int userId) {
19151        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19152    }
19153
19154    /**
19155     * Reverts user permission state changes (permissions and flags).
19156     *
19157     * @param ps The package for which to reset.
19158     * @param userId The device user for which to do a reset.
19159     */
19160    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19161            final PackageSetting ps, final int userId) {
19162        if (ps.pkg == null) {
19163            return;
19164        }
19165
19166        // These are flags that can change base on user actions.
19167        final int userSettableMask = FLAG_PERMISSION_USER_SET
19168                | FLAG_PERMISSION_USER_FIXED
19169                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19170                | FLAG_PERMISSION_REVIEW_REQUIRED;
19171
19172        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19173                | FLAG_PERMISSION_POLICY_FIXED;
19174
19175        boolean writeInstallPermissions = false;
19176        boolean writeRuntimePermissions = false;
19177
19178        final int permissionCount = ps.pkg.requestedPermissions.size();
19179        for (int i = 0; i < permissionCount; i++) {
19180            final String permName = ps.pkg.requestedPermissions.get(i);
19181            final BasePermission bp =
19182                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19183            if (bp == null) {
19184                continue;
19185            }
19186
19187            // If shared user we just reset the state to which only this app contributed.
19188            if (ps.sharedUser != null) {
19189                boolean used = false;
19190                final int packageCount = ps.sharedUser.packages.size();
19191                for (int j = 0; j < packageCount; j++) {
19192                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19193                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19194                            && pkg.pkg.requestedPermissions.contains(permName)) {
19195                        used = true;
19196                        break;
19197                    }
19198                }
19199                if (used) {
19200                    continue;
19201                }
19202            }
19203
19204            final PermissionsState permissionsState = ps.getPermissionsState();
19205
19206            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19207
19208            // Always clear the user settable flags.
19209            final boolean hasInstallState =
19210                    permissionsState.getInstallPermissionState(permName) != null;
19211            // If permission review is enabled and this is a legacy app, mark the
19212            // permission as requiring a review as this is the initial state.
19213            int flags = 0;
19214            if (mPermissionReviewRequired
19215                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19216                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19217            }
19218            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19219                if (hasInstallState) {
19220                    writeInstallPermissions = true;
19221                } else {
19222                    writeRuntimePermissions = true;
19223                }
19224            }
19225
19226            // Below is only runtime permission handling.
19227            if (!bp.isRuntime()) {
19228                continue;
19229            }
19230
19231            // Never clobber system or policy.
19232            if ((oldFlags & policyOrSystemFlags) != 0) {
19233                continue;
19234            }
19235
19236            // If this permission was granted by default, make sure it is.
19237            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19238                if (permissionsState.grantRuntimePermission(bp, userId)
19239                        != PERMISSION_OPERATION_FAILURE) {
19240                    writeRuntimePermissions = true;
19241                }
19242            // If permission review is enabled the permissions for a legacy apps
19243            // are represented as constantly granted runtime ones, so don't revoke.
19244            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19245                // Otherwise, reset the permission.
19246                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19247                switch (revokeResult) {
19248                    case PERMISSION_OPERATION_SUCCESS:
19249                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19250                        writeRuntimePermissions = true;
19251                        final int appId = ps.appId;
19252                        mHandler.post(new Runnable() {
19253                            @Override
19254                            public void run() {
19255                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19256                            }
19257                        });
19258                    } break;
19259                }
19260            }
19261        }
19262
19263        // Synchronously write as we are taking permissions away.
19264        if (writeRuntimePermissions) {
19265            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19266        }
19267
19268        // Synchronously write as we are taking permissions away.
19269        if (writeInstallPermissions) {
19270            mSettings.writeLPr();
19271        }
19272    }
19273
19274    /**
19275     * Remove entries from the keystore daemon. Will only remove it if the
19276     * {@code appId} is valid.
19277     */
19278    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19279        if (appId < 0) {
19280            return;
19281        }
19282
19283        final KeyStore keyStore = KeyStore.getInstance();
19284        if (keyStore != null) {
19285            if (userId == UserHandle.USER_ALL) {
19286                for (final int individual : sUserManager.getUserIds()) {
19287                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19288                }
19289            } else {
19290                keyStore.clearUid(UserHandle.getUid(userId, appId));
19291            }
19292        } else {
19293            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19294        }
19295    }
19296
19297    @Override
19298    public void deleteApplicationCacheFiles(final String packageName,
19299            final IPackageDataObserver observer) {
19300        final int userId = UserHandle.getCallingUserId();
19301        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19302    }
19303
19304    @Override
19305    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19306            final IPackageDataObserver observer) {
19307        final int callingUid = Binder.getCallingUid();
19308        mContext.enforceCallingOrSelfPermission(
19309                android.Manifest.permission.DELETE_CACHE_FILES, null);
19310        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19311                /* requireFullPermission= */ true, /* checkShell= */ false,
19312                "delete application cache files");
19313        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19314                android.Manifest.permission.ACCESS_INSTANT_APPS);
19315
19316        final PackageParser.Package pkg;
19317        synchronized (mPackages) {
19318            pkg = mPackages.get(packageName);
19319        }
19320
19321        // Queue up an async operation since the package deletion may take a little while.
19322        mHandler.post(new Runnable() {
19323            public void run() {
19324                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19325                boolean doClearData = true;
19326                if (ps != null) {
19327                    final boolean targetIsInstantApp =
19328                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19329                    doClearData = !targetIsInstantApp
19330                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19331                }
19332                if (doClearData) {
19333                    synchronized (mInstallLock) {
19334                        final int flags = StorageManager.FLAG_STORAGE_DE
19335                                | StorageManager.FLAG_STORAGE_CE;
19336                        // We're only clearing cache files, so we don't care if the
19337                        // app is unfrozen and still able to run
19338                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19339                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19340                    }
19341                    clearExternalStorageDataSync(packageName, userId, false);
19342                }
19343                if (observer != null) {
19344                    try {
19345                        observer.onRemoveCompleted(packageName, true);
19346                    } catch (RemoteException e) {
19347                        Log.i(TAG, "Observer no longer exists.");
19348                    }
19349                }
19350            }
19351        });
19352    }
19353
19354    @Override
19355    public void getPackageSizeInfo(final String packageName, int userHandle,
19356            final IPackageStatsObserver observer) {
19357        throw new UnsupportedOperationException(
19358                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19359    }
19360
19361    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19362        final PackageSetting ps;
19363        synchronized (mPackages) {
19364            ps = mSettings.mPackages.get(packageName);
19365            if (ps == null) {
19366                Slog.w(TAG, "Failed to find settings for " + packageName);
19367                return false;
19368            }
19369        }
19370
19371        final String[] packageNames = { packageName };
19372        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19373        final String[] codePaths = { ps.codePathString };
19374
19375        try {
19376            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19377                    ps.appId, ceDataInodes, codePaths, stats);
19378
19379            // For now, ignore code size of packages on system partition
19380            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19381                stats.codeSize = 0;
19382            }
19383
19384            // External clients expect these to be tracked separately
19385            stats.dataSize -= stats.cacheSize;
19386
19387        } catch (InstallerException e) {
19388            Slog.w(TAG, String.valueOf(e));
19389            return false;
19390        }
19391
19392        return true;
19393    }
19394
19395    private int getUidTargetSdkVersionLockedLPr(int uid) {
19396        Object obj = mSettings.getUserIdLPr(uid);
19397        if (obj instanceof SharedUserSetting) {
19398            final SharedUserSetting sus = (SharedUserSetting) obj;
19399            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19400            final Iterator<PackageSetting> it = sus.packages.iterator();
19401            while (it.hasNext()) {
19402                final PackageSetting ps = it.next();
19403                if (ps.pkg != null) {
19404                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19405                    if (v < vers) vers = v;
19406                }
19407            }
19408            return vers;
19409        } else if (obj instanceof PackageSetting) {
19410            final PackageSetting ps = (PackageSetting) obj;
19411            if (ps.pkg != null) {
19412                return ps.pkg.applicationInfo.targetSdkVersion;
19413            }
19414        }
19415        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19416    }
19417
19418    @Override
19419    public void addPreferredActivity(IntentFilter filter, int match,
19420            ComponentName[] set, ComponentName activity, int userId) {
19421        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19422                "Adding preferred");
19423    }
19424
19425    private void addPreferredActivityInternal(IntentFilter filter, int match,
19426            ComponentName[] set, ComponentName activity, boolean always, int userId,
19427            String opname) {
19428        // writer
19429        int callingUid = Binder.getCallingUid();
19430        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19431                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19432        if (filter.countActions() == 0) {
19433            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19434            return;
19435        }
19436        synchronized (mPackages) {
19437            if (mContext.checkCallingOrSelfPermission(
19438                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19439                    != PackageManager.PERMISSION_GRANTED) {
19440                if (getUidTargetSdkVersionLockedLPr(callingUid)
19441                        < Build.VERSION_CODES.FROYO) {
19442                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19443                            + callingUid);
19444                    return;
19445                }
19446                mContext.enforceCallingOrSelfPermission(
19447                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19448            }
19449
19450            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19451            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19452                    + userId + ":");
19453            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19454            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19455            scheduleWritePackageRestrictionsLocked(userId);
19456            postPreferredActivityChangedBroadcast(userId);
19457        }
19458    }
19459
19460    private void postPreferredActivityChangedBroadcast(int userId) {
19461        mHandler.post(() -> {
19462            final IActivityManager am = ActivityManager.getService();
19463            if (am == null) {
19464                return;
19465            }
19466
19467            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19468            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19469            try {
19470                am.broadcastIntent(null, intent, null, null,
19471                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19472                        null, false, false, userId);
19473            } catch (RemoteException e) {
19474            }
19475        });
19476    }
19477
19478    @Override
19479    public void replacePreferredActivity(IntentFilter filter, int match,
19480            ComponentName[] set, ComponentName activity, int userId) {
19481        if (filter.countActions() != 1) {
19482            throw new IllegalArgumentException(
19483                    "replacePreferredActivity expects filter to have only 1 action.");
19484        }
19485        if (filter.countDataAuthorities() != 0
19486                || filter.countDataPaths() != 0
19487                || filter.countDataSchemes() > 1
19488                || filter.countDataTypes() != 0) {
19489            throw new IllegalArgumentException(
19490                    "replacePreferredActivity expects filter to have no data authorities, " +
19491                    "paths, or types; and at most one scheme.");
19492        }
19493
19494        final int callingUid = Binder.getCallingUid();
19495        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19496                true /* requireFullPermission */, false /* checkShell */,
19497                "replace preferred activity");
19498        synchronized (mPackages) {
19499            if (mContext.checkCallingOrSelfPermission(
19500                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19501                    != PackageManager.PERMISSION_GRANTED) {
19502                if (getUidTargetSdkVersionLockedLPr(callingUid)
19503                        < Build.VERSION_CODES.FROYO) {
19504                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19505                            + Binder.getCallingUid());
19506                    return;
19507                }
19508                mContext.enforceCallingOrSelfPermission(
19509                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19510            }
19511
19512            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19513            if (pir != null) {
19514                // Get all of the existing entries that exactly match this filter.
19515                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19516                if (existing != null && existing.size() == 1) {
19517                    PreferredActivity cur = existing.get(0);
19518                    if (DEBUG_PREFERRED) {
19519                        Slog.i(TAG, "Checking replace of preferred:");
19520                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19521                        if (!cur.mPref.mAlways) {
19522                            Slog.i(TAG, "  -- CUR; not mAlways!");
19523                        } else {
19524                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19525                            Slog.i(TAG, "  -- CUR: mSet="
19526                                    + Arrays.toString(cur.mPref.mSetComponents));
19527                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19528                            Slog.i(TAG, "  -- NEW: mMatch="
19529                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19530                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19531                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19532                        }
19533                    }
19534                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19535                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19536                            && cur.mPref.sameSet(set)) {
19537                        // Setting the preferred activity to what it happens to be already
19538                        if (DEBUG_PREFERRED) {
19539                            Slog.i(TAG, "Replacing with same preferred activity "
19540                                    + cur.mPref.mShortComponent + " for user "
19541                                    + userId + ":");
19542                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19543                        }
19544                        return;
19545                    }
19546                }
19547
19548                if (existing != null) {
19549                    if (DEBUG_PREFERRED) {
19550                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19551                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19552                    }
19553                    for (int i = 0; i < existing.size(); i++) {
19554                        PreferredActivity pa = existing.get(i);
19555                        if (DEBUG_PREFERRED) {
19556                            Slog.i(TAG, "Removing existing preferred activity "
19557                                    + pa.mPref.mComponent + ":");
19558                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19559                        }
19560                        pir.removeFilter(pa);
19561                    }
19562                }
19563            }
19564            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19565                    "Replacing preferred");
19566        }
19567    }
19568
19569    @Override
19570    public void clearPackagePreferredActivities(String packageName) {
19571        final int callingUid = Binder.getCallingUid();
19572        if (getInstantAppPackageName(callingUid) != null) {
19573            return;
19574        }
19575        // writer
19576        synchronized (mPackages) {
19577            PackageParser.Package pkg = mPackages.get(packageName);
19578            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19579                if (mContext.checkCallingOrSelfPermission(
19580                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19581                        != PackageManager.PERMISSION_GRANTED) {
19582                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19583                            < Build.VERSION_CODES.FROYO) {
19584                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19585                                + callingUid);
19586                        return;
19587                    }
19588                    mContext.enforceCallingOrSelfPermission(
19589                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19590                }
19591            }
19592            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19593            if (ps != null
19594                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19595                return;
19596            }
19597            int user = UserHandle.getCallingUserId();
19598            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19599                scheduleWritePackageRestrictionsLocked(user);
19600            }
19601        }
19602    }
19603
19604    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19605    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19606        ArrayList<PreferredActivity> removed = null;
19607        boolean changed = false;
19608        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19609            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19610            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19611            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19612                continue;
19613            }
19614            Iterator<PreferredActivity> it = pir.filterIterator();
19615            while (it.hasNext()) {
19616                PreferredActivity pa = it.next();
19617                // Mark entry for removal only if it matches the package name
19618                // and the entry is of type "always".
19619                if (packageName == null ||
19620                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19621                                && pa.mPref.mAlways)) {
19622                    if (removed == null) {
19623                        removed = new ArrayList<PreferredActivity>();
19624                    }
19625                    removed.add(pa);
19626                }
19627            }
19628            if (removed != null) {
19629                for (int j=0; j<removed.size(); j++) {
19630                    PreferredActivity pa = removed.get(j);
19631                    pir.removeFilter(pa);
19632                }
19633                changed = true;
19634            }
19635        }
19636        if (changed) {
19637            postPreferredActivityChangedBroadcast(userId);
19638        }
19639        return changed;
19640    }
19641
19642    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19643    private void clearIntentFilterVerificationsLPw(int userId) {
19644        final int packageCount = mPackages.size();
19645        for (int i = 0; i < packageCount; i++) {
19646            PackageParser.Package pkg = mPackages.valueAt(i);
19647            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19648        }
19649    }
19650
19651    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19652    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19653        if (userId == UserHandle.USER_ALL) {
19654            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19655                    sUserManager.getUserIds())) {
19656                for (int oneUserId : sUserManager.getUserIds()) {
19657                    scheduleWritePackageRestrictionsLocked(oneUserId);
19658                }
19659            }
19660        } else {
19661            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19662                scheduleWritePackageRestrictionsLocked(userId);
19663            }
19664        }
19665    }
19666
19667    /** Clears state for all users, and touches intent filter verification policy */
19668    void clearDefaultBrowserIfNeeded(String packageName) {
19669        for (int oneUserId : sUserManager.getUserIds()) {
19670            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19671        }
19672    }
19673
19674    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19675        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19676        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19677            if (packageName.equals(defaultBrowserPackageName)) {
19678                setDefaultBrowserPackageName(null, userId);
19679            }
19680        }
19681    }
19682
19683    @Override
19684    public void resetApplicationPreferences(int userId) {
19685        mContext.enforceCallingOrSelfPermission(
19686                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19687        final long identity = Binder.clearCallingIdentity();
19688        // writer
19689        try {
19690            synchronized (mPackages) {
19691                clearPackagePreferredActivitiesLPw(null, userId);
19692                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19693                // TODO: We have to reset the default SMS and Phone. This requires
19694                // significant refactoring to keep all default apps in the package
19695                // manager (cleaner but more work) or have the services provide
19696                // callbacks to the package manager to request a default app reset.
19697                applyFactoryDefaultBrowserLPw(userId);
19698                clearIntentFilterVerificationsLPw(userId);
19699                primeDomainVerificationsLPw(userId);
19700                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19701                scheduleWritePackageRestrictionsLocked(userId);
19702            }
19703            resetNetworkPolicies(userId);
19704        } finally {
19705            Binder.restoreCallingIdentity(identity);
19706        }
19707    }
19708
19709    @Override
19710    public int getPreferredActivities(List<IntentFilter> outFilters,
19711            List<ComponentName> outActivities, String packageName) {
19712        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19713            return 0;
19714        }
19715        int num = 0;
19716        final int userId = UserHandle.getCallingUserId();
19717        // reader
19718        synchronized (mPackages) {
19719            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19720            if (pir != null) {
19721                final Iterator<PreferredActivity> it = pir.filterIterator();
19722                while (it.hasNext()) {
19723                    final PreferredActivity pa = it.next();
19724                    if (packageName == null
19725                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19726                                    && pa.mPref.mAlways)) {
19727                        if (outFilters != null) {
19728                            outFilters.add(new IntentFilter(pa));
19729                        }
19730                        if (outActivities != null) {
19731                            outActivities.add(pa.mPref.mComponent);
19732                        }
19733                    }
19734                }
19735            }
19736        }
19737
19738        return num;
19739    }
19740
19741    @Override
19742    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19743            int userId) {
19744        int callingUid = Binder.getCallingUid();
19745        if (callingUid != Process.SYSTEM_UID) {
19746            throw new SecurityException(
19747                    "addPersistentPreferredActivity can only be run by the system");
19748        }
19749        if (filter.countActions() == 0) {
19750            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19751            return;
19752        }
19753        synchronized (mPackages) {
19754            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19755                    ":");
19756            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19757            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19758                    new PersistentPreferredActivity(filter, activity));
19759            scheduleWritePackageRestrictionsLocked(userId);
19760            postPreferredActivityChangedBroadcast(userId);
19761        }
19762    }
19763
19764    @Override
19765    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19766        int callingUid = Binder.getCallingUid();
19767        if (callingUid != Process.SYSTEM_UID) {
19768            throw new SecurityException(
19769                    "clearPackagePersistentPreferredActivities can only be run by the system");
19770        }
19771        ArrayList<PersistentPreferredActivity> removed = null;
19772        boolean changed = false;
19773        synchronized (mPackages) {
19774            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19775                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19776                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19777                        .valueAt(i);
19778                if (userId != thisUserId) {
19779                    continue;
19780                }
19781                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19782                while (it.hasNext()) {
19783                    PersistentPreferredActivity ppa = it.next();
19784                    // Mark entry for removal only if it matches the package name.
19785                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19786                        if (removed == null) {
19787                            removed = new ArrayList<PersistentPreferredActivity>();
19788                        }
19789                        removed.add(ppa);
19790                    }
19791                }
19792                if (removed != null) {
19793                    for (int j=0; j<removed.size(); j++) {
19794                        PersistentPreferredActivity ppa = removed.get(j);
19795                        ppir.removeFilter(ppa);
19796                    }
19797                    changed = true;
19798                }
19799            }
19800
19801            if (changed) {
19802                scheduleWritePackageRestrictionsLocked(userId);
19803                postPreferredActivityChangedBroadcast(userId);
19804            }
19805        }
19806    }
19807
19808    /**
19809     * Common machinery for picking apart a restored XML blob and passing
19810     * it to a caller-supplied functor to be applied to the running system.
19811     */
19812    private void restoreFromXml(XmlPullParser parser, int userId,
19813            String expectedStartTag, BlobXmlRestorer functor)
19814            throws IOException, XmlPullParserException {
19815        int type;
19816        while ((type = parser.next()) != XmlPullParser.START_TAG
19817                && type != XmlPullParser.END_DOCUMENT) {
19818        }
19819        if (type != XmlPullParser.START_TAG) {
19820            // oops didn't find a start tag?!
19821            if (DEBUG_BACKUP) {
19822                Slog.e(TAG, "Didn't find start tag during restore");
19823            }
19824            return;
19825        }
19826Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19827        // this is supposed to be TAG_PREFERRED_BACKUP
19828        if (!expectedStartTag.equals(parser.getName())) {
19829            if (DEBUG_BACKUP) {
19830                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19831            }
19832            return;
19833        }
19834
19835        // skip interfering stuff, then we're aligned with the backing implementation
19836        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19837Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19838        functor.apply(parser, userId);
19839    }
19840
19841    private interface BlobXmlRestorer {
19842        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19843    }
19844
19845    /**
19846     * Non-Binder method, support for the backup/restore mechanism: write the
19847     * full set of preferred activities in its canonical XML format.  Returns the
19848     * XML output as a byte array, or null if there is none.
19849     */
19850    @Override
19851    public byte[] getPreferredActivityBackup(int userId) {
19852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19853            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19854        }
19855
19856        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19857        try {
19858            final XmlSerializer serializer = new FastXmlSerializer();
19859            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19860            serializer.startDocument(null, true);
19861            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19862
19863            synchronized (mPackages) {
19864                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19865            }
19866
19867            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19868            serializer.endDocument();
19869            serializer.flush();
19870        } catch (Exception e) {
19871            if (DEBUG_BACKUP) {
19872                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19873            }
19874            return null;
19875        }
19876
19877        return dataStream.toByteArray();
19878    }
19879
19880    @Override
19881    public void restorePreferredActivities(byte[] backup, int userId) {
19882        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19883            throw new SecurityException("Only the system may call restorePreferredActivities()");
19884        }
19885
19886        try {
19887            final XmlPullParser parser = Xml.newPullParser();
19888            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19889            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19890                    new BlobXmlRestorer() {
19891                        @Override
19892                        public void apply(XmlPullParser parser, int userId)
19893                                throws XmlPullParserException, IOException {
19894                            synchronized (mPackages) {
19895                                mSettings.readPreferredActivitiesLPw(parser, userId);
19896                            }
19897                        }
19898                    } );
19899        } catch (Exception e) {
19900            if (DEBUG_BACKUP) {
19901                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19902            }
19903        }
19904    }
19905
19906    /**
19907     * Non-Binder method, support for the backup/restore mechanism: write the
19908     * default browser (etc) settings in its canonical XML format.  Returns the default
19909     * browser XML representation as a byte array, or null if there is none.
19910     */
19911    @Override
19912    public byte[] getDefaultAppsBackup(int userId) {
19913        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19914            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19915        }
19916
19917        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19918        try {
19919            final XmlSerializer serializer = new FastXmlSerializer();
19920            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19921            serializer.startDocument(null, true);
19922            serializer.startTag(null, TAG_DEFAULT_APPS);
19923
19924            synchronized (mPackages) {
19925                mSettings.writeDefaultAppsLPr(serializer, userId);
19926            }
19927
19928            serializer.endTag(null, TAG_DEFAULT_APPS);
19929            serializer.endDocument();
19930            serializer.flush();
19931        } catch (Exception e) {
19932            if (DEBUG_BACKUP) {
19933                Slog.e(TAG, "Unable to write default apps for backup", e);
19934            }
19935            return null;
19936        }
19937
19938        return dataStream.toByteArray();
19939    }
19940
19941    @Override
19942    public void restoreDefaultApps(byte[] backup, int userId) {
19943        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19944            throw new SecurityException("Only the system may call restoreDefaultApps()");
19945        }
19946
19947        try {
19948            final XmlPullParser parser = Xml.newPullParser();
19949            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19950            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19951                    new BlobXmlRestorer() {
19952                        @Override
19953                        public void apply(XmlPullParser parser, int userId)
19954                                throws XmlPullParserException, IOException {
19955                            synchronized (mPackages) {
19956                                mSettings.readDefaultAppsLPw(parser, userId);
19957                            }
19958                        }
19959                    } );
19960        } catch (Exception e) {
19961            if (DEBUG_BACKUP) {
19962                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19963            }
19964        }
19965    }
19966
19967    @Override
19968    public byte[] getIntentFilterVerificationBackup(int userId) {
19969        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19970            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19971        }
19972
19973        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19974        try {
19975            final XmlSerializer serializer = new FastXmlSerializer();
19976            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19977            serializer.startDocument(null, true);
19978            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19979
19980            synchronized (mPackages) {
19981                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19982            }
19983
19984            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19985            serializer.endDocument();
19986            serializer.flush();
19987        } catch (Exception e) {
19988            if (DEBUG_BACKUP) {
19989                Slog.e(TAG, "Unable to write default apps for backup", e);
19990            }
19991            return null;
19992        }
19993
19994        return dataStream.toByteArray();
19995    }
19996
19997    @Override
19998    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19999        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20000            throw new SecurityException("Only the system may call restorePreferredActivities()");
20001        }
20002
20003        try {
20004            final XmlPullParser parser = Xml.newPullParser();
20005            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20006            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20007                    new BlobXmlRestorer() {
20008                        @Override
20009                        public void apply(XmlPullParser parser, int userId)
20010                                throws XmlPullParserException, IOException {
20011                            synchronized (mPackages) {
20012                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20013                                mSettings.writeLPr();
20014                            }
20015                        }
20016                    } );
20017        } catch (Exception e) {
20018            if (DEBUG_BACKUP) {
20019                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20020            }
20021        }
20022    }
20023
20024    @Override
20025    public byte[] getPermissionGrantBackup(int userId) {
20026        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20027            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20028        }
20029
20030        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20031        try {
20032            final XmlSerializer serializer = new FastXmlSerializer();
20033            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20034            serializer.startDocument(null, true);
20035            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20036
20037            synchronized (mPackages) {
20038                serializeRuntimePermissionGrantsLPr(serializer, userId);
20039            }
20040
20041            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20042            serializer.endDocument();
20043            serializer.flush();
20044        } catch (Exception e) {
20045            if (DEBUG_BACKUP) {
20046                Slog.e(TAG, "Unable to write default apps for backup", e);
20047            }
20048            return null;
20049        }
20050
20051        return dataStream.toByteArray();
20052    }
20053
20054    @Override
20055    public void restorePermissionGrants(byte[] backup, int userId) {
20056        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20057            throw new SecurityException("Only the system may call restorePermissionGrants()");
20058        }
20059
20060        try {
20061            final XmlPullParser parser = Xml.newPullParser();
20062            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20063            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20064                    new BlobXmlRestorer() {
20065                        @Override
20066                        public void apply(XmlPullParser parser, int userId)
20067                                throws XmlPullParserException, IOException {
20068                            synchronized (mPackages) {
20069                                processRestoredPermissionGrantsLPr(parser, userId);
20070                            }
20071                        }
20072                    } );
20073        } catch (Exception e) {
20074            if (DEBUG_BACKUP) {
20075                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20076            }
20077        }
20078    }
20079
20080    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20081            throws IOException {
20082        serializer.startTag(null, TAG_ALL_GRANTS);
20083
20084        final int N = mSettings.mPackages.size();
20085        for (int i = 0; i < N; i++) {
20086            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20087            boolean pkgGrantsKnown = false;
20088
20089            PermissionsState packagePerms = ps.getPermissionsState();
20090
20091            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20092                final int grantFlags = state.getFlags();
20093                // only look at grants that are not system/policy fixed
20094                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20095                    final boolean isGranted = state.isGranted();
20096                    // And only back up the user-twiddled state bits
20097                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20098                        final String packageName = mSettings.mPackages.keyAt(i);
20099                        if (!pkgGrantsKnown) {
20100                            serializer.startTag(null, TAG_GRANT);
20101                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20102                            pkgGrantsKnown = true;
20103                        }
20104
20105                        final boolean userSet =
20106                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20107                        final boolean userFixed =
20108                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20109                        final boolean revoke =
20110                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20111
20112                        serializer.startTag(null, TAG_PERMISSION);
20113                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20114                        if (isGranted) {
20115                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20116                        }
20117                        if (userSet) {
20118                            serializer.attribute(null, ATTR_USER_SET, "true");
20119                        }
20120                        if (userFixed) {
20121                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20122                        }
20123                        if (revoke) {
20124                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20125                        }
20126                        serializer.endTag(null, TAG_PERMISSION);
20127                    }
20128                }
20129            }
20130
20131            if (pkgGrantsKnown) {
20132                serializer.endTag(null, TAG_GRANT);
20133            }
20134        }
20135
20136        serializer.endTag(null, TAG_ALL_GRANTS);
20137    }
20138
20139    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20140            throws XmlPullParserException, IOException {
20141        String pkgName = null;
20142        int outerDepth = parser.getDepth();
20143        int type;
20144        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20145                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20146            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20147                continue;
20148            }
20149
20150            final String tagName = parser.getName();
20151            if (tagName.equals(TAG_GRANT)) {
20152                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20153                if (DEBUG_BACKUP) {
20154                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20155                }
20156            } else if (tagName.equals(TAG_PERMISSION)) {
20157
20158                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20159                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20160
20161                int newFlagSet = 0;
20162                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20163                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20164                }
20165                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20166                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20167                }
20168                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20169                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20170                }
20171                if (DEBUG_BACKUP) {
20172                    Slog.v(TAG, "  + Restoring grant:"
20173                            + " pkg=" + pkgName
20174                            + " perm=" + permName
20175                            + " granted=" + isGranted
20176                            + " bits=0x" + Integer.toHexString(newFlagSet));
20177                }
20178                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20179                if (ps != null) {
20180                    // Already installed so we apply the grant immediately
20181                    if (DEBUG_BACKUP) {
20182                        Slog.v(TAG, "        + already installed; applying");
20183                    }
20184                    PermissionsState perms = ps.getPermissionsState();
20185                    BasePermission bp =
20186                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20187                    if (bp != null) {
20188                        if (isGranted) {
20189                            perms.grantRuntimePermission(bp, userId);
20190                        }
20191                        if (newFlagSet != 0) {
20192                            perms.updatePermissionFlags(
20193                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20194                        }
20195                    }
20196                } else {
20197                    // Need to wait for post-restore install to apply the grant
20198                    if (DEBUG_BACKUP) {
20199                        Slog.v(TAG, "        - not yet installed; saving for later");
20200                    }
20201                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20202                            isGranted, newFlagSet, userId);
20203                }
20204            } else {
20205                PackageManagerService.reportSettingsProblem(Log.WARN,
20206                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20207                XmlUtils.skipCurrentTag(parser);
20208            }
20209        }
20210
20211        scheduleWriteSettingsLocked();
20212        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20213    }
20214
20215    @Override
20216    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20217            int sourceUserId, int targetUserId, int flags) {
20218        mContext.enforceCallingOrSelfPermission(
20219                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20220        int callingUid = Binder.getCallingUid();
20221        enforceOwnerRights(ownerPackage, callingUid);
20222        PackageManagerServiceUtils.enforceShellRestriction(
20223                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20224        if (intentFilter.countActions() == 0) {
20225            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20226            return;
20227        }
20228        synchronized (mPackages) {
20229            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20230                    ownerPackage, targetUserId, flags);
20231            CrossProfileIntentResolver resolver =
20232                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20233            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20234            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20235            if (existing != null) {
20236                int size = existing.size();
20237                for (int i = 0; i < size; i++) {
20238                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20239                        return;
20240                    }
20241                }
20242            }
20243            resolver.addFilter(newFilter);
20244            scheduleWritePackageRestrictionsLocked(sourceUserId);
20245        }
20246    }
20247
20248    @Override
20249    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20250        mContext.enforceCallingOrSelfPermission(
20251                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20252        final int callingUid = Binder.getCallingUid();
20253        enforceOwnerRights(ownerPackage, callingUid);
20254        PackageManagerServiceUtils.enforceShellRestriction(
20255                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20256        synchronized (mPackages) {
20257            CrossProfileIntentResolver resolver =
20258                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20259            ArraySet<CrossProfileIntentFilter> set =
20260                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20261            for (CrossProfileIntentFilter filter : set) {
20262                if (filter.getOwnerPackage().equals(ownerPackage)) {
20263                    resolver.removeFilter(filter);
20264                }
20265            }
20266            scheduleWritePackageRestrictionsLocked(sourceUserId);
20267        }
20268    }
20269
20270    // Enforcing that callingUid is owning pkg on userId
20271    private void enforceOwnerRights(String pkg, int callingUid) {
20272        // The system owns everything.
20273        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20274            return;
20275        }
20276        final int callingUserId = UserHandle.getUserId(callingUid);
20277        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20278        if (pi == null) {
20279            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20280                    + callingUserId);
20281        }
20282        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20283            throw new SecurityException("Calling uid " + callingUid
20284                    + " does not own package " + pkg);
20285        }
20286    }
20287
20288    @Override
20289    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20290        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20291            return null;
20292        }
20293        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20294    }
20295
20296    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20297        UserManagerService ums = UserManagerService.getInstance();
20298        if (ums != null) {
20299            final UserInfo parent = ums.getProfileParent(userId);
20300            final int launcherUid = (parent != null) ? parent.id : userId;
20301            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20302            if (launcherComponent != null) {
20303                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20304                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20305                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20306                        .setPackage(launcherComponent.getPackageName());
20307                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20308            }
20309        }
20310    }
20311
20312    /**
20313     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20314     * then reports the most likely home activity or null if there are more than one.
20315     */
20316    private ComponentName getDefaultHomeActivity(int userId) {
20317        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20318        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20319        if (cn != null) {
20320            return cn;
20321        }
20322
20323        // Find the launcher with the highest priority and return that component if there are no
20324        // other home activity with the same priority.
20325        int lastPriority = Integer.MIN_VALUE;
20326        ComponentName lastComponent = null;
20327        final int size = allHomeCandidates.size();
20328        for (int i = 0; i < size; i++) {
20329            final ResolveInfo ri = allHomeCandidates.get(i);
20330            if (ri.priority > lastPriority) {
20331                lastComponent = ri.activityInfo.getComponentName();
20332                lastPriority = ri.priority;
20333            } else if (ri.priority == lastPriority) {
20334                // Two components found with same priority.
20335                lastComponent = null;
20336            }
20337        }
20338        return lastComponent;
20339    }
20340
20341    private Intent getHomeIntent() {
20342        Intent intent = new Intent(Intent.ACTION_MAIN);
20343        intent.addCategory(Intent.CATEGORY_HOME);
20344        intent.addCategory(Intent.CATEGORY_DEFAULT);
20345        return intent;
20346    }
20347
20348    private IntentFilter getHomeFilter() {
20349        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20350        filter.addCategory(Intent.CATEGORY_HOME);
20351        filter.addCategory(Intent.CATEGORY_DEFAULT);
20352        return filter;
20353    }
20354
20355    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20356            int userId) {
20357        Intent intent  = getHomeIntent();
20358        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20359                PackageManager.GET_META_DATA, userId);
20360        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20361                true, false, false, userId);
20362
20363        allHomeCandidates.clear();
20364        if (list != null) {
20365            for (ResolveInfo ri : list) {
20366                allHomeCandidates.add(ri);
20367            }
20368        }
20369        return (preferred == null || preferred.activityInfo == null)
20370                ? null
20371                : new ComponentName(preferred.activityInfo.packageName,
20372                        preferred.activityInfo.name);
20373    }
20374
20375    @Override
20376    public void setHomeActivity(ComponentName comp, int userId) {
20377        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20378            return;
20379        }
20380        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20381        getHomeActivitiesAsUser(homeActivities, userId);
20382
20383        boolean found = false;
20384
20385        final int size = homeActivities.size();
20386        final ComponentName[] set = new ComponentName[size];
20387        for (int i = 0; i < size; i++) {
20388            final ResolveInfo candidate = homeActivities.get(i);
20389            final ActivityInfo info = candidate.activityInfo;
20390            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20391            set[i] = activityName;
20392            if (!found && activityName.equals(comp)) {
20393                found = true;
20394            }
20395        }
20396        if (!found) {
20397            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20398                    + userId);
20399        }
20400        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20401                set, comp, userId);
20402    }
20403
20404    private @Nullable String getSetupWizardPackageName() {
20405        final Intent intent = new Intent(Intent.ACTION_MAIN);
20406        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20407
20408        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20409                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20410                        | MATCH_DISABLED_COMPONENTS,
20411                UserHandle.myUserId());
20412        if (matches.size() == 1) {
20413            return matches.get(0).getComponentInfo().packageName;
20414        } else {
20415            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20416                    + ": matches=" + matches);
20417            return null;
20418        }
20419    }
20420
20421    private @Nullable String getStorageManagerPackageName() {
20422        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20423
20424        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20425                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20426                        | MATCH_DISABLED_COMPONENTS,
20427                UserHandle.myUserId());
20428        if (matches.size() == 1) {
20429            return matches.get(0).getComponentInfo().packageName;
20430        } else {
20431            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20432                    + matches.size() + ": matches=" + matches);
20433            return null;
20434        }
20435    }
20436
20437    @Override
20438    public void setApplicationEnabledSetting(String appPackageName,
20439            int newState, int flags, int userId, String callingPackage) {
20440        if (!sUserManager.exists(userId)) return;
20441        if (callingPackage == null) {
20442            callingPackage = Integer.toString(Binder.getCallingUid());
20443        }
20444        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20445    }
20446
20447    @Override
20448    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20449        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20450        synchronized (mPackages) {
20451            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20452            if (pkgSetting != null) {
20453                pkgSetting.setUpdateAvailable(updateAvailable);
20454            }
20455        }
20456    }
20457
20458    @Override
20459    public void setComponentEnabledSetting(ComponentName componentName,
20460            int newState, int flags, int userId) {
20461        if (!sUserManager.exists(userId)) return;
20462        setEnabledSetting(componentName.getPackageName(),
20463                componentName.getClassName(), newState, flags, userId, null);
20464    }
20465
20466    private void setEnabledSetting(final String packageName, String className, int newState,
20467            final int flags, int userId, String callingPackage) {
20468        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20469              || newState == COMPONENT_ENABLED_STATE_ENABLED
20470              || newState == COMPONENT_ENABLED_STATE_DISABLED
20471              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20472              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20473            throw new IllegalArgumentException("Invalid new component state: "
20474                    + newState);
20475        }
20476        PackageSetting pkgSetting;
20477        final int callingUid = Binder.getCallingUid();
20478        final int permission;
20479        if (callingUid == Process.SYSTEM_UID) {
20480            permission = PackageManager.PERMISSION_GRANTED;
20481        } else {
20482            permission = mContext.checkCallingOrSelfPermission(
20483                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20484        }
20485        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20486                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20487        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20488        boolean sendNow = false;
20489        boolean isApp = (className == null);
20490        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20491        String componentName = isApp ? packageName : className;
20492        int packageUid = -1;
20493        ArrayList<String> components;
20494
20495        // reader
20496        synchronized (mPackages) {
20497            pkgSetting = mSettings.mPackages.get(packageName);
20498            if (pkgSetting == null) {
20499                if (!isCallerInstantApp) {
20500                    if (className == null) {
20501                        throw new IllegalArgumentException("Unknown package: " + packageName);
20502                    }
20503                    throw new IllegalArgumentException(
20504                            "Unknown component: " + packageName + "/" + className);
20505                } else {
20506                    // throw SecurityException to prevent leaking package information
20507                    throw new SecurityException(
20508                            "Attempt to change component state; "
20509                            + "pid=" + Binder.getCallingPid()
20510                            + ", uid=" + callingUid
20511                            + (className == null
20512                                    ? ", package=" + packageName
20513                                    : ", component=" + packageName + "/" + className));
20514                }
20515            }
20516        }
20517
20518        // Limit who can change which apps
20519        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20520            // Don't allow apps that don't have permission to modify other apps
20521            if (!allowedByPermission
20522                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20523                throw new SecurityException(
20524                        "Attempt to change component state; "
20525                        + "pid=" + Binder.getCallingPid()
20526                        + ", uid=" + callingUid
20527                        + (className == null
20528                                ? ", package=" + packageName
20529                                : ", component=" + packageName + "/" + className));
20530            }
20531            // Don't allow changing protected packages.
20532            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20533                throw new SecurityException("Cannot disable a protected package: " + packageName);
20534            }
20535        }
20536
20537        synchronized (mPackages) {
20538            if (callingUid == Process.SHELL_UID
20539                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20540                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20541                // unless it is a test package.
20542                int oldState = pkgSetting.getEnabled(userId);
20543                if (className == null
20544                        &&
20545                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20546                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20547                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20548                        &&
20549                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20550                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20551                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20552                    // ok
20553                } else {
20554                    throw new SecurityException(
20555                            "Shell cannot change component state for " + packageName + "/"
20556                                    + className + " to " + newState);
20557                }
20558            }
20559        }
20560        if (className == null) {
20561            // We're dealing with an application/package level state change
20562            synchronized (mPackages) {
20563                if (pkgSetting.getEnabled(userId) == newState) {
20564                    // Nothing to do
20565                    return;
20566                }
20567            }
20568            // If we're enabling a system stub, there's a little more work to do.
20569            // Prior to enabling the package, we need to decompress the APK(s) to the
20570            // data partition and then replace the version on the system partition.
20571            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20572            final boolean isSystemStub = deletedPkg.isStub
20573                    && deletedPkg.isSystemApp();
20574            if (isSystemStub
20575                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20576                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20577                final File codePath = decompressPackage(deletedPkg);
20578                if (codePath == null) {
20579                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20580                    return;
20581                }
20582                // TODO remove direct parsing of the package object during internal cleanup
20583                // of scan package
20584                // We need to call parse directly here for no other reason than we need
20585                // the new package in order to disable the old one [we use the information
20586                // for some internal optimization to optionally create a new package setting
20587                // object on replace]. However, we can't get the package from the scan
20588                // because the scan modifies live structures and we need to remove the
20589                // old [system] package from the system before a scan can be attempted.
20590                // Once scan is indempotent we can remove this parse and use the package
20591                // object we scanned, prior to adding it to package settings.
20592                final PackageParser pp = new PackageParser();
20593                pp.setSeparateProcesses(mSeparateProcesses);
20594                pp.setDisplayMetrics(mMetrics);
20595                pp.setCallback(mPackageParserCallback);
20596                final PackageParser.Package tmpPkg;
20597                try {
20598                    final int parseFlags = mDefParseFlags
20599                            | PackageParser.PARSE_MUST_BE_APK
20600                            | PackageParser.PARSE_IS_SYSTEM
20601                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20602                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20603                } catch (PackageParserException e) {
20604                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20605                    return;
20606                }
20607                synchronized (mInstallLock) {
20608                    // Disable the stub and remove any package entries
20609                    removePackageLI(deletedPkg, true);
20610                    synchronized (mPackages) {
20611                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20612                    }
20613                    final PackageParser.Package newPkg;
20614                    try (PackageFreezer freezer =
20615                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20616                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20617                                | PackageParser.PARSE_ENFORCE_CODE;
20618                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20619                                0 /*currentTime*/, null /*user*/);
20620                        prepareAppDataAfterInstallLIF(newPkg);
20621                        synchronized (mPackages) {
20622                            try {
20623                                updateSharedLibrariesLPr(newPkg, null);
20624                            } catch (PackageManagerException e) {
20625                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20626                            }
20627                            updatePermissionsLPw(newPkg.packageName, newPkg,
20628                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20629                            mSettings.writeLPr();
20630                        }
20631                    } catch (PackageManagerException e) {
20632                        // Whoops! Something went wrong; try to roll back to the stub
20633                        Slog.w(TAG, "Failed to install compressed system package:"
20634                                + pkgSetting.name, e);
20635                        // Remove the failed install
20636                        removeCodePathLI(codePath);
20637
20638                        // Install the system package
20639                        try (PackageFreezer freezer =
20640                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20641                            synchronized (mPackages) {
20642                                // NOTE: The system package always needs to be enabled; even
20643                                // if it's for a compressed stub. If we don't, installing the
20644                                // system package fails during scan [scanning checks the disabled
20645                                // packages]. We will reverse this later, after we've "installed"
20646                                // the stub.
20647                                // This leaves us in a fragile state; the stub should never be
20648                                // enabled, so, cross your fingers and hope nothing goes wrong
20649                                // until we can disable the package later.
20650                                enableSystemPackageLPw(deletedPkg);
20651                            }
20652                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20653                                    false /*isPrivileged*/, null /*allUserHandles*/,
20654                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20655                                    true /*writeSettings*/);
20656                        } catch (PackageManagerException pme) {
20657                            Slog.w(TAG, "Failed to restore system package:"
20658                                    + deletedPkg.packageName, pme);
20659                        } finally {
20660                            synchronized (mPackages) {
20661                                mSettings.disableSystemPackageLPw(
20662                                        deletedPkg.packageName, true /*replaced*/);
20663                                mSettings.writeLPr();
20664                            }
20665                        }
20666                        return;
20667                    }
20668                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20669                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20670                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20671                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20672                            newPkg.baseCodePath, newPkg.splitCodePaths);
20673                }
20674            }
20675            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20676                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20677                // Don't care about who enables an app.
20678                callingPackage = null;
20679            }
20680            synchronized (mPackages) {
20681                pkgSetting.setEnabled(newState, userId, callingPackage);
20682            }
20683        } else {
20684            synchronized (mPackages) {
20685                // We're dealing with a component level state change
20686                // First, verify that this is a valid class name.
20687                PackageParser.Package pkg = pkgSetting.pkg;
20688                if (pkg == null || !pkg.hasComponentClassName(className)) {
20689                    if (pkg != null &&
20690                            pkg.applicationInfo.targetSdkVersion >=
20691                                    Build.VERSION_CODES.JELLY_BEAN) {
20692                        throw new IllegalArgumentException("Component class " + className
20693                                + " does not exist in " + packageName);
20694                    } else {
20695                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20696                                + className + " does not exist in " + packageName);
20697                    }
20698                }
20699                switch (newState) {
20700                    case COMPONENT_ENABLED_STATE_ENABLED:
20701                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20702                            return;
20703                        }
20704                        break;
20705                    case COMPONENT_ENABLED_STATE_DISABLED:
20706                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20707                            return;
20708                        }
20709                        break;
20710                    case COMPONENT_ENABLED_STATE_DEFAULT:
20711                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20712                            return;
20713                        }
20714                        break;
20715                    default:
20716                        Slog.e(TAG, "Invalid new component state: " + newState);
20717                        return;
20718                }
20719            }
20720        }
20721        synchronized (mPackages) {
20722            scheduleWritePackageRestrictionsLocked(userId);
20723            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20724            final long callingId = Binder.clearCallingIdentity();
20725            try {
20726                updateInstantAppInstallerLocked(packageName);
20727            } finally {
20728                Binder.restoreCallingIdentity(callingId);
20729            }
20730            components = mPendingBroadcasts.get(userId, packageName);
20731            final boolean newPackage = components == null;
20732            if (newPackage) {
20733                components = new ArrayList<String>();
20734            }
20735            if (!components.contains(componentName)) {
20736                components.add(componentName);
20737            }
20738            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20739                sendNow = true;
20740                // Purge entry from pending broadcast list if another one exists already
20741                // since we are sending one right away.
20742                mPendingBroadcasts.remove(userId, packageName);
20743            } else {
20744                if (newPackage) {
20745                    mPendingBroadcasts.put(userId, packageName, components);
20746                }
20747                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20748                    // Schedule a message
20749                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20750                }
20751            }
20752        }
20753
20754        long callingId = Binder.clearCallingIdentity();
20755        try {
20756            if (sendNow) {
20757                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20758                sendPackageChangedBroadcast(packageName,
20759                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20760            }
20761        } finally {
20762            Binder.restoreCallingIdentity(callingId);
20763        }
20764    }
20765
20766    @Override
20767    public void flushPackageRestrictionsAsUser(int userId) {
20768        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20769            return;
20770        }
20771        if (!sUserManager.exists(userId)) {
20772            return;
20773        }
20774        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20775                false /* checkShell */, "flushPackageRestrictions");
20776        synchronized (mPackages) {
20777            mSettings.writePackageRestrictionsLPr(userId);
20778            mDirtyUsers.remove(userId);
20779            if (mDirtyUsers.isEmpty()) {
20780                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20781            }
20782        }
20783    }
20784
20785    private void sendPackageChangedBroadcast(String packageName,
20786            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20787        if (DEBUG_INSTALL)
20788            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20789                    + componentNames);
20790        Bundle extras = new Bundle(4);
20791        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20792        String nameList[] = new String[componentNames.size()];
20793        componentNames.toArray(nameList);
20794        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20795        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20796        extras.putInt(Intent.EXTRA_UID, packageUid);
20797        // If this is not reporting a change of the overall package, then only send it
20798        // to registered receivers.  We don't want to launch a swath of apps for every
20799        // little component state change.
20800        final int flags = !componentNames.contains(packageName)
20801                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20802        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20803                new int[] {UserHandle.getUserId(packageUid)});
20804    }
20805
20806    @Override
20807    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20808        if (!sUserManager.exists(userId)) return;
20809        final int callingUid = Binder.getCallingUid();
20810        if (getInstantAppPackageName(callingUid) != null) {
20811            return;
20812        }
20813        final int permission = mContext.checkCallingOrSelfPermission(
20814                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20815        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20816        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20817                true /* requireFullPermission */, true /* checkShell */, "stop package");
20818        // writer
20819        synchronized (mPackages) {
20820            final PackageSetting ps = mSettings.mPackages.get(packageName);
20821            if (!filterAppAccessLPr(ps, callingUid, userId)
20822                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20823                            allowedByPermission, callingUid, userId)) {
20824                scheduleWritePackageRestrictionsLocked(userId);
20825            }
20826        }
20827    }
20828
20829    @Override
20830    public String getInstallerPackageName(String packageName) {
20831        final int callingUid = Binder.getCallingUid();
20832        if (getInstantAppPackageName(callingUid) != null) {
20833            return null;
20834        }
20835        // reader
20836        synchronized (mPackages) {
20837            final PackageSetting ps = mSettings.mPackages.get(packageName);
20838            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20839                return null;
20840            }
20841            return mSettings.getInstallerPackageNameLPr(packageName);
20842        }
20843    }
20844
20845    public boolean isOrphaned(String packageName) {
20846        // reader
20847        synchronized (mPackages) {
20848            return mSettings.isOrphaned(packageName);
20849        }
20850    }
20851
20852    @Override
20853    public int getApplicationEnabledSetting(String packageName, int userId) {
20854        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20855        int callingUid = Binder.getCallingUid();
20856        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20857                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20858        // reader
20859        synchronized (mPackages) {
20860            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20861                return COMPONENT_ENABLED_STATE_DISABLED;
20862            }
20863            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20864        }
20865    }
20866
20867    @Override
20868    public int getComponentEnabledSetting(ComponentName component, int userId) {
20869        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20870        int callingUid = Binder.getCallingUid();
20871        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20872                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20873        synchronized (mPackages) {
20874            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20875                    component, TYPE_UNKNOWN, userId)) {
20876                return COMPONENT_ENABLED_STATE_DISABLED;
20877            }
20878            return mSettings.getComponentEnabledSettingLPr(component, userId);
20879        }
20880    }
20881
20882    @Override
20883    public void enterSafeMode() {
20884        enforceSystemOrRoot("Only the system can request entering safe mode");
20885
20886        if (!mSystemReady) {
20887            mSafeMode = true;
20888        }
20889    }
20890
20891    @Override
20892    public void systemReady() {
20893        enforceSystemOrRoot("Only the system can claim the system is ready");
20894
20895        mSystemReady = true;
20896        final ContentResolver resolver = mContext.getContentResolver();
20897        ContentObserver co = new ContentObserver(mHandler) {
20898            @Override
20899            public void onChange(boolean selfChange) {
20900                mEphemeralAppsDisabled =
20901                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20902                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20903            }
20904        };
20905        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20906                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20907                false, co, UserHandle.USER_SYSTEM);
20908        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20909                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20910        co.onChange(true);
20911
20912        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20913        // disabled after already being started.
20914        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20915                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20916
20917        // Read the compatibilty setting when the system is ready.
20918        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20919                mContext.getContentResolver(),
20920                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20921        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20922        if (DEBUG_SETTINGS) {
20923            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20924        }
20925
20926        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20927
20928        synchronized (mPackages) {
20929            // Verify that all of the preferred activity components actually
20930            // exist.  It is possible for applications to be updated and at
20931            // that point remove a previously declared activity component that
20932            // had been set as a preferred activity.  We try to clean this up
20933            // the next time we encounter that preferred activity, but it is
20934            // possible for the user flow to never be able to return to that
20935            // situation so here we do a sanity check to make sure we haven't
20936            // left any junk around.
20937            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20938            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20939                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20940                removed.clear();
20941                for (PreferredActivity pa : pir.filterSet()) {
20942                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20943                        removed.add(pa);
20944                    }
20945                }
20946                if (removed.size() > 0) {
20947                    for (int r=0; r<removed.size(); r++) {
20948                        PreferredActivity pa = removed.get(r);
20949                        Slog.w(TAG, "Removing dangling preferred activity: "
20950                                + pa.mPref.mComponent);
20951                        pir.removeFilter(pa);
20952                    }
20953                    mSettings.writePackageRestrictionsLPr(
20954                            mSettings.mPreferredActivities.keyAt(i));
20955                }
20956            }
20957
20958            for (int userId : UserManagerService.getInstance().getUserIds()) {
20959                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20960                    grantPermissionsUserIds = ArrayUtils.appendInt(
20961                            grantPermissionsUserIds, userId);
20962                }
20963            }
20964        }
20965        sUserManager.systemReady();
20966
20967        // If we upgraded grant all default permissions before kicking off.
20968        for (int userId : grantPermissionsUserIds) {
20969            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20970        }
20971
20972        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20973            // If we did not grant default permissions, we preload from this the
20974            // default permission exceptions lazily to ensure we don't hit the
20975            // disk on a new user creation.
20976            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20977        }
20978
20979        // Now that we've scanned all packages, and granted any default
20980        // permissions, ensure permissions are updated. Beware of dragons if you
20981        // try optimizing this.
20982        synchronized (mPackages) {
20983            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
20984                    UPDATE_PERMISSIONS_ALL);
20985        }
20986
20987        // Kick off any messages waiting for system ready
20988        if (mPostSystemReadyMessages != null) {
20989            for (Message msg : mPostSystemReadyMessages) {
20990                msg.sendToTarget();
20991            }
20992            mPostSystemReadyMessages = null;
20993        }
20994
20995        // Watch for external volumes that come and go over time
20996        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20997        storage.registerListener(mStorageListener);
20998
20999        mInstallerService.systemReady();
21000        mPackageDexOptimizer.systemReady();
21001
21002        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21003                StorageManagerInternal.class);
21004        StorageManagerInternal.addExternalStoragePolicy(
21005                new StorageManagerInternal.ExternalStorageMountPolicy() {
21006            @Override
21007            public int getMountMode(int uid, String packageName) {
21008                if (Process.isIsolated(uid)) {
21009                    return Zygote.MOUNT_EXTERNAL_NONE;
21010                }
21011                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21012                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21013                }
21014                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21015                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21016                }
21017                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21018                    return Zygote.MOUNT_EXTERNAL_READ;
21019                }
21020                return Zygote.MOUNT_EXTERNAL_WRITE;
21021            }
21022
21023            @Override
21024            public boolean hasExternalStorage(int uid, String packageName) {
21025                return true;
21026            }
21027        });
21028
21029        // Now that we're mostly running, clean up stale users and apps
21030        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21031        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21032
21033        if (mPrivappPermissionsViolations != null) {
21034            throw new IllegalStateException("Signature|privileged permissions not in "
21035                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21036        }
21037    }
21038
21039    public void waitForAppDataPrepared() {
21040        if (mPrepareAppDataFuture == null) {
21041            return;
21042        }
21043        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21044        mPrepareAppDataFuture = null;
21045    }
21046
21047    @Override
21048    public boolean isSafeMode() {
21049        // allow instant applications
21050        return mSafeMode;
21051    }
21052
21053    @Override
21054    public boolean hasSystemUidErrors() {
21055        // allow instant applications
21056        return mHasSystemUidErrors;
21057    }
21058
21059    static String arrayToString(int[] array) {
21060        StringBuffer buf = new StringBuffer(128);
21061        buf.append('[');
21062        if (array != null) {
21063            for (int i=0; i<array.length; i++) {
21064                if (i > 0) buf.append(", ");
21065                buf.append(array[i]);
21066            }
21067        }
21068        buf.append(']');
21069        return buf.toString();
21070    }
21071
21072    @Override
21073    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21074            FileDescriptor err, String[] args, ShellCallback callback,
21075            ResultReceiver resultReceiver) {
21076        (new PackageManagerShellCommand(this)).exec(
21077                this, in, out, err, args, callback, resultReceiver);
21078    }
21079
21080    @Override
21081    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21082        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21083
21084        DumpState dumpState = new DumpState();
21085        boolean fullPreferred = false;
21086        boolean checkin = false;
21087
21088        String packageName = null;
21089        ArraySet<String> permissionNames = null;
21090
21091        int opti = 0;
21092        while (opti < args.length) {
21093            String opt = args[opti];
21094            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21095                break;
21096            }
21097            opti++;
21098
21099            if ("-a".equals(opt)) {
21100                // Right now we only know how to print all.
21101            } else if ("-h".equals(opt)) {
21102                pw.println("Package manager dump options:");
21103                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21104                pw.println("    --checkin: dump for a checkin");
21105                pw.println("    -f: print details of intent filters");
21106                pw.println("    -h: print this help");
21107                pw.println("  cmd may be one of:");
21108                pw.println("    l[ibraries]: list known shared libraries");
21109                pw.println("    f[eatures]: list device features");
21110                pw.println("    k[eysets]: print known keysets");
21111                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21112                pw.println("    perm[issions]: dump permissions");
21113                pw.println("    permission [name ...]: dump declaration and use of given permission");
21114                pw.println("    pref[erred]: print preferred package settings");
21115                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21116                pw.println("    prov[iders]: dump content providers");
21117                pw.println("    p[ackages]: dump installed packages");
21118                pw.println("    s[hared-users]: dump shared user IDs");
21119                pw.println("    m[essages]: print collected runtime messages");
21120                pw.println("    v[erifiers]: print package verifier info");
21121                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21122                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21123                pw.println("    version: print database version info");
21124                pw.println("    write: write current settings now");
21125                pw.println("    installs: details about install sessions");
21126                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21127                pw.println("    dexopt: dump dexopt state");
21128                pw.println("    compiler-stats: dump compiler statistics");
21129                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21130                pw.println("    <package.name>: info about given package");
21131                return;
21132            } else if ("--checkin".equals(opt)) {
21133                checkin = true;
21134            } else if ("-f".equals(opt)) {
21135                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21136            } else if ("--proto".equals(opt)) {
21137                dumpProto(fd);
21138                return;
21139            } else {
21140                pw.println("Unknown argument: " + opt + "; use -h for help");
21141            }
21142        }
21143
21144        // Is the caller requesting to dump a particular piece of data?
21145        if (opti < args.length) {
21146            String cmd = args[opti];
21147            opti++;
21148            // Is this a package name?
21149            if ("android".equals(cmd) || cmd.contains(".")) {
21150                packageName = cmd;
21151                // When dumping a single package, we always dump all of its
21152                // filter information since the amount of data will be reasonable.
21153                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21154            } else if ("check-permission".equals(cmd)) {
21155                if (opti >= args.length) {
21156                    pw.println("Error: check-permission missing permission argument");
21157                    return;
21158                }
21159                String perm = args[opti];
21160                opti++;
21161                if (opti >= args.length) {
21162                    pw.println("Error: check-permission missing package argument");
21163                    return;
21164                }
21165
21166                String pkg = args[opti];
21167                opti++;
21168                int user = UserHandle.getUserId(Binder.getCallingUid());
21169                if (opti < args.length) {
21170                    try {
21171                        user = Integer.parseInt(args[opti]);
21172                    } catch (NumberFormatException e) {
21173                        pw.println("Error: check-permission user argument is not a number: "
21174                                + args[opti]);
21175                        return;
21176                    }
21177                }
21178
21179                // Normalize package name to handle renamed packages and static libs
21180                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21181
21182                pw.println(checkPermission(perm, pkg, user));
21183                return;
21184            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21185                dumpState.setDump(DumpState.DUMP_LIBS);
21186            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21187                dumpState.setDump(DumpState.DUMP_FEATURES);
21188            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21189                if (opti >= args.length) {
21190                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21191                            | DumpState.DUMP_SERVICE_RESOLVERS
21192                            | DumpState.DUMP_RECEIVER_RESOLVERS
21193                            | DumpState.DUMP_CONTENT_RESOLVERS);
21194                } else {
21195                    while (opti < args.length) {
21196                        String name = args[opti];
21197                        if ("a".equals(name) || "activity".equals(name)) {
21198                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21199                        } else if ("s".equals(name) || "service".equals(name)) {
21200                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21201                        } else if ("r".equals(name) || "receiver".equals(name)) {
21202                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21203                        } else if ("c".equals(name) || "content".equals(name)) {
21204                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21205                        } else {
21206                            pw.println("Error: unknown resolver table type: " + name);
21207                            return;
21208                        }
21209                        opti++;
21210                    }
21211                }
21212            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21213                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21214            } else if ("permission".equals(cmd)) {
21215                if (opti >= args.length) {
21216                    pw.println("Error: permission requires permission name");
21217                    return;
21218                }
21219                permissionNames = new ArraySet<>();
21220                while (opti < args.length) {
21221                    permissionNames.add(args[opti]);
21222                    opti++;
21223                }
21224                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21225                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21226            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21227                dumpState.setDump(DumpState.DUMP_PREFERRED);
21228            } else if ("preferred-xml".equals(cmd)) {
21229                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21230                if (opti < args.length && "--full".equals(args[opti])) {
21231                    fullPreferred = true;
21232                    opti++;
21233                }
21234            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21235                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21236            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21237                dumpState.setDump(DumpState.DUMP_PACKAGES);
21238            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21239                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21240            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21241                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21242            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21243                dumpState.setDump(DumpState.DUMP_MESSAGES);
21244            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21245                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21246            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21247                    || "intent-filter-verifiers".equals(cmd)) {
21248                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21249            } else if ("version".equals(cmd)) {
21250                dumpState.setDump(DumpState.DUMP_VERSION);
21251            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21252                dumpState.setDump(DumpState.DUMP_KEYSETS);
21253            } else if ("installs".equals(cmd)) {
21254                dumpState.setDump(DumpState.DUMP_INSTALLS);
21255            } else if ("frozen".equals(cmd)) {
21256                dumpState.setDump(DumpState.DUMP_FROZEN);
21257            } else if ("volumes".equals(cmd)) {
21258                dumpState.setDump(DumpState.DUMP_VOLUMES);
21259            } else if ("dexopt".equals(cmd)) {
21260                dumpState.setDump(DumpState.DUMP_DEXOPT);
21261            } else if ("compiler-stats".equals(cmd)) {
21262                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21263            } else if ("changes".equals(cmd)) {
21264                dumpState.setDump(DumpState.DUMP_CHANGES);
21265            } else if ("write".equals(cmd)) {
21266                synchronized (mPackages) {
21267                    mSettings.writeLPr();
21268                    pw.println("Settings written.");
21269                    return;
21270                }
21271            }
21272        }
21273
21274        if (checkin) {
21275            pw.println("vers,1");
21276        }
21277
21278        // reader
21279        synchronized (mPackages) {
21280            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21281                if (!checkin) {
21282                    if (dumpState.onTitlePrinted())
21283                        pw.println();
21284                    pw.println("Database versions:");
21285                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21286                }
21287            }
21288
21289            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21290                if (!checkin) {
21291                    if (dumpState.onTitlePrinted())
21292                        pw.println();
21293                    pw.println("Verifiers:");
21294                    pw.print("  Required: ");
21295                    pw.print(mRequiredVerifierPackage);
21296                    pw.print(" (uid=");
21297                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21298                            UserHandle.USER_SYSTEM));
21299                    pw.println(")");
21300                } else if (mRequiredVerifierPackage != null) {
21301                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21302                    pw.print(",");
21303                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21304                            UserHandle.USER_SYSTEM));
21305                }
21306            }
21307
21308            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21309                    packageName == null) {
21310                if (mIntentFilterVerifierComponent != null) {
21311                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21312                    if (!checkin) {
21313                        if (dumpState.onTitlePrinted())
21314                            pw.println();
21315                        pw.println("Intent Filter Verifier:");
21316                        pw.print("  Using: ");
21317                        pw.print(verifierPackageName);
21318                        pw.print(" (uid=");
21319                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21320                                UserHandle.USER_SYSTEM));
21321                        pw.println(")");
21322                    } else if (verifierPackageName != null) {
21323                        pw.print("ifv,"); pw.print(verifierPackageName);
21324                        pw.print(",");
21325                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21326                                UserHandle.USER_SYSTEM));
21327                    }
21328                } else {
21329                    pw.println();
21330                    pw.println("No Intent Filter Verifier available!");
21331                }
21332            }
21333
21334            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21335                boolean printedHeader = false;
21336                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21337                while (it.hasNext()) {
21338                    String libName = it.next();
21339                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21340                    if (versionedLib == null) {
21341                        continue;
21342                    }
21343                    final int versionCount = versionedLib.size();
21344                    for (int i = 0; i < versionCount; i++) {
21345                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21346                        if (!checkin) {
21347                            if (!printedHeader) {
21348                                if (dumpState.onTitlePrinted())
21349                                    pw.println();
21350                                pw.println("Libraries:");
21351                                printedHeader = true;
21352                            }
21353                            pw.print("  ");
21354                        } else {
21355                            pw.print("lib,");
21356                        }
21357                        pw.print(libEntry.info.getName());
21358                        if (libEntry.info.isStatic()) {
21359                            pw.print(" version=" + libEntry.info.getVersion());
21360                        }
21361                        if (!checkin) {
21362                            pw.print(" -> ");
21363                        }
21364                        if (libEntry.path != null) {
21365                            pw.print(" (jar) ");
21366                            pw.print(libEntry.path);
21367                        } else {
21368                            pw.print(" (apk) ");
21369                            pw.print(libEntry.apk);
21370                        }
21371                        pw.println();
21372                    }
21373                }
21374            }
21375
21376            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21377                if (dumpState.onTitlePrinted())
21378                    pw.println();
21379                if (!checkin) {
21380                    pw.println("Features:");
21381                }
21382
21383                synchronized (mAvailableFeatures) {
21384                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21385                        if (checkin) {
21386                            pw.print("feat,");
21387                            pw.print(feat.name);
21388                            pw.print(",");
21389                            pw.println(feat.version);
21390                        } else {
21391                            pw.print("  ");
21392                            pw.print(feat.name);
21393                            if (feat.version > 0) {
21394                                pw.print(" version=");
21395                                pw.print(feat.version);
21396                            }
21397                            pw.println();
21398                        }
21399                    }
21400                }
21401            }
21402
21403            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21404                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21405                        : "Activity Resolver Table:", "  ", packageName,
21406                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21407                    dumpState.setTitlePrinted(true);
21408                }
21409            }
21410            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21411                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21412                        : "Receiver Resolver Table:", "  ", packageName,
21413                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21414                    dumpState.setTitlePrinted(true);
21415                }
21416            }
21417            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21418                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21419                        : "Service Resolver Table:", "  ", packageName,
21420                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21421                    dumpState.setTitlePrinted(true);
21422                }
21423            }
21424            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21425                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21426                        : "Provider Resolver Table:", "  ", packageName,
21427                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21428                    dumpState.setTitlePrinted(true);
21429                }
21430            }
21431
21432            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21433                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21434                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21435                    int user = mSettings.mPreferredActivities.keyAt(i);
21436                    if (pir.dump(pw,
21437                            dumpState.getTitlePrinted()
21438                                ? "\nPreferred Activities User " + user + ":"
21439                                : "Preferred Activities User " + user + ":", "  ",
21440                            packageName, true, false)) {
21441                        dumpState.setTitlePrinted(true);
21442                    }
21443                }
21444            }
21445
21446            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21447                pw.flush();
21448                FileOutputStream fout = new FileOutputStream(fd);
21449                BufferedOutputStream str = new BufferedOutputStream(fout);
21450                XmlSerializer serializer = new FastXmlSerializer();
21451                try {
21452                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21453                    serializer.startDocument(null, true);
21454                    serializer.setFeature(
21455                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21456                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21457                    serializer.endDocument();
21458                    serializer.flush();
21459                } catch (IllegalArgumentException e) {
21460                    pw.println("Failed writing: " + e);
21461                } catch (IllegalStateException e) {
21462                    pw.println("Failed writing: " + e);
21463                } catch (IOException e) {
21464                    pw.println("Failed writing: " + e);
21465                }
21466            }
21467
21468            if (!checkin
21469                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21470                    && packageName == null) {
21471                pw.println();
21472                int count = mSettings.mPackages.size();
21473                if (count == 0) {
21474                    pw.println("No applications!");
21475                    pw.println();
21476                } else {
21477                    final String prefix = "  ";
21478                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21479                    if (allPackageSettings.size() == 0) {
21480                        pw.println("No domain preferred apps!");
21481                        pw.println();
21482                    } else {
21483                        pw.println("App verification status:");
21484                        pw.println();
21485                        count = 0;
21486                        for (PackageSetting ps : allPackageSettings) {
21487                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21488                            if (ivi == null || ivi.getPackageName() == null) continue;
21489                            pw.println(prefix + "Package: " + ivi.getPackageName());
21490                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21491                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21492                            pw.println();
21493                            count++;
21494                        }
21495                        if (count == 0) {
21496                            pw.println(prefix + "No app verification established.");
21497                            pw.println();
21498                        }
21499                        for (int userId : sUserManager.getUserIds()) {
21500                            pw.println("App linkages for user " + userId + ":");
21501                            pw.println();
21502                            count = 0;
21503                            for (PackageSetting ps : allPackageSettings) {
21504                                final long status = ps.getDomainVerificationStatusForUser(userId);
21505                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21506                                        && !DEBUG_DOMAIN_VERIFICATION) {
21507                                    continue;
21508                                }
21509                                pw.println(prefix + "Package: " + ps.name);
21510                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21511                                String statusStr = IntentFilterVerificationInfo.
21512                                        getStatusStringFromValue(status);
21513                                pw.println(prefix + "Status:  " + statusStr);
21514                                pw.println();
21515                                count++;
21516                            }
21517                            if (count == 0) {
21518                                pw.println(prefix + "No configured app linkages.");
21519                                pw.println();
21520                            }
21521                        }
21522                    }
21523                }
21524            }
21525
21526            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21527                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21528            }
21529
21530            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21531                boolean printedSomething = false;
21532                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21533                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21534                        continue;
21535                    }
21536                    if (!printedSomething) {
21537                        if (dumpState.onTitlePrinted())
21538                            pw.println();
21539                        pw.println("Registered ContentProviders:");
21540                        printedSomething = true;
21541                    }
21542                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21543                    pw.print("    "); pw.println(p.toString());
21544                }
21545                printedSomething = false;
21546                for (Map.Entry<String, PackageParser.Provider> entry :
21547                        mProvidersByAuthority.entrySet()) {
21548                    PackageParser.Provider p = entry.getValue();
21549                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21550                        continue;
21551                    }
21552                    if (!printedSomething) {
21553                        if (dumpState.onTitlePrinted())
21554                            pw.println();
21555                        pw.println("ContentProvider Authorities:");
21556                        printedSomething = true;
21557                    }
21558                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21559                    pw.print("    "); pw.println(p.toString());
21560                    if (p.info != null && p.info.applicationInfo != null) {
21561                        final String appInfo = p.info.applicationInfo.toString();
21562                        pw.print("      applicationInfo="); pw.println(appInfo);
21563                    }
21564                }
21565            }
21566
21567            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21568                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21569            }
21570
21571            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21572                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21573            }
21574
21575            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21576                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21577            }
21578
21579            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21580                if (dumpState.onTitlePrinted()) pw.println();
21581                pw.println("Package Changes:");
21582                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21583                final int K = mChangedPackages.size();
21584                for (int i = 0; i < K; i++) {
21585                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21586                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21587                    final int N = changes.size();
21588                    if (N == 0) {
21589                        pw.print("    "); pw.println("No packages changed");
21590                    } else {
21591                        for (int j = 0; j < N; j++) {
21592                            final String pkgName = changes.valueAt(j);
21593                            final int sequenceNumber = changes.keyAt(j);
21594                            pw.print("    ");
21595                            pw.print("seq=");
21596                            pw.print(sequenceNumber);
21597                            pw.print(", package=");
21598                            pw.println(pkgName);
21599                        }
21600                    }
21601                }
21602            }
21603
21604            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21605                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21606            }
21607
21608            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21609                // XXX should handle packageName != null by dumping only install data that
21610                // the given package is involved with.
21611                if (dumpState.onTitlePrinted()) pw.println();
21612
21613                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21614                ipw.println();
21615                ipw.println("Frozen packages:");
21616                ipw.increaseIndent();
21617                if (mFrozenPackages.size() == 0) {
21618                    ipw.println("(none)");
21619                } else {
21620                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21621                        ipw.println(mFrozenPackages.valueAt(i));
21622                    }
21623                }
21624                ipw.decreaseIndent();
21625            }
21626
21627            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21628                if (dumpState.onTitlePrinted()) pw.println();
21629
21630                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21631                ipw.println();
21632                ipw.println("Loaded volumes:");
21633                ipw.increaseIndent();
21634                if (mLoadedVolumes.size() == 0) {
21635                    ipw.println("(none)");
21636                } else {
21637                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21638                        ipw.println(mLoadedVolumes.valueAt(i));
21639                    }
21640                }
21641                ipw.decreaseIndent();
21642            }
21643
21644            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21645                if (dumpState.onTitlePrinted()) pw.println();
21646                dumpDexoptStateLPr(pw, packageName);
21647            }
21648
21649            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21650                if (dumpState.onTitlePrinted()) pw.println();
21651                dumpCompilerStatsLPr(pw, packageName);
21652            }
21653
21654            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21655                if (dumpState.onTitlePrinted()) pw.println();
21656                mSettings.dumpReadMessagesLPr(pw, dumpState);
21657
21658                pw.println();
21659                pw.println("Package warning messages:");
21660                BufferedReader in = null;
21661                String line = null;
21662                try {
21663                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21664                    while ((line = in.readLine()) != null) {
21665                        if (line.contains("ignored: updated version")) continue;
21666                        pw.println(line);
21667                    }
21668                } catch (IOException ignored) {
21669                } finally {
21670                    IoUtils.closeQuietly(in);
21671                }
21672            }
21673
21674            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21675                BufferedReader in = null;
21676                String line = null;
21677                try {
21678                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21679                    while ((line = in.readLine()) != null) {
21680                        if (line.contains("ignored: updated version")) continue;
21681                        pw.print("msg,");
21682                        pw.println(line);
21683                    }
21684                } catch (IOException ignored) {
21685                } finally {
21686                    IoUtils.closeQuietly(in);
21687                }
21688            }
21689        }
21690
21691        // PackageInstaller should be called outside of mPackages lock
21692        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21693            // XXX should handle packageName != null by dumping only install data that
21694            // the given package is involved with.
21695            if (dumpState.onTitlePrinted()) pw.println();
21696            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21697        }
21698    }
21699
21700    private void dumpProto(FileDescriptor fd) {
21701        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21702
21703        synchronized (mPackages) {
21704            final long requiredVerifierPackageToken =
21705                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21706            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21707            proto.write(
21708                    PackageServiceDumpProto.PackageShortProto.UID,
21709                    getPackageUid(
21710                            mRequiredVerifierPackage,
21711                            MATCH_DEBUG_TRIAGED_MISSING,
21712                            UserHandle.USER_SYSTEM));
21713            proto.end(requiredVerifierPackageToken);
21714
21715            if (mIntentFilterVerifierComponent != null) {
21716                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21717                final long verifierPackageToken =
21718                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21719                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21720                proto.write(
21721                        PackageServiceDumpProto.PackageShortProto.UID,
21722                        getPackageUid(
21723                                verifierPackageName,
21724                                MATCH_DEBUG_TRIAGED_MISSING,
21725                                UserHandle.USER_SYSTEM));
21726                proto.end(verifierPackageToken);
21727            }
21728
21729            dumpSharedLibrariesProto(proto);
21730            dumpFeaturesProto(proto);
21731            mSettings.dumpPackagesProto(proto);
21732            mSettings.dumpSharedUsersProto(proto);
21733            dumpMessagesProto(proto);
21734        }
21735        proto.flush();
21736    }
21737
21738    private void dumpMessagesProto(ProtoOutputStream proto) {
21739        BufferedReader in = null;
21740        String line = null;
21741        try {
21742            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21743            while ((line = in.readLine()) != null) {
21744                if (line.contains("ignored: updated version")) continue;
21745                proto.write(PackageServiceDumpProto.MESSAGES, line);
21746            }
21747        } catch (IOException ignored) {
21748        } finally {
21749            IoUtils.closeQuietly(in);
21750        }
21751    }
21752
21753    private void dumpFeaturesProto(ProtoOutputStream proto) {
21754        synchronized (mAvailableFeatures) {
21755            final int count = mAvailableFeatures.size();
21756            for (int i = 0; i < count; i++) {
21757                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21758            }
21759        }
21760    }
21761
21762    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21763        final int count = mSharedLibraries.size();
21764        for (int i = 0; i < count; i++) {
21765            final String libName = mSharedLibraries.keyAt(i);
21766            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21767            if (versionedLib == null) {
21768                continue;
21769            }
21770            final int versionCount = versionedLib.size();
21771            for (int j = 0; j < versionCount; j++) {
21772                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21773                final long sharedLibraryToken =
21774                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21775                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21776                final boolean isJar = (libEntry.path != null);
21777                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21778                if (isJar) {
21779                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21780                } else {
21781                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21782                }
21783                proto.end(sharedLibraryToken);
21784            }
21785        }
21786    }
21787
21788    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21789        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21790        ipw.println();
21791        ipw.println("Dexopt state:");
21792        ipw.increaseIndent();
21793        Collection<PackageParser.Package> packages = null;
21794        if (packageName != null) {
21795            PackageParser.Package targetPackage = mPackages.get(packageName);
21796            if (targetPackage != null) {
21797                packages = Collections.singletonList(targetPackage);
21798            } else {
21799                ipw.println("Unable to find package: " + packageName);
21800                return;
21801            }
21802        } else {
21803            packages = mPackages.values();
21804        }
21805
21806        for (PackageParser.Package pkg : packages) {
21807            ipw.println("[" + pkg.packageName + "]");
21808            ipw.increaseIndent();
21809            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21810                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21811            ipw.decreaseIndent();
21812        }
21813    }
21814
21815    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21816        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21817        ipw.println();
21818        ipw.println("Compiler stats:");
21819        ipw.increaseIndent();
21820        Collection<PackageParser.Package> packages = null;
21821        if (packageName != null) {
21822            PackageParser.Package targetPackage = mPackages.get(packageName);
21823            if (targetPackage != null) {
21824                packages = Collections.singletonList(targetPackage);
21825            } else {
21826                ipw.println("Unable to find package: " + packageName);
21827                return;
21828            }
21829        } else {
21830            packages = mPackages.values();
21831        }
21832
21833        for (PackageParser.Package pkg : packages) {
21834            ipw.println("[" + pkg.packageName + "]");
21835            ipw.increaseIndent();
21836
21837            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21838            if (stats == null) {
21839                ipw.println("(No recorded stats)");
21840            } else {
21841                stats.dump(ipw);
21842            }
21843            ipw.decreaseIndent();
21844        }
21845    }
21846
21847    private String dumpDomainString(String packageName) {
21848        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21849                .getList();
21850        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21851
21852        ArraySet<String> result = new ArraySet<>();
21853        if (iviList.size() > 0) {
21854            for (IntentFilterVerificationInfo ivi : iviList) {
21855                for (String host : ivi.getDomains()) {
21856                    result.add(host);
21857                }
21858            }
21859        }
21860        if (filters != null && filters.size() > 0) {
21861            for (IntentFilter filter : filters) {
21862                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21863                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21864                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21865                    result.addAll(filter.getHostsList());
21866                }
21867            }
21868        }
21869
21870        StringBuilder sb = new StringBuilder(result.size() * 16);
21871        for (String domain : result) {
21872            if (sb.length() > 0) sb.append(" ");
21873            sb.append(domain);
21874        }
21875        return sb.toString();
21876    }
21877
21878    // ------- apps on sdcard specific code -------
21879    static final boolean DEBUG_SD_INSTALL = false;
21880
21881    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21882
21883    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21884
21885    private boolean mMediaMounted = false;
21886
21887    static String getEncryptKey() {
21888        try {
21889            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21890                    SD_ENCRYPTION_KEYSTORE_NAME);
21891            if (sdEncKey == null) {
21892                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21893                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21894                if (sdEncKey == null) {
21895                    Slog.e(TAG, "Failed to create encryption keys");
21896                    return null;
21897                }
21898            }
21899            return sdEncKey;
21900        } catch (NoSuchAlgorithmException nsae) {
21901            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21902            return null;
21903        } catch (IOException ioe) {
21904            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21905            return null;
21906        }
21907    }
21908
21909    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21910            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21911        final int size = infos.size();
21912        final String[] packageNames = new String[size];
21913        final int[] packageUids = new int[size];
21914        for (int i = 0; i < size; i++) {
21915            final ApplicationInfo info = infos.get(i);
21916            packageNames[i] = info.packageName;
21917            packageUids[i] = info.uid;
21918        }
21919        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21920                finishedReceiver);
21921    }
21922
21923    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21924            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21925        sendResourcesChangedBroadcast(mediaStatus, replacing,
21926                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21927    }
21928
21929    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21930            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21931        int size = pkgList.length;
21932        if (size > 0) {
21933            // Send broadcasts here
21934            Bundle extras = new Bundle();
21935            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21936            if (uidArr != null) {
21937                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21938            }
21939            if (replacing) {
21940                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21941            }
21942            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21943                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21944            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21945        }
21946    }
21947
21948    private void loadPrivatePackages(final VolumeInfo vol) {
21949        mHandler.post(new Runnable() {
21950            @Override
21951            public void run() {
21952                loadPrivatePackagesInner(vol);
21953            }
21954        });
21955    }
21956
21957    private void loadPrivatePackagesInner(VolumeInfo vol) {
21958        final String volumeUuid = vol.fsUuid;
21959        if (TextUtils.isEmpty(volumeUuid)) {
21960            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21961            return;
21962        }
21963
21964        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21965        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21966        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21967
21968        final VersionInfo ver;
21969        final List<PackageSetting> packages;
21970        synchronized (mPackages) {
21971            ver = mSettings.findOrCreateVersion(volumeUuid);
21972            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21973        }
21974
21975        for (PackageSetting ps : packages) {
21976            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21977            synchronized (mInstallLock) {
21978                final PackageParser.Package pkg;
21979                try {
21980                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21981                    loaded.add(pkg.applicationInfo);
21982
21983                } catch (PackageManagerException e) {
21984                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21985                }
21986
21987                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21988                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21989                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21990                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21991                }
21992            }
21993        }
21994
21995        // Reconcile app data for all started/unlocked users
21996        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21997        final UserManager um = mContext.getSystemService(UserManager.class);
21998        UserManagerInternal umInternal = getUserManagerInternal();
21999        for (UserInfo user : um.getUsers()) {
22000            final int flags;
22001            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22002                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22003            } else if (umInternal.isUserRunning(user.id)) {
22004                flags = StorageManager.FLAG_STORAGE_DE;
22005            } else {
22006                continue;
22007            }
22008
22009            try {
22010                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22011                synchronized (mInstallLock) {
22012                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22013                }
22014            } catch (IllegalStateException e) {
22015                // Device was probably ejected, and we'll process that event momentarily
22016                Slog.w(TAG, "Failed to prepare storage: " + e);
22017            }
22018        }
22019
22020        synchronized (mPackages) {
22021            int updateFlags = UPDATE_PERMISSIONS_ALL;
22022            if (ver.sdkVersion != mSdkVersion) {
22023                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22024                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22025                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22026            }
22027            updatePermissionsLocked(null, null, volumeUuid, updateFlags);
22028
22029            // Yay, everything is now upgraded
22030            ver.forceCurrent();
22031
22032            mSettings.writeLPr();
22033        }
22034
22035        for (PackageFreezer freezer : freezers) {
22036            freezer.close();
22037        }
22038
22039        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22040        sendResourcesChangedBroadcast(true, false, loaded, null);
22041        mLoadedVolumes.add(vol.getId());
22042    }
22043
22044    private void unloadPrivatePackages(final VolumeInfo vol) {
22045        mHandler.post(new Runnable() {
22046            @Override
22047            public void run() {
22048                unloadPrivatePackagesInner(vol);
22049            }
22050        });
22051    }
22052
22053    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22054        final String volumeUuid = vol.fsUuid;
22055        if (TextUtils.isEmpty(volumeUuid)) {
22056            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22057            return;
22058        }
22059
22060        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22061        synchronized (mInstallLock) {
22062        synchronized (mPackages) {
22063            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22064            for (PackageSetting ps : packages) {
22065                if (ps.pkg == null) continue;
22066
22067                final ApplicationInfo info = ps.pkg.applicationInfo;
22068                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22069                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22070
22071                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22072                        "unloadPrivatePackagesInner")) {
22073                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22074                            false, null)) {
22075                        unloaded.add(info);
22076                    } else {
22077                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22078                    }
22079                }
22080
22081                // Try very hard to release any references to this package
22082                // so we don't risk the system server being killed due to
22083                // open FDs
22084                AttributeCache.instance().removePackage(ps.name);
22085            }
22086
22087            mSettings.writeLPr();
22088        }
22089        }
22090
22091        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22092        sendResourcesChangedBroadcast(false, false, unloaded, null);
22093        mLoadedVolumes.remove(vol.getId());
22094
22095        // Try very hard to release any references to this path so we don't risk
22096        // the system server being killed due to open FDs
22097        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22098
22099        for (int i = 0; i < 3; i++) {
22100            System.gc();
22101            System.runFinalization();
22102        }
22103    }
22104
22105    private void assertPackageKnown(String volumeUuid, String packageName)
22106            throws PackageManagerException {
22107        synchronized (mPackages) {
22108            // Normalize package name to handle renamed packages
22109            packageName = normalizePackageNameLPr(packageName);
22110
22111            final PackageSetting ps = mSettings.mPackages.get(packageName);
22112            if (ps == null) {
22113                throw new PackageManagerException("Package " + packageName + " is unknown");
22114            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22115                throw new PackageManagerException(
22116                        "Package " + packageName + " found on unknown volume " + volumeUuid
22117                                + "; expected volume " + ps.volumeUuid);
22118            }
22119        }
22120    }
22121
22122    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22123            throws PackageManagerException {
22124        synchronized (mPackages) {
22125            // Normalize package name to handle renamed packages
22126            packageName = normalizePackageNameLPr(packageName);
22127
22128            final PackageSetting ps = mSettings.mPackages.get(packageName);
22129            if (ps == null) {
22130                throw new PackageManagerException("Package " + packageName + " is unknown");
22131            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22132                throw new PackageManagerException(
22133                        "Package " + packageName + " found on unknown volume " + volumeUuid
22134                                + "; expected volume " + ps.volumeUuid);
22135            } else if (!ps.getInstalled(userId)) {
22136                throw new PackageManagerException(
22137                        "Package " + packageName + " not installed for user " + userId);
22138            }
22139        }
22140    }
22141
22142    private List<String> collectAbsoluteCodePaths() {
22143        synchronized (mPackages) {
22144            List<String> codePaths = new ArrayList<>();
22145            final int packageCount = mSettings.mPackages.size();
22146            for (int i = 0; i < packageCount; i++) {
22147                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22148                codePaths.add(ps.codePath.getAbsolutePath());
22149            }
22150            return codePaths;
22151        }
22152    }
22153
22154    /**
22155     * Examine all apps present on given mounted volume, and destroy apps that
22156     * aren't expected, either due to uninstallation or reinstallation on
22157     * another volume.
22158     */
22159    private void reconcileApps(String volumeUuid) {
22160        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22161        List<File> filesToDelete = null;
22162
22163        final File[] files = FileUtils.listFilesOrEmpty(
22164                Environment.getDataAppDirectory(volumeUuid));
22165        for (File file : files) {
22166            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22167                    && !PackageInstallerService.isStageName(file.getName());
22168            if (!isPackage) {
22169                // Ignore entries which are not packages
22170                continue;
22171            }
22172
22173            String absolutePath = file.getAbsolutePath();
22174
22175            boolean pathValid = false;
22176            final int absoluteCodePathCount = absoluteCodePaths.size();
22177            for (int i = 0; i < absoluteCodePathCount; i++) {
22178                String absoluteCodePath = absoluteCodePaths.get(i);
22179                if (absolutePath.startsWith(absoluteCodePath)) {
22180                    pathValid = true;
22181                    break;
22182                }
22183            }
22184
22185            if (!pathValid) {
22186                if (filesToDelete == null) {
22187                    filesToDelete = new ArrayList<>();
22188                }
22189                filesToDelete.add(file);
22190            }
22191        }
22192
22193        if (filesToDelete != null) {
22194            final int fileToDeleteCount = filesToDelete.size();
22195            for (int i = 0; i < fileToDeleteCount; i++) {
22196                File fileToDelete = filesToDelete.get(i);
22197                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22198                synchronized (mInstallLock) {
22199                    removeCodePathLI(fileToDelete);
22200                }
22201            }
22202        }
22203    }
22204
22205    /**
22206     * Reconcile all app data for the given user.
22207     * <p>
22208     * Verifies that directories exist and that ownership and labeling is
22209     * correct for all installed apps on all mounted volumes.
22210     */
22211    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22212        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22213        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22214            final String volumeUuid = vol.getFsUuid();
22215            synchronized (mInstallLock) {
22216                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22217            }
22218        }
22219    }
22220
22221    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22222            boolean migrateAppData) {
22223        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22224    }
22225
22226    /**
22227     * Reconcile all app data on given mounted volume.
22228     * <p>
22229     * Destroys app data that isn't expected, either due to uninstallation or
22230     * reinstallation on another volume.
22231     * <p>
22232     * Verifies that directories exist and that ownership and labeling is
22233     * correct for all installed apps.
22234     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22235     */
22236    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22237            boolean migrateAppData, boolean onlyCoreApps) {
22238        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22239                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22240        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22241
22242        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22243        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22244
22245        // First look for stale data that doesn't belong, and check if things
22246        // have changed since we did our last restorecon
22247        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22248            if (StorageManager.isFileEncryptedNativeOrEmulated()
22249                    && !StorageManager.isUserKeyUnlocked(userId)) {
22250                throw new RuntimeException(
22251                        "Yikes, someone asked us to reconcile CE storage while " + userId
22252                                + " was still locked; this would have caused massive data loss!");
22253            }
22254
22255            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22256            for (File file : files) {
22257                final String packageName = file.getName();
22258                try {
22259                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22260                } catch (PackageManagerException e) {
22261                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22262                    try {
22263                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22264                                StorageManager.FLAG_STORAGE_CE, 0);
22265                    } catch (InstallerException e2) {
22266                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22267                    }
22268                }
22269            }
22270        }
22271        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22272            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22273            for (File file : files) {
22274                final String packageName = file.getName();
22275                try {
22276                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22277                } catch (PackageManagerException e) {
22278                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22279                    try {
22280                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22281                                StorageManager.FLAG_STORAGE_DE, 0);
22282                    } catch (InstallerException e2) {
22283                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22284                    }
22285                }
22286            }
22287        }
22288
22289        // Ensure that data directories are ready to roll for all packages
22290        // installed for this volume and user
22291        final List<PackageSetting> packages;
22292        synchronized (mPackages) {
22293            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22294        }
22295        int preparedCount = 0;
22296        for (PackageSetting ps : packages) {
22297            final String packageName = ps.name;
22298            if (ps.pkg == null) {
22299                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22300                // TODO: might be due to legacy ASEC apps; we should circle back
22301                // and reconcile again once they're scanned
22302                continue;
22303            }
22304            // Skip non-core apps if requested
22305            if (onlyCoreApps && !ps.pkg.coreApp) {
22306                result.add(packageName);
22307                continue;
22308            }
22309
22310            if (ps.getInstalled(userId)) {
22311                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22312                preparedCount++;
22313            }
22314        }
22315
22316        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22317        return result;
22318    }
22319
22320    /**
22321     * Prepare app data for the given app just after it was installed or
22322     * upgraded. This method carefully only touches users that it's installed
22323     * for, and it forces a restorecon to handle any seinfo changes.
22324     * <p>
22325     * Verifies that directories exist and that ownership and labeling is
22326     * correct for all installed apps. If there is an ownership mismatch, it
22327     * will try recovering system apps by wiping data; third-party app data is
22328     * left intact.
22329     * <p>
22330     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22331     */
22332    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22333        final PackageSetting ps;
22334        synchronized (mPackages) {
22335            ps = mSettings.mPackages.get(pkg.packageName);
22336            mSettings.writeKernelMappingLPr(ps);
22337        }
22338
22339        final UserManager um = mContext.getSystemService(UserManager.class);
22340        UserManagerInternal umInternal = getUserManagerInternal();
22341        for (UserInfo user : um.getUsers()) {
22342            final int flags;
22343            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22344                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22345            } else if (umInternal.isUserRunning(user.id)) {
22346                flags = StorageManager.FLAG_STORAGE_DE;
22347            } else {
22348                continue;
22349            }
22350
22351            if (ps.getInstalled(user.id)) {
22352                // TODO: when user data is locked, mark that we're still dirty
22353                prepareAppDataLIF(pkg, user.id, flags);
22354            }
22355        }
22356    }
22357
22358    /**
22359     * Prepare app data for the given app.
22360     * <p>
22361     * Verifies that directories exist and that ownership and labeling is
22362     * correct for all installed apps. If there is an ownership mismatch, this
22363     * will try recovering system apps by wiping data; third-party app data is
22364     * left intact.
22365     */
22366    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22367        if (pkg == null) {
22368            Slog.wtf(TAG, "Package was null!", new Throwable());
22369            return;
22370        }
22371        prepareAppDataLeafLIF(pkg, userId, flags);
22372        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22373        for (int i = 0; i < childCount; i++) {
22374            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22375        }
22376    }
22377
22378    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22379            boolean maybeMigrateAppData) {
22380        prepareAppDataLIF(pkg, userId, flags);
22381
22382        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22383            // We may have just shuffled around app data directories, so
22384            // prepare them one more time
22385            prepareAppDataLIF(pkg, userId, flags);
22386        }
22387    }
22388
22389    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22390        if (DEBUG_APP_DATA) {
22391            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22392                    + Integer.toHexString(flags));
22393        }
22394
22395        final String volumeUuid = pkg.volumeUuid;
22396        final String packageName = pkg.packageName;
22397        final ApplicationInfo app = pkg.applicationInfo;
22398        final int appId = UserHandle.getAppId(app.uid);
22399
22400        Preconditions.checkNotNull(app.seInfo);
22401
22402        long ceDataInode = -1;
22403        try {
22404            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22405                    appId, app.seInfo, app.targetSdkVersion);
22406        } catch (InstallerException e) {
22407            if (app.isSystemApp()) {
22408                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22409                        + ", but trying to recover: " + e);
22410                destroyAppDataLeafLIF(pkg, userId, flags);
22411                try {
22412                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22413                            appId, app.seInfo, app.targetSdkVersion);
22414                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22415                } catch (InstallerException e2) {
22416                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22417                }
22418            } else {
22419                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22420            }
22421        }
22422
22423        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22424            // TODO: mark this structure as dirty so we persist it!
22425            synchronized (mPackages) {
22426                final PackageSetting ps = mSettings.mPackages.get(packageName);
22427                if (ps != null) {
22428                    ps.setCeDataInode(ceDataInode, userId);
22429                }
22430            }
22431        }
22432
22433        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22434    }
22435
22436    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22437        if (pkg == null) {
22438            Slog.wtf(TAG, "Package was null!", new Throwable());
22439            return;
22440        }
22441        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22442        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22443        for (int i = 0; i < childCount; i++) {
22444            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22445        }
22446    }
22447
22448    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22449        final String volumeUuid = pkg.volumeUuid;
22450        final String packageName = pkg.packageName;
22451        final ApplicationInfo app = pkg.applicationInfo;
22452
22453        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22454            // Create a native library symlink only if we have native libraries
22455            // and if the native libraries are 32 bit libraries. We do not provide
22456            // this symlink for 64 bit libraries.
22457            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22458                final String nativeLibPath = app.nativeLibraryDir;
22459                try {
22460                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22461                            nativeLibPath, userId);
22462                } catch (InstallerException e) {
22463                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22464                }
22465            }
22466        }
22467    }
22468
22469    /**
22470     * For system apps on non-FBE devices, this method migrates any existing
22471     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22472     * requested by the app.
22473     */
22474    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22475        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22476                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22477            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22478                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22479            try {
22480                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22481                        storageTarget);
22482            } catch (InstallerException e) {
22483                logCriticalInfo(Log.WARN,
22484                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22485            }
22486            return true;
22487        } else {
22488            return false;
22489        }
22490    }
22491
22492    public PackageFreezer freezePackage(String packageName, String killReason) {
22493        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22494    }
22495
22496    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22497        return new PackageFreezer(packageName, userId, killReason);
22498    }
22499
22500    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22501            String killReason) {
22502        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22503    }
22504
22505    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22506            String killReason) {
22507        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22508            return new PackageFreezer();
22509        } else {
22510            return freezePackage(packageName, userId, killReason);
22511        }
22512    }
22513
22514    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22515            String killReason) {
22516        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22517    }
22518
22519    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22520            String killReason) {
22521        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22522            return new PackageFreezer();
22523        } else {
22524            return freezePackage(packageName, userId, killReason);
22525        }
22526    }
22527
22528    /**
22529     * Class that freezes and kills the given package upon creation, and
22530     * unfreezes it upon closing. This is typically used when doing surgery on
22531     * app code/data to prevent the app from running while you're working.
22532     */
22533    private class PackageFreezer implements AutoCloseable {
22534        private final String mPackageName;
22535        private final PackageFreezer[] mChildren;
22536
22537        private final boolean mWeFroze;
22538
22539        private final AtomicBoolean mClosed = new AtomicBoolean();
22540        private final CloseGuard mCloseGuard = CloseGuard.get();
22541
22542        /**
22543         * Create and return a stub freezer that doesn't actually do anything,
22544         * typically used when someone requested
22545         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22546         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22547         */
22548        public PackageFreezer() {
22549            mPackageName = null;
22550            mChildren = null;
22551            mWeFroze = false;
22552            mCloseGuard.open("close");
22553        }
22554
22555        public PackageFreezer(String packageName, int userId, String killReason) {
22556            synchronized (mPackages) {
22557                mPackageName = packageName;
22558                mWeFroze = mFrozenPackages.add(mPackageName);
22559
22560                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22561                if (ps != null) {
22562                    killApplication(ps.name, ps.appId, userId, killReason);
22563                }
22564
22565                final PackageParser.Package p = mPackages.get(packageName);
22566                if (p != null && p.childPackages != null) {
22567                    final int N = p.childPackages.size();
22568                    mChildren = new PackageFreezer[N];
22569                    for (int i = 0; i < N; i++) {
22570                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22571                                userId, killReason);
22572                    }
22573                } else {
22574                    mChildren = null;
22575                }
22576            }
22577            mCloseGuard.open("close");
22578        }
22579
22580        @Override
22581        protected void finalize() throws Throwable {
22582            try {
22583                if (mCloseGuard != null) {
22584                    mCloseGuard.warnIfOpen();
22585                }
22586
22587                close();
22588            } finally {
22589                super.finalize();
22590            }
22591        }
22592
22593        @Override
22594        public void close() {
22595            mCloseGuard.close();
22596            if (mClosed.compareAndSet(false, true)) {
22597                synchronized (mPackages) {
22598                    if (mWeFroze) {
22599                        mFrozenPackages.remove(mPackageName);
22600                    }
22601
22602                    if (mChildren != null) {
22603                        for (PackageFreezer freezer : mChildren) {
22604                            freezer.close();
22605                        }
22606                    }
22607                }
22608            }
22609        }
22610    }
22611
22612    /**
22613     * Verify that given package is currently frozen.
22614     */
22615    private void checkPackageFrozen(String packageName) {
22616        synchronized (mPackages) {
22617            if (!mFrozenPackages.contains(packageName)) {
22618                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22619            }
22620        }
22621    }
22622
22623    @Override
22624    public int movePackage(final String packageName, final String volumeUuid) {
22625        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22626
22627        final int callingUid = Binder.getCallingUid();
22628        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22629        final int moveId = mNextMoveId.getAndIncrement();
22630        mHandler.post(new Runnable() {
22631            @Override
22632            public void run() {
22633                try {
22634                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22635                } catch (PackageManagerException e) {
22636                    Slog.w(TAG, "Failed to move " + packageName, e);
22637                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22638                }
22639            }
22640        });
22641        return moveId;
22642    }
22643
22644    private void movePackageInternal(final String packageName, final String volumeUuid,
22645            final int moveId, final int callingUid, UserHandle user)
22646                    throws PackageManagerException {
22647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22648        final PackageManager pm = mContext.getPackageManager();
22649
22650        final boolean currentAsec;
22651        final String currentVolumeUuid;
22652        final File codeFile;
22653        final String installerPackageName;
22654        final String packageAbiOverride;
22655        final int appId;
22656        final String seinfo;
22657        final String label;
22658        final int targetSdkVersion;
22659        final PackageFreezer freezer;
22660        final int[] installedUserIds;
22661
22662        // reader
22663        synchronized (mPackages) {
22664            final PackageParser.Package pkg = mPackages.get(packageName);
22665            final PackageSetting ps = mSettings.mPackages.get(packageName);
22666            if (pkg == null
22667                    || ps == null
22668                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22669                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22670            }
22671            if (pkg.applicationInfo.isSystemApp()) {
22672                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22673                        "Cannot move system application");
22674            }
22675
22676            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22677            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22678                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22679            if (isInternalStorage && !allow3rdPartyOnInternal) {
22680                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22681                        "3rd party apps are not allowed on internal storage");
22682            }
22683
22684            if (pkg.applicationInfo.isExternalAsec()) {
22685                currentAsec = true;
22686                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22687            } else if (pkg.applicationInfo.isForwardLocked()) {
22688                currentAsec = true;
22689                currentVolumeUuid = "forward_locked";
22690            } else {
22691                currentAsec = false;
22692                currentVolumeUuid = ps.volumeUuid;
22693
22694                final File probe = new File(pkg.codePath);
22695                final File probeOat = new File(probe, "oat");
22696                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22697                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22698                            "Move only supported for modern cluster style installs");
22699                }
22700            }
22701
22702            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22703                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22704                        "Package already moved to " + volumeUuid);
22705            }
22706            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22707                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22708                        "Device admin cannot be moved");
22709            }
22710
22711            if (mFrozenPackages.contains(packageName)) {
22712                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22713                        "Failed to move already frozen package");
22714            }
22715
22716            codeFile = new File(pkg.codePath);
22717            installerPackageName = ps.installerPackageName;
22718            packageAbiOverride = ps.cpuAbiOverrideString;
22719            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22720            seinfo = pkg.applicationInfo.seInfo;
22721            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22722            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22723            freezer = freezePackage(packageName, "movePackageInternal");
22724            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22725        }
22726
22727        final Bundle extras = new Bundle();
22728        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22729        extras.putString(Intent.EXTRA_TITLE, label);
22730        mMoveCallbacks.notifyCreated(moveId, extras);
22731
22732        int installFlags;
22733        final boolean moveCompleteApp;
22734        final File measurePath;
22735
22736        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22737            installFlags = INSTALL_INTERNAL;
22738            moveCompleteApp = !currentAsec;
22739            measurePath = Environment.getDataAppDirectory(volumeUuid);
22740        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22741            installFlags = INSTALL_EXTERNAL;
22742            moveCompleteApp = false;
22743            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22744        } else {
22745            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22746            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22747                    || !volume.isMountedWritable()) {
22748                freezer.close();
22749                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22750                        "Move location not mounted private volume");
22751            }
22752
22753            Preconditions.checkState(!currentAsec);
22754
22755            installFlags = INSTALL_INTERNAL;
22756            moveCompleteApp = true;
22757            measurePath = Environment.getDataAppDirectory(volumeUuid);
22758        }
22759
22760        // If we're moving app data around, we need all the users unlocked
22761        if (moveCompleteApp) {
22762            for (int userId : installedUserIds) {
22763                if (StorageManager.isFileEncryptedNativeOrEmulated()
22764                        && !StorageManager.isUserKeyUnlocked(userId)) {
22765                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22766                            "User " + userId + " must be unlocked");
22767                }
22768            }
22769        }
22770
22771        final PackageStats stats = new PackageStats(null, -1);
22772        synchronized (mInstaller) {
22773            for (int userId : installedUserIds) {
22774                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22775                    freezer.close();
22776                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22777                            "Failed to measure package size");
22778                }
22779            }
22780        }
22781
22782        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22783                + stats.dataSize);
22784
22785        final long startFreeBytes = measurePath.getUsableSpace();
22786        final long sizeBytes;
22787        if (moveCompleteApp) {
22788            sizeBytes = stats.codeSize + stats.dataSize;
22789        } else {
22790            sizeBytes = stats.codeSize;
22791        }
22792
22793        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22794            freezer.close();
22795            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22796                    "Not enough free space to move");
22797        }
22798
22799        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22800
22801        final CountDownLatch installedLatch = new CountDownLatch(1);
22802        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22803            @Override
22804            public void onUserActionRequired(Intent intent) throws RemoteException {
22805                throw new IllegalStateException();
22806            }
22807
22808            @Override
22809            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22810                    Bundle extras) throws RemoteException {
22811                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22812                        + PackageManager.installStatusToString(returnCode, msg));
22813
22814                installedLatch.countDown();
22815                freezer.close();
22816
22817                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22818                switch (status) {
22819                    case PackageInstaller.STATUS_SUCCESS:
22820                        mMoveCallbacks.notifyStatusChanged(moveId,
22821                                PackageManager.MOVE_SUCCEEDED);
22822                        break;
22823                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22824                        mMoveCallbacks.notifyStatusChanged(moveId,
22825                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22826                        break;
22827                    default:
22828                        mMoveCallbacks.notifyStatusChanged(moveId,
22829                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22830                        break;
22831                }
22832            }
22833        };
22834
22835        final MoveInfo move;
22836        if (moveCompleteApp) {
22837            // Kick off a thread to report progress estimates
22838            new Thread() {
22839                @Override
22840                public void run() {
22841                    while (true) {
22842                        try {
22843                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22844                                break;
22845                            }
22846                        } catch (InterruptedException ignored) {
22847                        }
22848
22849                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22850                        final int progress = 10 + (int) MathUtils.constrain(
22851                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22852                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22853                    }
22854                }
22855            }.start();
22856
22857            final String dataAppName = codeFile.getName();
22858            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22859                    dataAppName, appId, seinfo, targetSdkVersion);
22860        } else {
22861            move = null;
22862        }
22863
22864        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22865
22866        final Message msg = mHandler.obtainMessage(INIT_COPY);
22867        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22868        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22869                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22870                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22871                PackageManager.INSTALL_REASON_UNKNOWN);
22872        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22873        msg.obj = params;
22874
22875        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22876                System.identityHashCode(msg.obj));
22877        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22878                System.identityHashCode(msg.obj));
22879
22880        mHandler.sendMessage(msg);
22881    }
22882
22883    @Override
22884    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22885        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22886
22887        final int realMoveId = mNextMoveId.getAndIncrement();
22888        final Bundle extras = new Bundle();
22889        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22890        mMoveCallbacks.notifyCreated(realMoveId, extras);
22891
22892        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22893            @Override
22894            public void onCreated(int moveId, Bundle extras) {
22895                // Ignored
22896            }
22897
22898            @Override
22899            public void onStatusChanged(int moveId, int status, long estMillis) {
22900                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22901            }
22902        };
22903
22904        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22905        storage.setPrimaryStorageUuid(volumeUuid, callback);
22906        return realMoveId;
22907    }
22908
22909    @Override
22910    public int getMoveStatus(int moveId) {
22911        mContext.enforceCallingOrSelfPermission(
22912                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22913        return mMoveCallbacks.mLastStatus.get(moveId);
22914    }
22915
22916    @Override
22917    public void registerMoveCallback(IPackageMoveObserver callback) {
22918        mContext.enforceCallingOrSelfPermission(
22919                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22920        mMoveCallbacks.register(callback);
22921    }
22922
22923    @Override
22924    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22925        mContext.enforceCallingOrSelfPermission(
22926                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22927        mMoveCallbacks.unregister(callback);
22928    }
22929
22930    @Override
22931    public boolean setInstallLocation(int loc) {
22932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22933                null);
22934        if (getInstallLocation() == loc) {
22935            return true;
22936        }
22937        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22938                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22939            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22940                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22941            return true;
22942        }
22943        return false;
22944   }
22945
22946    @Override
22947    public int getInstallLocation() {
22948        // allow instant app access
22949        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22950                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22951                PackageHelper.APP_INSTALL_AUTO);
22952    }
22953
22954    /** Called by UserManagerService */
22955    void cleanUpUser(UserManagerService userManager, int userHandle) {
22956        synchronized (mPackages) {
22957            mDirtyUsers.remove(userHandle);
22958            mUserNeedsBadging.delete(userHandle);
22959            mSettings.removeUserLPw(userHandle);
22960            mPendingBroadcasts.remove(userHandle);
22961            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22962            removeUnusedPackagesLPw(userManager, userHandle);
22963        }
22964    }
22965
22966    /**
22967     * We're removing userHandle and would like to remove any downloaded packages
22968     * that are no longer in use by any other user.
22969     * @param userHandle the user being removed
22970     */
22971    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22972        final boolean DEBUG_CLEAN_APKS = false;
22973        int [] users = userManager.getUserIds();
22974        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22975        while (psit.hasNext()) {
22976            PackageSetting ps = psit.next();
22977            if (ps.pkg == null) {
22978                continue;
22979            }
22980            final String packageName = ps.pkg.packageName;
22981            // Skip over if system app
22982            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22983                continue;
22984            }
22985            if (DEBUG_CLEAN_APKS) {
22986                Slog.i(TAG, "Checking package " + packageName);
22987            }
22988            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22989            if (keep) {
22990                if (DEBUG_CLEAN_APKS) {
22991                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22992                }
22993            } else {
22994                for (int i = 0; i < users.length; i++) {
22995                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22996                        keep = true;
22997                        if (DEBUG_CLEAN_APKS) {
22998                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22999                                    + users[i]);
23000                        }
23001                        break;
23002                    }
23003                }
23004            }
23005            if (!keep) {
23006                if (DEBUG_CLEAN_APKS) {
23007                    Slog.i(TAG, "  Removing package " + packageName);
23008                }
23009                mHandler.post(new Runnable() {
23010                    public void run() {
23011                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23012                                userHandle, 0);
23013                    } //end run
23014                });
23015            }
23016        }
23017    }
23018
23019    /** Called by UserManagerService */
23020    void createNewUser(int userId, String[] disallowedPackages) {
23021        synchronized (mInstallLock) {
23022            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23023        }
23024        synchronized (mPackages) {
23025            scheduleWritePackageRestrictionsLocked(userId);
23026            scheduleWritePackageListLocked(userId);
23027            applyFactoryDefaultBrowserLPw(userId);
23028            primeDomainVerificationsLPw(userId);
23029        }
23030    }
23031
23032    void onNewUserCreated(final int userId) {
23033        synchronized(mPackages) {
23034            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23035            // If permission review for legacy apps is required, we represent
23036            // dagerous permissions for such apps as always granted runtime
23037            // permissions to keep per user flag state whether review is needed.
23038            // Hence, if a new user is added we have to propagate dangerous
23039            // permission grants for these legacy apps.
23040            if (mPermissionReviewRequired) {
23041                updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23042                        | UPDATE_PERMISSIONS_REPLACE_ALL);
23043            }
23044        }
23045    }
23046
23047    @Override
23048    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23049        mContext.enforceCallingOrSelfPermission(
23050                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23051                "Only package verification agents can read the verifier device identity");
23052
23053        synchronized (mPackages) {
23054            return mSettings.getVerifierDeviceIdentityLPw();
23055        }
23056    }
23057
23058    @Override
23059    public void setPermissionEnforced(String permission, boolean enforced) {
23060        // TODO: Now that we no longer change GID for storage, this should to away.
23061        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23062                "setPermissionEnforced");
23063        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23064            synchronized (mPackages) {
23065                if (mSettings.mReadExternalStorageEnforced == null
23066                        || mSettings.mReadExternalStorageEnforced != enforced) {
23067                    mSettings.mReadExternalStorageEnforced =
23068                            enforced ? Boolean.TRUE : Boolean.FALSE;
23069                    mSettings.writeLPr();
23070                }
23071            }
23072            // kill any non-foreground processes so we restart them and
23073            // grant/revoke the GID.
23074            final IActivityManager am = ActivityManager.getService();
23075            if (am != null) {
23076                final long token = Binder.clearCallingIdentity();
23077                try {
23078                    am.killProcessesBelowForeground("setPermissionEnforcement");
23079                } catch (RemoteException e) {
23080                } finally {
23081                    Binder.restoreCallingIdentity(token);
23082                }
23083            }
23084        } else {
23085            throw new IllegalArgumentException("No selective enforcement for " + permission);
23086        }
23087    }
23088
23089    @Override
23090    @Deprecated
23091    public boolean isPermissionEnforced(String permission) {
23092        // allow instant applications
23093        return true;
23094    }
23095
23096    @Override
23097    public boolean isStorageLow() {
23098        // allow instant applications
23099        final long token = Binder.clearCallingIdentity();
23100        try {
23101            final DeviceStorageMonitorInternal
23102                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23103            if (dsm != null) {
23104                return dsm.isMemoryLow();
23105            } else {
23106                return false;
23107            }
23108        } finally {
23109            Binder.restoreCallingIdentity(token);
23110        }
23111    }
23112
23113    @Override
23114    public IPackageInstaller getPackageInstaller() {
23115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23116            return null;
23117        }
23118        return mInstallerService;
23119    }
23120
23121    private boolean userNeedsBadging(int userId) {
23122        int index = mUserNeedsBadging.indexOfKey(userId);
23123        if (index < 0) {
23124            final UserInfo userInfo;
23125            final long token = Binder.clearCallingIdentity();
23126            try {
23127                userInfo = sUserManager.getUserInfo(userId);
23128            } finally {
23129                Binder.restoreCallingIdentity(token);
23130            }
23131            final boolean b;
23132            if (userInfo != null && userInfo.isManagedProfile()) {
23133                b = true;
23134            } else {
23135                b = false;
23136            }
23137            mUserNeedsBadging.put(userId, b);
23138            return b;
23139        }
23140        return mUserNeedsBadging.valueAt(index);
23141    }
23142
23143    @Override
23144    public KeySet getKeySetByAlias(String packageName, String alias) {
23145        if (packageName == null || alias == null) {
23146            return null;
23147        }
23148        synchronized(mPackages) {
23149            final PackageParser.Package pkg = mPackages.get(packageName);
23150            if (pkg == null) {
23151                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23152                throw new IllegalArgumentException("Unknown package: " + packageName);
23153            }
23154            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23155            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23156                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23157                throw new IllegalArgumentException("Unknown package: " + packageName);
23158            }
23159            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23160            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23161        }
23162    }
23163
23164    @Override
23165    public KeySet getSigningKeySet(String packageName) {
23166        if (packageName == null) {
23167            return null;
23168        }
23169        synchronized(mPackages) {
23170            final int callingUid = Binder.getCallingUid();
23171            final int callingUserId = UserHandle.getUserId(callingUid);
23172            final PackageParser.Package pkg = mPackages.get(packageName);
23173            if (pkg == null) {
23174                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23175                throw new IllegalArgumentException("Unknown package: " + packageName);
23176            }
23177            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23178            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23179                // filter and pretend the package doesn't exist
23180                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23181                        + ", uid:" + callingUid);
23182                throw new IllegalArgumentException("Unknown package: " + packageName);
23183            }
23184            if (pkg.applicationInfo.uid != callingUid
23185                    && Process.SYSTEM_UID != callingUid) {
23186                throw new SecurityException("May not access signing KeySet of other apps.");
23187            }
23188            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23189            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23190        }
23191    }
23192
23193    @Override
23194    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23195        final int callingUid = Binder.getCallingUid();
23196        if (getInstantAppPackageName(callingUid) != null) {
23197            return false;
23198        }
23199        if (packageName == null || ks == null) {
23200            return false;
23201        }
23202        synchronized(mPackages) {
23203            final PackageParser.Package pkg = mPackages.get(packageName);
23204            if (pkg == null
23205                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23206                            UserHandle.getUserId(callingUid))) {
23207                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23208                throw new IllegalArgumentException("Unknown package: " + packageName);
23209            }
23210            IBinder ksh = ks.getToken();
23211            if (ksh instanceof KeySetHandle) {
23212                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23213                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23214            }
23215            return false;
23216        }
23217    }
23218
23219    @Override
23220    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23221        final int callingUid = Binder.getCallingUid();
23222        if (getInstantAppPackageName(callingUid) != null) {
23223            return false;
23224        }
23225        if (packageName == null || ks == null) {
23226            return false;
23227        }
23228        synchronized(mPackages) {
23229            final PackageParser.Package pkg = mPackages.get(packageName);
23230            if (pkg == null
23231                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23232                            UserHandle.getUserId(callingUid))) {
23233                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23234                throw new IllegalArgumentException("Unknown package: " + packageName);
23235            }
23236            IBinder ksh = ks.getToken();
23237            if (ksh instanceof KeySetHandle) {
23238                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23239                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23240            }
23241            return false;
23242        }
23243    }
23244
23245    private void deletePackageIfUnusedLPr(final String packageName) {
23246        PackageSetting ps = mSettings.mPackages.get(packageName);
23247        if (ps == null) {
23248            return;
23249        }
23250        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23251            // TODO Implement atomic delete if package is unused
23252            // It is currently possible that the package will be deleted even if it is installed
23253            // after this method returns.
23254            mHandler.post(new Runnable() {
23255                public void run() {
23256                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23257                            0, PackageManager.DELETE_ALL_USERS);
23258                }
23259            });
23260        }
23261    }
23262
23263    /**
23264     * Check and throw if the given before/after packages would be considered a
23265     * downgrade.
23266     */
23267    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23268            throws PackageManagerException {
23269        if (after.versionCode < before.mVersionCode) {
23270            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23271                    "Update version code " + after.versionCode + " is older than current "
23272                    + before.mVersionCode);
23273        } else if (after.versionCode == before.mVersionCode) {
23274            if (after.baseRevisionCode < before.baseRevisionCode) {
23275                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23276                        "Update base revision code " + after.baseRevisionCode
23277                        + " is older than current " + before.baseRevisionCode);
23278            }
23279
23280            if (!ArrayUtils.isEmpty(after.splitNames)) {
23281                for (int i = 0; i < after.splitNames.length; i++) {
23282                    final String splitName = after.splitNames[i];
23283                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23284                    if (j != -1) {
23285                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23286                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23287                                    "Update split " + splitName + " revision code "
23288                                    + after.splitRevisionCodes[i] + " is older than current "
23289                                    + before.splitRevisionCodes[j]);
23290                        }
23291                    }
23292                }
23293            }
23294        }
23295    }
23296
23297    private static class MoveCallbacks extends Handler {
23298        private static final int MSG_CREATED = 1;
23299        private static final int MSG_STATUS_CHANGED = 2;
23300
23301        private final RemoteCallbackList<IPackageMoveObserver>
23302                mCallbacks = new RemoteCallbackList<>();
23303
23304        private final SparseIntArray mLastStatus = new SparseIntArray();
23305
23306        public MoveCallbacks(Looper looper) {
23307            super(looper);
23308        }
23309
23310        public void register(IPackageMoveObserver callback) {
23311            mCallbacks.register(callback);
23312        }
23313
23314        public void unregister(IPackageMoveObserver callback) {
23315            mCallbacks.unregister(callback);
23316        }
23317
23318        @Override
23319        public void handleMessage(Message msg) {
23320            final SomeArgs args = (SomeArgs) msg.obj;
23321            final int n = mCallbacks.beginBroadcast();
23322            for (int i = 0; i < n; i++) {
23323                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23324                try {
23325                    invokeCallback(callback, msg.what, args);
23326                } catch (RemoteException ignored) {
23327                }
23328            }
23329            mCallbacks.finishBroadcast();
23330            args.recycle();
23331        }
23332
23333        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23334                throws RemoteException {
23335            switch (what) {
23336                case MSG_CREATED: {
23337                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23338                    break;
23339                }
23340                case MSG_STATUS_CHANGED: {
23341                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23342                    break;
23343                }
23344            }
23345        }
23346
23347        private void notifyCreated(int moveId, Bundle extras) {
23348            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23349
23350            final SomeArgs args = SomeArgs.obtain();
23351            args.argi1 = moveId;
23352            args.arg2 = extras;
23353            obtainMessage(MSG_CREATED, args).sendToTarget();
23354        }
23355
23356        private void notifyStatusChanged(int moveId, int status) {
23357            notifyStatusChanged(moveId, status, -1);
23358        }
23359
23360        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23361            Slog.v(TAG, "Move " + moveId + " status " + status);
23362
23363            final SomeArgs args = SomeArgs.obtain();
23364            args.argi1 = moveId;
23365            args.argi2 = status;
23366            args.arg3 = estMillis;
23367            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23368
23369            synchronized (mLastStatus) {
23370                mLastStatus.put(moveId, status);
23371            }
23372        }
23373    }
23374
23375    private final static class OnPermissionChangeListeners extends Handler {
23376        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23377
23378        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23379                new RemoteCallbackList<>();
23380
23381        public OnPermissionChangeListeners(Looper looper) {
23382            super(looper);
23383        }
23384
23385        @Override
23386        public void handleMessage(Message msg) {
23387            switch (msg.what) {
23388                case MSG_ON_PERMISSIONS_CHANGED: {
23389                    final int uid = msg.arg1;
23390                    handleOnPermissionsChanged(uid);
23391                } break;
23392            }
23393        }
23394
23395        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23396            mPermissionListeners.register(listener);
23397
23398        }
23399
23400        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23401            mPermissionListeners.unregister(listener);
23402        }
23403
23404        public void onPermissionsChanged(int uid) {
23405            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23406                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23407            }
23408        }
23409
23410        private void handleOnPermissionsChanged(int uid) {
23411            final int count = mPermissionListeners.beginBroadcast();
23412            try {
23413                for (int i = 0; i < count; i++) {
23414                    IOnPermissionsChangeListener callback = mPermissionListeners
23415                            .getBroadcastItem(i);
23416                    try {
23417                        callback.onPermissionsChanged(uid);
23418                    } catch (RemoteException e) {
23419                        Log.e(TAG, "Permission listener is dead", e);
23420                    }
23421                }
23422            } finally {
23423                mPermissionListeners.finishBroadcast();
23424            }
23425        }
23426    }
23427
23428    private class PackageManagerNative extends IPackageManagerNative.Stub {
23429        @Override
23430        public String[] getNamesForUids(int[] uids) throws RemoteException {
23431            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23432            // massage results so they can be parsed by the native binder
23433            for (int i = results.length - 1; i >= 0; --i) {
23434                if (results[i] == null) {
23435                    results[i] = "";
23436                }
23437            }
23438            return results;
23439        }
23440
23441        // NB: this differentiates between preloads and sideloads
23442        @Override
23443        public String getInstallerForPackage(String packageName) throws RemoteException {
23444            final String installerName = getInstallerPackageName(packageName);
23445            if (!TextUtils.isEmpty(installerName)) {
23446                return installerName;
23447            }
23448            // differentiate between preload and sideload
23449            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23450            ApplicationInfo appInfo = getApplicationInfo(packageName,
23451                                    /*flags*/ 0,
23452                                    /*userId*/ callingUser);
23453            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23454                return "preload";
23455            }
23456            return "";
23457        }
23458
23459        @Override
23460        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23461            try {
23462                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23463                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23464                if (pInfo != null) {
23465                    return pInfo.versionCode;
23466                }
23467            } catch (Exception e) {
23468            }
23469            return 0;
23470        }
23471    }
23472
23473    private class PackageManagerInternalImpl extends PackageManagerInternal {
23474        @Override
23475        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23476                int flagValues, int userId) {
23477            PackageManagerService.this.updatePermissionFlags(
23478                    permName, packageName, flagMask, flagValues, userId);
23479        }
23480
23481        @Override
23482        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23483            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23484        }
23485
23486        @Override
23487        public boolean isInstantApp(String packageName, int userId) {
23488            return PackageManagerService.this.isInstantApp(packageName, userId);
23489        }
23490
23491        @Override
23492        public String getInstantAppPackageName(int uid) {
23493            return PackageManagerService.this.getInstantAppPackageName(uid);
23494        }
23495
23496        @Override
23497        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23498            synchronized (mPackages) {
23499                return PackageManagerService.this.filterAppAccessLPr(
23500                        (PackageSetting) pkg.mExtras, callingUid, userId);
23501            }
23502        }
23503
23504        @Override
23505        public PackageParser.Package getPackage(String packageName) {
23506            synchronized (mPackages) {
23507                packageName = resolveInternalPackageNameLPr(
23508                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23509                return mPackages.get(packageName);
23510            }
23511        }
23512
23513        @Override
23514        public PackageParser.Package getDisabledPackage(String packageName) {
23515            synchronized (mPackages) {
23516                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23517                return (ps != null) ? ps.pkg : null;
23518            }
23519        }
23520
23521        @Override
23522        public String getKnownPackageName(int knownPackage, int userId) {
23523            switch(knownPackage) {
23524                case PackageManagerInternal.PACKAGE_BROWSER:
23525                    return getDefaultBrowserPackageName(userId);
23526                case PackageManagerInternal.PACKAGE_INSTALLER:
23527                    return mRequiredInstallerPackage;
23528                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23529                    return mSetupWizardPackage;
23530                case PackageManagerInternal.PACKAGE_SYSTEM:
23531                    return "android";
23532                case PackageManagerInternal.PACKAGE_VERIFIER:
23533                    return mRequiredVerifierPackage;
23534            }
23535            return null;
23536        }
23537
23538        @Override
23539        public boolean isResolveActivityComponent(ComponentInfo component) {
23540            return mResolveActivity.packageName.equals(component.packageName)
23541                    && mResolveActivity.name.equals(component.name);
23542        }
23543
23544        @Override
23545        public void setLocationPackagesProvider(PackagesProvider provider) {
23546            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23547        }
23548
23549        @Override
23550        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23551            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23552        }
23553
23554        @Override
23555        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23556            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23557        }
23558
23559        @Override
23560        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23561            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23562        }
23563
23564        @Override
23565        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23566            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23567        }
23568
23569        @Override
23570        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23571            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23572        }
23573
23574        @Override
23575        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23576            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23577        }
23578
23579        @Override
23580        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23581            synchronized (mPackages) {
23582                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23583            }
23584            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23585        }
23586
23587        @Override
23588        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23589            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23590                    packageName, userId);
23591        }
23592
23593        @Override
23594        public void setKeepUninstalledPackages(final List<String> packageList) {
23595            Preconditions.checkNotNull(packageList);
23596            List<String> removedFromList = null;
23597            synchronized (mPackages) {
23598                if (mKeepUninstalledPackages != null) {
23599                    final int packagesCount = mKeepUninstalledPackages.size();
23600                    for (int i = 0; i < packagesCount; i++) {
23601                        String oldPackage = mKeepUninstalledPackages.get(i);
23602                        if (packageList != null && packageList.contains(oldPackage)) {
23603                            continue;
23604                        }
23605                        if (removedFromList == null) {
23606                            removedFromList = new ArrayList<>();
23607                        }
23608                        removedFromList.add(oldPackage);
23609                    }
23610                }
23611                mKeepUninstalledPackages = new ArrayList<>(packageList);
23612                if (removedFromList != null) {
23613                    final int removedCount = removedFromList.size();
23614                    for (int i = 0; i < removedCount; i++) {
23615                        deletePackageIfUnusedLPr(removedFromList.get(i));
23616                    }
23617                }
23618            }
23619        }
23620
23621        @Override
23622        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23623            synchronized (mPackages) {
23624                // If we do not support permission review, done.
23625                if (!mPermissionReviewRequired) {
23626                    return false;
23627                }
23628
23629                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23630                if (packageSetting == null) {
23631                    return false;
23632                }
23633
23634                // Permission review applies only to apps not supporting the new permission model.
23635                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23636                    return false;
23637                }
23638
23639                // Legacy apps have the permission and get user consent on launch.
23640                PermissionsState permissionsState = packageSetting.getPermissionsState();
23641                return permissionsState.isPermissionReviewRequired(userId);
23642            }
23643        }
23644
23645        @Override
23646        public PackageInfo getPackageInfo(
23647                String packageName, int flags, int filterCallingUid, int userId) {
23648            return PackageManagerService.this
23649                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23650                            flags, filterCallingUid, userId);
23651        }
23652
23653        @Override
23654        public ApplicationInfo getApplicationInfo(
23655                String packageName, int flags, int filterCallingUid, int userId) {
23656            return PackageManagerService.this
23657                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23658        }
23659
23660        @Override
23661        public ActivityInfo getActivityInfo(
23662                ComponentName component, int flags, int filterCallingUid, int userId) {
23663            return PackageManagerService.this
23664                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23665        }
23666
23667        @Override
23668        public List<ResolveInfo> queryIntentActivities(
23669                Intent intent, int flags, int filterCallingUid, int userId) {
23670            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23671            return PackageManagerService.this
23672                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23673                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23674        }
23675
23676        @Override
23677        public List<ResolveInfo> queryIntentServices(
23678                Intent intent, int flags, int callingUid, int userId) {
23679            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23680            return PackageManagerService.this
23681                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23682                            false);
23683        }
23684
23685        @Override
23686        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23687                int userId) {
23688            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23689        }
23690
23691        @Override
23692        public void setDeviceAndProfileOwnerPackages(
23693                int deviceOwnerUserId, String deviceOwnerPackage,
23694                SparseArray<String> profileOwnerPackages) {
23695            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23696                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23697        }
23698
23699        @Override
23700        public boolean isPackageDataProtected(int userId, String packageName) {
23701            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23702        }
23703
23704        @Override
23705        public boolean isPackageEphemeral(int userId, String packageName) {
23706            synchronized (mPackages) {
23707                final PackageSetting ps = mSettings.mPackages.get(packageName);
23708                return ps != null ? ps.getInstantApp(userId) : false;
23709            }
23710        }
23711
23712        @Override
23713        public boolean wasPackageEverLaunched(String packageName, int userId) {
23714            synchronized (mPackages) {
23715                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23716            }
23717        }
23718
23719        @Override
23720        public void grantRuntimePermission(String packageName, String permName, int userId,
23721                boolean overridePolicy) {
23722            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23723                    permName, packageName, overridePolicy, getCallingUid(), userId,
23724                    mPermissionCallback);
23725        }
23726
23727        @Override
23728        public void revokeRuntimePermission(String packageName, String permName, int userId,
23729                boolean overridePolicy) {
23730            mPermissionManager.revokeRuntimePermission(
23731                    permName, packageName, overridePolicy, getCallingUid(), userId,
23732                    mPermissionCallback);
23733        }
23734
23735        @Override
23736        public String getNameForUid(int uid) {
23737            return PackageManagerService.this.getNameForUid(uid);
23738        }
23739
23740        @Override
23741        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23742                Intent origIntent, String resolvedType, String callingPackage,
23743                Bundle verificationBundle, int userId) {
23744            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23745                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23746                    userId);
23747        }
23748
23749        @Override
23750        public void grantEphemeralAccess(int userId, Intent intent,
23751                int targetAppId, int ephemeralAppId) {
23752            synchronized (mPackages) {
23753                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23754                        targetAppId, ephemeralAppId);
23755            }
23756        }
23757
23758        @Override
23759        public boolean isInstantAppInstallerComponent(ComponentName component) {
23760            synchronized (mPackages) {
23761                return mInstantAppInstallerActivity != null
23762                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23763            }
23764        }
23765
23766        @Override
23767        public void pruneInstantApps() {
23768            mInstantAppRegistry.pruneInstantApps();
23769        }
23770
23771        @Override
23772        public String getSetupWizardPackageName() {
23773            return mSetupWizardPackage;
23774        }
23775
23776        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23777            if (policy != null) {
23778                mExternalSourcesPolicy = policy;
23779            }
23780        }
23781
23782        @Override
23783        public boolean isPackagePersistent(String packageName) {
23784            synchronized (mPackages) {
23785                PackageParser.Package pkg = mPackages.get(packageName);
23786                return pkg != null
23787                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23788                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23789                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23790                        : false;
23791            }
23792        }
23793
23794        @Override
23795        public List<PackageInfo> getOverlayPackages(int userId) {
23796            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23797            synchronized (mPackages) {
23798                for (PackageParser.Package p : mPackages.values()) {
23799                    if (p.mOverlayTarget != null) {
23800                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23801                        if (pkg != null) {
23802                            overlayPackages.add(pkg);
23803                        }
23804                    }
23805                }
23806            }
23807            return overlayPackages;
23808        }
23809
23810        @Override
23811        public List<String> getTargetPackageNames(int userId) {
23812            List<String> targetPackages = new ArrayList<>();
23813            synchronized (mPackages) {
23814                for (PackageParser.Package p : mPackages.values()) {
23815                    if (p.mOverlayTarget == null) {
23816                        targetPackages.add(p.packageName);
23817                    }
23818                }
23819            }
23820            return targetPackages;
23821        }
23822
23823        @Override
23824        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23825                @Nullable List<String> overlayPackageNames) {
23826            synchronized (mPackages) {
23827                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23828                    Slog.e(TAG, "failed to find package " + targetPackageName);
23829                    return false;
23830                }
23831                ArrayList<String> overlayPaths = null;
23832                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23833                    final int N = overlayPackageNames.size();
23834                    overlayPaths = new ArrayList<>(N);
23835                    for (int i = 0; i < N; i++) {
23836                        final String packageName = overlayPackageNames.get(i);
23837                        final PackageParser.Package pkg = mPackages.get(packageName);
23838                        if (pkg == null) {
23839                            Slog.e(TAG, "failed to find package " + packageName);
23840                            return false;
23841                        }
23842                        overlayPaths.add(pkg.baseCodePath);
23843                    }
23844                }
23845
23846                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23847                ps.setOverlayPaths(overlayPaths, userId);
23848                return true;
23849            }
23850        }
23851
23852        @Override
23853        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23854                int flags, int userId, boolean resolveForStart) {
23855            return resolveIntentInternal(
23856                    intent, resolvedType, flags, userId, resolveForStart);
23857        }
23858
23859        @Override
23860        public ResolveInfo resolveService(Intent intent, String resolvedType,
23861                int flags, int userId, int callingUid) {
23862            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23863        }
23864
23865        @Override
23866        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23867            return PackageManagerService.this.resolveContentProviderInternal(
23868                    name, flags, userId);
23869        }
23870
23871        @Override
23872        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23873            synchronized (mPackages) {
23874                mIsolatedOwners.put(isolatedUid, ownerUid);
23875            }
23876        }
23877
23878        @Override
23879        public void removeIsolatedUid(int isolatedUid) {
23880            synchronized (mPackages) {
23881                mIsolatedOwners.delete(isolatedUid);
23882            }
23883        }
23884
23885        @Override
23886        public int getUidTargetSdkVersion(int uid) {
23887            synchronized (mPackages) {
23888                return getUidTargetSdkVersionLockedLPr(uid);
23889            }
23890        }
23891
23892        @Override
23893        public boolean canAccessInstantApps(int callingUid, int userId) {
23894            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23895        }
23896
23897        @Override
23898        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23899            synchronized (mPackages) {
23900                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23901            }
23902        }
23903
23904        @Override
23905        public void notifyPackageUse(String packageName, int reason) {
23906            synchronized (mPackages) {
23907                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23908            }
23909        }
23910    }
23911
23912    @Override
23913    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23914        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23915        synchronized (mPackages) {
23916            final long identity = Binder.clearCallingIdentity();
23917            try {
23918                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23919                        packageNames, userId);
23920            } finally {
23921                Binder.restoreCallingIdentity(identity);
23922            }
23923        }
23924    }
23925
23926    @Override
23927    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23928        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23929        synchronized (mPackages) {
23930            final long identity = Binder.clearCallingIdentity();
23931            try {
23932                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23933                        packageNames, userId);
23934            } finally {
23935                Binder.restoreCallingIdentity(identity);
23936            }
23937        }
23938    }
23939
23940    private static void enforceSystemOrPhoneCaller(String tag) {
23941        int callingUid = Binder.getCallingUid();
23942        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23943            throw new SecurityException(
23944                    "Cannot call " + tag + " from UID " + callingUid);
23945        }
23946    }
23947
23948    boolean isHistoricalPackageUsageAvailable() {
23949        return mPackageUsage.isHistoricalPackageUsageAvailable();
23950    }
23951
23952    /**
23953     * Return a <b>copy</b> of the collection of packages known to the package manager.
23954     * @return A copy of the values of mPackages.
23955     */
23956    Collection<PackageParser.Package> getPackages() {
23957        synchronized (mPackages) {
23958            return new ArrayList<>(mPackages.values());
23959        }
23960    }
23961
23962    /**
23963     * Logs process start information (including base APK hash) to the security log.
23964     * @hide
23965     */
23966    @Override
23967    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23968            String apkFile, int pid) {
23969        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23970            return;
23971        }
23972        if (!SecurityLog.isLoggingEnabled()) {
23973            return;
23974        }
23975        Bundle data = new Bundle();
23976        data.putLong("startTimestamp", System.currentTimeMillis());
23977        data.putString("processName", processName);
23978        data.putInt("uid", uid);
23979        data.putString("seinfo", seinfo);
23980        data.putString("apkFile", apkFile);
23981        data.putInt("pid", pid);
23982        Message msg = mProcessLoggingHandler.obtainMessage(
23983                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23984        msg.setData(data);
23985        mProcessLoggingHandler.sendMessage(msg);
23986    }
23987
23988    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23989        return mCompilerStats.getPackageStats(pkgName);
23990    }
23991
23992    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23993        return getOrCreateCompilerPackageStats(pkg.packageName);
23994    }
23995
23996    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23997        return mCompilerStats.getOrCreatePackageStats(pkgName);
23998    }
23999
24000    public void deleteCompilerPackageStats(String pkgName) {
24001        mCompilerStats.deletePackageStats(pkgName);
24002    }
24003
24004    @Override
24005    public int getInstallReason(String packageName, int userId) {
24006        final int callingUid = Binder.getCallingUid();
24007        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24008                true /* requireFullPermission */, false /* checkShell */,
24009                "get install reason");
24010        synchronized (mPackages) {
24011            final PackageSetting ps = mSettings.mPackages.get(packageName);
24012            if (filterAppAccessLPr(ps, callingUid, userId)) {
24013                return PackageManager.INSTALL_REASON_UNKNOWN;
24014            }
24015            if (ps != null) {
24016                return ps.getInstallReason(userId);
24017            }
24018        }
24019        return PackageManager.INSTALL_REASON_UNKNOWN;
24020    }
24021
24022    @Override
24023    public boolean canRequestPackageInstalls(String packageName, int userId) {
24024        return canRequestPackageInstallsInternal(packageName, 0, userId,
24025                true /* throwIfPermNotDeclared*/);
24026    }
24027
24028    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24029            boolean throwIfPermNotDeclared) {
24030        int callingUid = Binder.getCallingUid();
24031        int uid = getPackageUid(packageName, 0, userId);
24032        if (callingUid != uid && callingUid != Process.ROOT_UID
24033                && callingUid != Process.SYSTEM_UID) {
24034            throw new SecurityException(
24035                    "Caller uid " + callingUid + " does not own package " + packageName);
24036        }
24037        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24038        if (info == null) {
24039            return false;
24040        }
24041        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24042            return false;
24043        }
24044        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24045        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24046        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24047            if (throwIfPermNotDeclared) {
24048                throw new SecurityException("Need to declare " + appOpPermission
24049                        + " to call this api");
24050            } else {
24051                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24052                return false;
24053            }
24054        }
24055        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24056            return false;
24057        }
24058        if (mExternalSourcesPolicy != null) {
24059            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24060            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24061                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24062            }
24063        }
24064        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24065    }
24066
24067    @Override
24068    public ComponentName getInstantAppResolverSettingsComponent() {
24069        return mInstantAppResolverSettingsComponent;
24070    }
24071
24072    @Override
24073    public ComponentName getInstantAppInstallerComponent() {
24074        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24075            return null;
24076        }
24077        return mInstantAppInstallerActivity == null
24078                ? null : mInstantAppInstallerActivity.getComponentName();
24079    }
24080
24081    @Override
24082    public String getInstantAppAndroidId(String packageName, int userId) {
24083        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24084                "getInstantAppAndroidId");
24085        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24086                true /* requireFullPermission */, false /* checkShell */,
24087                "getInstantAppAndroidId");
24088        // Make sure the target is an Instant App.
24089        if (!isInstantApp(packageName, userId)) {
24090            return null;
24091        }
24092        synchronized (mPackages) {
24093            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24094        }
24095    }
24096
24097    boolean canHaveOatDir(String packageName) {
24098        synchronized (mPackages) {
24099            PackageParser.Package p = mPackages.get(packageName);
24100            if (p == null) {
24101                return false;
24102            }
24103            return p.canHaveOatDir();
24104        }
24105    }
24106
24107    private String getOatDir(PackageParser.Package pkg) {
24108        if (!pkg.canHaveOatDir()) {
24109            return null;
24110        }
24111        File codePath = new File(pkg.codePath);
24112        if (codePath.isDirectory()) {
24113            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24114        }
24115        return null;
24116    }
24117
24118    void deleteOatArtifactsOfPackage(String packageName) {
24119        final String[] instructionSets;
24120        final List<String> codePaths;
24121        final String oatDir;
24122        final PackageParser.Package pkg;
24123        synchronized (mPackages) {
24124            pkg = mPackages.get(packageName);
24125        }
24126        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24127        codePaths = pkg.getAllCodePaths();
24128        oatDir = getOatDir(pkg);
24129
24130        for (String codePath : codePaths) {
24131            for (String isa : instructionSets) {
24132                try {
24133                    mInstaller.deleteOdex(codePath, isa, oatDir);
24134                } catch (InstallerException e) {
24135                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24136                }
24137            }
24138        }
24139    }
24140
24141    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24142        Set<String> unusedPackages = new HashSet<>();
24143        long currentTimeInMillis = System.currentTimeMillis();
24144        synchronized (mPackages) {
24145            for (PackageParser.Package pkg : mPackages.values()) {
24146                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24147                if (ps == null) {
24148                    continue;
24149                }
24150                PackageDexUsage.PackageUseInfo packageUseInfo =
24151                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24152                if (PackageManagerServiceUtils
24153                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24154                                downgradeTimeThresholdMillis, packageUseInfo,
24155                                pkg.getLatestPackageUseTimeInMills(),
24156                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24157                    unusedPackages.add(pkg.packageName);
24158                }
24159            }
24160        }
24161        return unusedPackages;
24162    }
24163}
24164
24165interface PackageSender {
24166    void sendPackageBroadcast(final String action, final String pkg,
24167        final Bundle extras, final int flags, final String targetPkg,
24168        final IIntentReceiver finishedReceiver, final int[] userIds);
24169    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24170        boolean includeStopped, int appId, int... userIds);
24171}
24172