PackageManagerService.java revision 460f28c2f017dcef9c34a93c7bd5b18e97c6e15f
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    // System configuration read by SystemConfig.
757    final int[] mGlobalGids;
758    final SparseArray<ArraySet<String>> mSystemPermissions;
759    @GuardedBy("mAvailableFeatures")
760    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
761
762    // If mac_permissions.xml was found for seinfo labeling.
763    boolean mFoundPolicyFile;
764
765    private final InstantAppRegistry mInstantAppRegistry;
766
767    @GuardedBy("mPackages")
768    int mChangedPackagesSequenceNumber;
769    /**
770     * List of changed [installed, removed or updated] packages.
771     * mapping from user id -> sequence number -> package name
772     */
773    @GuardedBy("mPackages")
774    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
775    /**
776     * The sequence number of the last change to a package.
777     * mapping from user id -> package name -> sequence number
778     */
779    @GuardedBy("mPackages")
780    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
781
782    class PackageParserCallback implements PackageParser.Callback {
783        @Override public final boolean hasFeature(String feature) {
784            return PackageManagerService.this.hasSystemFeature(feature, 0);
785        }
786
787        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
788                Collection<PackageParser.Package> allPackages, String targetPackageName) {
789            List<PackageParser.Package> overlayPackages = null;
790            for (PackageParser.Package p : allPackages) {
791                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
792                    if (overlayPackages == null) {
793                        overlayPackages = new ArrayList<PackageParser.Package>();
794                    }
795                    overlayPackages.add(p);
796                }
797            }
798            if (overlayPackages != null) {
799                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
800                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
801                        return p1.mOverlayPriority - p2.mOverlayPriority;
802                    }
803                };
804                Collections.sort(overlayPackages, cmp);
805            }
806            return overlayPackages;
807        }
808
809        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
810                String targetPackageName, String targetPath) {
811            if ("android".equals(targetPackageName)) {
812                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
813                // native AssetManager.
814                return null;
815            }
816            List<PackageParser.Package> overlayPackages =
817                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
818            if (overlayPackages == null || overlayPackages.isEmpty()) {
819                return null;
820            }
821            List<String> overlayPathList = null;
822            for (PackageParser.Package overlayPackage : overlayPackages) {
823                if (targetPath == null) {
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                    continue;
829                }
830
831                try {
832                    // Creates idmaps for system to parse correctly the Android manifest of the
833                    // target package.
834                    //
835                    // OverlayManagerService will update each of them with a correct gid from its
836                    // target package app id.
837                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
838                            UserHandle.getSharedAppGid(
839                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
840                    if (overlayPathList == null) {
841                        overlayPathList = new ArrayList<String>();
842                    }
843                    overlayPathList.add(overlayPackage.baseCodePath);
844                } catch (InstallerException e) {
845                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
846                            overlayPackage.baseCodePath);
847                }
848            }
849            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
850        }
851
852        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
853            synchronized (mPackages) {
854                return getStaticOverlayPathsLocked(
855                        mPackages.values(), targetPackageName, targetPath);
856            }
857        }
858
859        @Override public final String[] getOverlayApks(String targetPackageName) {
860            return getStaticOverlayPaths(targetPackageName, null);
861        }
862
863        @Override public final String[] getOverlayPaths(String targetPackageName,
864                String targetPath) {
865            return getStaticOverlayPaths(targetPackageName, targetPath);
866        }
867    }
868
869    class ParallelPackageParserCallback extends PackageParserCallback {
870        List<PackageParser.Package> mOverlayPackages = null;
871
872        void findStaticOverlayPackages() {
873            synchronized (mPackages) {
874                for (PackageParser.Package p : mPackages.values()) {
875                    if (p.mIsStaticOverlay) {
876                        if (mOverlayPackages == null) {
877                            mOverlayPackages = new ArrayList<PackageParser.Package>();
878                        }
879                        mOverlayPackages.add(p);
880                    }
881                }
882            }
883        }
884
885        @Override
886        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
887            // We can trust mOverlayPackages without holding mPackages because package uninstall
888            // can't happen while running parallel parsing.
889            // Moreover holding mPackages on each parsing thread causes dead-lock.
890            return mOverlayPackages == null ? null :
891                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
892        }
893    }
894
895    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
896    final ParallelPackageParserCallback mParallelPackageParserCallback =
897            new ParallelPackageParserCallback();
898
899    public static final class SharedLibraryEntry {
900        public final @Nullable String path;
901        public final @Nullable String apk;
902        public final @NonNull SharedLibraryInfo info;
903
904        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
905                String declaringPackageName, int declaringPackageVersionCode) {
906            path = _path;
907            apk = _apk;
908            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
909                    declaringPackageName, declaringPackageVersionCode), null);
910        }
911    }
912
913    // Currently known shared libraries.
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
915    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
916            new ArrayMap<>();
917
918    // All available activities, for your resolving pleasure.
919    final ActivityIntentResolver mActivities =
920            new ActivityIntentResolver();
921
922    // All available receivers, for your resolving pleasure.
923    final ActivityIntentResolver mReceivers =
924            new ActivityIntentResolver();
925
926    // All available services, for your resolving pleasure.
927    final ServiceIntentResolver mServices = new ServiceIntentResolver();
928
929    // All available providers, for your resolving pleasure.
930    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
931
932    // Mapping from provider base names (first directory in content URI codePath)
933    // to the provider information.
934    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
935            new ArrayMap<String, PackageParser.Provider>();
936
937    // Mapping from instrumentation class names to info about them.
938    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
939            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
940
941    // Packages whose data we have transfered into another package, thus
942    // should no longer exist.
943    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
944
945    // Broadcast actions that are only available to the system.
946    @GuardedBy("mProtectedBroadcasts")
947    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
948
949    /** List of packages waiting for verification. */
950    final SparseArray<PackageVerificationState> mPendingVerification
951            = new SparseArray<PackageVerificationState>();
952
953    final PackageInstallerService mInstallerService;
954
955    private final PackageDexOptimizer mPackageDexOptimizer;
956    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
957    // is used by other apps).
958    private final DexManager mDexManager;
959
960    private AtomicInteger mNextMoveId = new AtomicInteger();
961    private final MoveCallbacks mMoveCallbacks;
962
963    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
964
965    // Cache of users who need badging.
966    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
967
968    /** Token for keys in mPendingVerification. */
969    private int mPendingVerificationToken = 0;
970
971    volatile boolean mSystemReady;
972    volatile boolean mSafeMode;
973    volatile boolean mHasSystemUidErrors;
974    private volatile boolean mEphemeralAppsDisabled;
975
976    ApplicationInfo mAndroidApplication;
977    final ActivityInfo mResolveActivity = new ActivityInfo();
978    final ResolveInfo mResolveInfo = new ResolveInfo();
979    ComponentName mResolveComponentName;
980    PackageParser.Package mPlatformPackage;
981    ComponentName mCustomResolverComponentName;
982
983    boolean mResolverReplaced = false;
984
985    private final @Nullable ComponentName mIntentFilterVerifierComponent;
986    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
987
988    private int mIntentFilterVerificationToken = 0;
989
990    /** The service connection to the ephemeral resolver */
991    final EphemeralResolverConnection mInstantAppResolverConnection;
992    /** Component used to show resolver settings for Instant Apps */
993    final ComponentName mInstantAppResolverSettingsComponent;
994
995    /** Activity used to install instant applications */
996    ActivityInfo mInstantAppInstallerActivity;
997    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
998
999    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1000            = new SparseArray<IntentFilterVerificationState>();
1001
1002    // TODO remove this and go through mPermissonManager directly
1003    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1004    private final PermissionManagerInternal mPermissionManager;
1005
1006    // List of packages names to keep cached, even if they are uninstalled for all users
1007    private List<String> mKeepUninstalledPackages;
1008
1009    private UserManagerInternal mUserManagerInternal;
1010
1011    private DeviceIdleController.LocalService mDeviceIdleController;
1012
1013    private File mCacheDir;
1014
1015    private ArraySet<String> mPrivappPermissionsViolations;
1016
1017    private Future<?> mPrepareAppDataFuture;
1018
1019    private static class IFVerificationParams {
1020        PackageParser.Package pkg;
1021        boolean replacing;
1022        int userId;
1023        int verifierUid;
1024
1025        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1026                int _userId, int _verifierUid) {
1027            pkg = _pkg;
1028            replacing = _replacing;
1029            userId = _userId;
1030            replacing = _replacing;
1031            verifierUid = _verifierUid;
1032        }
1033    }
1034
1035    private interface IntentFilterVerifier<T extends IntentFilter> {
1036        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1037                                               T filter, String packageName);
1038        void startVerifications(int userId);
1039        void receiveVerificationResponse(int verificationId);
1040    }
1041
1042    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1043        private Context mContext;
1044        private ComponentName mIntentFilterVerifierComponent;
1045        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1046
1047        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1048            mContext = context;
1049            mIntentFilterVerifierComponent = verifierComponent;
1050        }
1051
1052        private String getDefaultScheme() {
1053            return IntentFilter.SCHEME_HTTPS;
1054        }
1055
1056        @Override
1057        public void startVerifications(int userId) {
1058            // Launch verifications requests
1059            int count = mCurrentIntentFilterVerifications.size();
1060            for (int n=0; n<count; n++) {
1061                int verificationId = mCurrentIntentFilterVerifications.get(n);
1062                final IntentFilterVerificationState ivs =
1063                        mIntentFilterVerificationStates.get(verificationId);
1064
1065                String packageName = ivs.getPackageName();
1066
1067                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1068                final int filterCount = filters.size();
1069                ArraySet<String> domainsSet = new ArraySet<>();
1070                for (int m=0; m<filterCount; m++) {
1071                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1072                    domainsSet.addAll(filter.getHostsList());
1073                }
1074                synchronized (mPackages) {
1075                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1076                            packageName, domainsSet) != null) {
1077                        scheduleWriteSettingsLocked();
1078                    }
1079                }
1080                sendVerificationRequest(verificationId, ivs);
1081            }
1082            mCurrentIntentFilterVerifications.clear();
1083        }
1084
1085        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1086            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1089                    verificationId);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1092                    getDefaultScheme());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1095                    ivs.getHostsString());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1098                    ivs.getPackageName());
1099            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1100            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1101
1102            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1103            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1104                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1105                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1106
1107            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Sending IntentFilter verification broadcast");
1110        }
1111
1112        public void receiveVerificationResponse(int verificationId) {
1113            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1114
1115            final boolean verified = ivs.isVerified();
1116
1117            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1118            final int count = filters.size();
1119            if (DEBUG_DOMAIN_VERIFICATION) {
1120                Slog.i(TAG, "Received verification response " + verificationId
1121                        + " for " + count + " filters, verified=" + verified);
1122            }
1123            for (int n=0; n<count; n++) {
1124                PackageParser.ActivityIntentInfo filter = filters.get(n);
1125                filter.setVerified(verified);
1126
1127                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1128                        + " verified with result:" + verified + " and hosts:"
1129                        + ivs.getHostsString());
1130            }
1131
1132            mIntentFilterVerificationStates.remove(verificationId);
1133
1134            final String packageName = ivs.getPackageName();
1135            IntentFilterVerificationInfo ivi = null;
1136
1137            synchronized (mPackages) {
1138                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1139            }
1140            if (ivi == null) {
1141                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1142                        + verificationId + " packageName:" + packageName);
1143                return;
1144            }
1145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1146                    "Updating IntentFilterVerificationInfo for package " + packageName
1147                            +" verificationId:" + verificationId);
1148
1149            synchronized (mPackages) {
1150                if (verified) {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1152                } else {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1154                }
1155                scheduleWriteSettingsLocked();
1156
1157                final int userId = ivs.getUserId();
1158                if (userId != UserHandle.USER_ALL) {
1159                    final int userStatus =
1160                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1161
1162                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1163                    boolean needUpdate = false;
1164
1165                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1166                    // already been set by the User thru the Disambiguation dialog
1167                    switch (userStatus) {
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                            } else {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1173                            }
1174                            needUpdate = true;
1175                            break;
1176
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                                needUpdate = true;
1181                            }
1182                            break;
1183
1184                        default:
1185                            // Nothing to do
1186                    }
1187
1188                    if (needUpdate) {
1189                        mSettings.updateIntentFilterVerificationStatusLPw(
1190                                packageName, updatedStatus, userId);
1191                        scheduleWritePackageRestrictionsLocked(userId);
1192                    }
1193                }
1194            }
1195        }
1196
1197        @Override
1198        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1199                    ActivityIntentInfo filter, String packageName) {
1200            if (!hasValidDomains(filter)) {
1201                return false;
1202            }
1203            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1204            if (ivs == null) {
1205                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1206                        packageName);
1207            }
1208            if (DEBUG_DOMAIN_VERIFICATION) {
1209                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1210            }
1211            ivs.addFilter(filter);
1212            return true;
1213        }
1214
1215        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1216                int userId, int verificationId, String packageName) {
1217            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1218                    verifierUid, userId, packageName);
1219            ivs.setPendingState();
1220            synchronized (mPackages) {
1221                mIntentFilterVerificationStates.append(verificationId, ivs);
1222                mCurrentIntentFilterVerifications.add(verificationId);
1223            }
1224            return ivs;
1225        }
1226    }
1227
1228    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1229        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1230                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1231                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1232    }
1233
1234    // Set of pending broadcasts for aggregating enable/disable of components.
1235    static class PendingPackageBroadcasts {
1236        // for each user id, a map of <package name -> components within that package>
1237        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1238
1239        public PendingPackageBroadcasts() {
1240            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1241        }
1242
1243        public ArrayList<String> get(int userId, String packageName) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            return packages.get(packageName);
1246        }
1247
1248        public void put(int userId, String packageName, ArrayList<String> components) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            packages.put(packageName, components);
1251        }
1252
1253        public void remove(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1255            if (packages != null) {
1256                packages.remove(packageName);
1257            }
1258        }
1259
1260        public void remove(int userId) {
1261            mUidMap.remove(userId);
1262        }
1263
1264        public int userIdCount() {
1265            return mUidMap.size();
1266        }
1267
1268        public int userIdAt(int n) {
1269            return mUidMap.keyAt(n);
1270        }
1271
1272        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1273            return mUidMap.get(userId);
1274        }
1275
1276        public int size() {
1277            // total number of pending broadcast entries across all userIds
1278            int num = 0;
1279            for (int i = 0; i< mUidMap.size(); i++) {
1280                num += mUidMap.valueAt(i).size();
1281            }
1282            return num;
1283        }
1284
1285        public void clear() {
1286            mUidMap.clear();
1287        }
1288
1289        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1290            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1291            if (map == null) {
1292                map = new ArrayMap<String, ArrayList<String>>();
1293                mUidMap.put(userId, map);
1294            }
1295            return map;
1296        }
1297    }
1298    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1299
1300    // Service Connection to remote media container service to copy
1301    // package uri's from external media onto secure containers
1302    // or internal storage.
1303    private IMediaContainerService mContainerService = null;
1304
1305    static final int SEND_PENDING_BROADCAST = 1;
1306    static final int MCS_BOUND = 3;
1307    static final int END_COPY = 4;
1308    static final int INIT_COPY = 5;
1309    static final int MCS_UNBIND = 6;
1310    static final int START_CLEANING_PACKAGE = 7;
1311    static final int FIND_INSTALL_LOC = 8;
1312    static final int POST_INSTALL = 9;
1313    static final int MCS_RECONNECT = 10;
1314    static final int MCS_GIVE_UP = 11;
1315    static final int WRITE_SETTINGS = 13;
1316    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1317    static final int PACKAGE_VERIFIED = 15;
1318    static final int CHECK_PENDING_VERIFICATION = 16;
1319    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1320    static final int INTENT_FILTER_VERIFIED = 18;
1321    static final int WRITE_PACKAGE_LIST = 19;
1322    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1323
1324    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1325
1326    // Delay time in millisecs
1327    static final int BROADCAST_DELAY = 10 * 1000;
1328
1329    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1330            2 * 60 * 60 * 1000L; /* two hours */
1331
1332    static UserManagerService sUserManager;
1333
1334    // Stores a list of users whose package restrictions file needs to be updated
1335    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1336
1337    final private DefaultContainerConnection mDefContainerConn =
1338            new DefaultContainerConnection();
1339    class DefaultContainerConnection implements ServiceConnection {
1340        public void onServiceConnected(ComponentName name, IBinder service) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1342            final IMediaContainerService imcs = IMediaContainerService.Stub
1343                    .asInterface(Binder.allowBlocking(service));
1344            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1345        }
1346
1347        public void onServiceDisconnected(ComponentName name) {
1348            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1349        }
1350    }
1351
1352    // Recordkeeping of restore-after-install operations that are currently in flight
1353    // between the Package Manager and the Backup Manager
1354    static class PostInstallData {
1355        public InstallArgs args;
1356        public PackageInstalledInfo res;
1357
1358        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1359            args = _a;
1360            res = _r;
1361        }
1362    }
1363
1364    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1365    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1366
1367    // XML tags for backup/restore of various bits of state
1368    private static final String TAG_PREFERRED_BACKUP = "pa";
1369    private static final String TAG_DEFAULT_APPS = "da";
1370    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1371
1372    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1373    private static final String TAG_ALL_GRANTS = "rt-grants";
1374    private static final String TAG_GRANT = "grant";
1375    private static final String ATTR_PACKAGE_NAME = "pkg";
1376
1377    private static final String TAG_PERMISSION = "perm";
1378    private static final String ATTR_PERMISSION_NAME = "name";
1379    private static final String ATTR_IS_GRANTED = "g";
1380    private static final String ATTR_USER_SET = "set";
1381    private static final String ATTR_USER_FIXED = "fixed";
1382    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1383
1384    // System/policy permission grants are not backed up
1385    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1386            FLAG_PERMISSION_POLICY_FIXED
1387            | FLAG_PERMISSION_SYSTEM_FIXED
1388            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1389
1390    // And we back up these user-adjusted states
1391    private static final int USER_RUNTIME_GRANT_MASK =
1392            FLAG_PERMISSION_USER_SET
1393            | FLAG_PERMISSION_USER_FIXED
1394            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1395
1396    final @Nullable String mRequiredVerifierPackage;
1397    final @NonNull String mRequiredInstallerPackage;
1398    final @NonNull String mRequiredUninstallerPackage;
1399    final @Nullable String mSetupWizardPackage;
1400    final @Nullable String mStorageManagerPackage;
1401    final @NonNull String mServicesSystemSharedLibraryPackageName;
1402    final @NonNull String mSharedSystemSharedLibraryPackageName;
1403
1404    final boolean mPermissionReviewRequired;
1405
1406    private final PackageUsage mPackageUsage = new PackageUsage();
1407    private final CompilerStats mCompilerStats = new CompilerStats();
1408
1409    class PackageHandler extends Handler {
1410        private boolean mBound = false;
1411        final ArrayList<HandlerParams> mPendingInstalls =
1412            new ArrayList<HandlerParams>();
1413
1414        private boolean connectToService() {
1415            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1416                    " DefaultContainerService");
1417            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1418            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1420                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1421                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422                mBound = true;
1423                return true;
1424            }
1425            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426            return false;
1427        }
1428
1429        private void disconnectService() {
1430            mContainerService = null;
1431            mBound = false;
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1433            mContext.unbindService(mDefContainerConn);
1434            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1435        }
1436
1437        PackageHandler(Looper looper) {
1438            super(looper);
1439        }
1440
1441        public void handleMessage(Message msg) {
1442            try {
1443                doHandleMessage(msg);
1444            } finally {
1445                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446            }
1447        }
1448
1449        void doHandleMessage(Message msg) {
1450            switch (msg.what) {
1451                case INIT_COPY: {
1452                    HandlerParams params = (HandlerParams) msg.obj;
1453                    int idx = mPendingInstalls.size();
1454                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1455                    // If a bind was already initiated we dont really
1456                    // need to do anything. The pending install
1457                    // will be processed later on.
1458                    if (!mBound) {
1459                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1460                                System.identityHashCode(mHandler));
1461                        // If this is the only one pending we might
1462                        // have to bind to the service again.
1463                        if (!connectToService()) {
1464                            Slog.e(TAG, "Failed to bind to media container service");
1465                            params.serviceError();
1466                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1467                                    System.identityHashCode(mHandler));
1468                            if (params.traceMethod != null) {
1469                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1470                                        params.traceCookie);
1471                            }
1472                            return;
1473                        } else {
1474                            // Once we bind to the service, the first
1475                            // pending request will be processed.
1476                            mPendingInstalls.add(idx, params);
1477                        }
1478                    } else {
1479                        mPendingInstalls.add(idx, params);
1480                        // Already bound to the service. Just make
1481                        // sure we trigger off processing the first request.
1482                        if (idx == 0) {
1483                            mHandler.sendEmptyMessage(MCS_BOUND);
1484                        }
1485                    }
1486                    break;
1487                }
1488                case MCS_BOUND: {
1489                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1490                    if (msg.obj != null) {
1491                        mContainerService = (IMediaContainerService) msg.obj;
1492                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1493                                System.identityHashCode(mHandler));
1494                    }
1495                    if (mContainerService == null) {
1496                        if (!mBound) {
1497                            // Something seriously wrong since we are not bound and we are not
1498                            // waiting for connection. Bail out.
1499                            Slog.e(TAG, "Cannot bind to media container service");
1500                            for (HandlerParams params : mPendingInstalls) {
1501                                // Indicate service bind error
1502                                params.serviceError();
1503                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1504                                        System.identityHashCode(params));
1505                                if (params.traceMethod != null) {
1506                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1507                                            params.traceMethod, params.traceCookie);
1508                                }
1509                                return;
1510                            }
1511                            mPendingInstalls.clear();
1512                        } else {
1513                            Slog.w(TAG, "Waiting to connect to media container service");
1514                        }
1515                    } else if (mPendingInstalls.size() > 0) {
1516                        HandlerParams params = mPendingInstalls.get(0);
1517                        if (params != null) {
1518                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1519                                    System.identityHashCode(params));
1520                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1521                            if (params.startCopy()) {
1522                                // We are done...  look for more work or to
1523                                // go idle.
1524                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1525                                        "Checking for more work or unbind...");
1526                                // Delete pending install
1527                                if (mPendingInstalls.size() > 0) {
1528                                    mPendingInstalls.remove(0);
1529                                }
1530                                if (mPendingInstalls.size() == 0) {
1531                                    if (mBound) {
1532                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                                "Posting delayed MCS_UNBIND");
1534                                        removeMessages(MCS_UNBIND);
1535                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1536                                        // Unbind after a little delay, to avoid
1537                                        // continual thrashing.
1538                                        sendMessageDelayed(ubmsg, 10000);
1539                                    }
1540                                } else {
1541                                    // There are more pending requests in queue.
1542                                    // Just post MCS_BOUND message to trigger processing
1543                                    // of next pending install.
1544                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1545                                            "Posting MCS_BOUND for next work");
1546                                    mHandler.sendEmptyMessage(MCS_BOUND);
1547                                }
1548                            }
1549                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1550                        }
1551                    } else {
1552                        // Should never happen ideally.
1553                        Slog.w(TAG, "Empty queue");
1554                    }
1555                    break;
1556                }
1557                case MCS_RECONNECT: {
1558                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1559                    if (mPendingInstalls.size() > 0) {
1560                        if (mBound) {
1561                            disconnectService();
1562                        }
1563                        if (!connectToService()) {
1564                            Slog.e(TAG, "Failed to bind to media container service");
1565                            for (HandlerParams params : mPendingInstalls) {
1566                                // Indicate service bind error
1567                                params.serviceError();
1568                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1569                                        System.identityHashCode(params));
1570                            }
1571                            mPendingInstalls.clear();
1572                        }
1573                    }
1574                    break;
1575                }
1576                case MCS_UNBIND: {
1577                    // If there is no actual work left, then time to unbind.
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1579
1580                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1581                        if (mBound) {
1582                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1583
1584                            disconnectService();
1585                        }
1586                    } else if (mPendingInstalls.size() > 0) {
1587                        // There are more pending requests in queue.
1588                        // Just post MCS_BOUND message to trigger processing
1589                        // of next pending install.
1590                        mHandler.sendEmptyMessage(MCS_BOUND);
1591                    }
1592
1593                    break;
1594                }
1595                case MCS_GIVE_UP: {
1596                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1597                    HandlerParams params = mPendingInstalls.remove(0);
1598                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1599                            System.identityHashCode(params));
1600                    break;
1601                }
1602                case SEND_PENDING_BROADCAST: {
1603                    String packages[];
1604                    ArrayList<String> components[];
1605                    int size = 0;
1606                    int uids[];
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        if (mPendingBroadcasts == null) {
1610                            return;
1611                        }
1612                        size = mPendingBroadcasts.size();
1613                        if (size <= 0) {
1614                            // Nothing to be done. Just return
1615                            return;
1616                        }
1617                        packages = new String[size];
1618                        components = new ArrayList[size];
1619                        uids = new int[size];
1620                        int i = 0;  // filling out the above arrays
1621
1622                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1623                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1624                            Iterator<Map.Entry<String, ArrayList<String>>> it
1625                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1626                                            .entrySet().iterator();
1627                            while (it.hasNext() && i < size) {
1628                                Map.Entry<String, ArrayList<String>> ent = it.next();
1629                                packages[i] = ent.getKey();
1630                                components[i] = ent.getValue();
1631                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1632                                uids[i] = (ps != null)
1633                                        ? UserHandle.getUid(packageUserId, ps.appId)
1634                                        : -1;
1635                                i++;
1636                            }
1637                        }
1638                        size = i;
1639                        mPendingBroadcasts.clear();
1640                    }
1641                    // Send broadcasts
1642                    for (int i = 0; i < size; i++) {
1643                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1644                    }
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1646                    break;
1647                }
1648                case START_CLEANING_PACKAGE: {
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1650                    final String packageName = (String)msg.obj;
1651                    final int userId = msg.arg1;
1652                    final boolean andCode = msg.arg2 != 0;
1653                    synchronized (mPackages) {
1654                        if (userId == UserHandle.USER_ALL) {
1655                            int[] users = sUserManager.getUserIds();
1656                            for (int user : users) {
1657                                mSettings.addPackageToCleanLPw(
1658                                        new PackageCleanItem(user, packageName, andCode));
1659                            }
1660                        } else {
1661                            mSettings.addPackageToCleanLPw(
1662                                    new PackageCleanItem(userId, packageName, andCode));
1663                        }
1664                    }
1665                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1666                    startCleaningPackages();
1667                } break;
1668                case POST_INSTALL: {
1669                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1670
1671                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1672                    final boolean didRestore = (msg.arg2 != 0);
1673                    mRunningInstalls.delete(msg.arg1);
1674
1675                    if (data != null) {
1676                        InstallArgs args = data.args;
1677                        PackageInstalledInfo parentRes = data.res;
1678
1679                        final boolean grantPermissions = (args.installFlags
1680                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1681                        final boolean killApp = (args.installFlags
1682                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1683                        final boolean virtualPreload = ((args.installFlags
1684                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1685                        final String[] grantedPermissions = args.installGrantPermissions;
1686
1687                        // Handle the parent package
1688                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1689                                virtualPreload, grantedPermissions, didRestore,
1690                                args.installerPackageName, args.observer);
1691
1692                        // Handle the child packages
1693                        final int childCount = (parentRes.addedChildPackages != null)
1694                                ? parentRes.addedChildPackages.size() : 0;
1695                        for (int i = 0; i < childCount; i++) {
1696                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1697                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1698                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1699                                    args.installerPackageName, args.observer);
1700                        }
1701
1702                        // Log tracing if needed
1703                        if (args.traceMethod != null) {
1704                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1705                                    args.traceCookie);
1706                        }
1707                    } else {
1708                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1709                    }
1710
1711                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1712                } break;
1713                case WRITE_SETTINGS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_SETTINGS);
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        mSettings.writeLPr();
1719                        mDirtyUsers.clear();
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case WRITE_PACKAGE_RESTRICTIONS: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1727                        for (int userId : mDirtyUsers) {
1728                            mSettings.writePackageRestrictionsLPr(userId);
1729                        }
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_LIST: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_LIST);
1738                        mSettings.writePackageListLPr(msg.arg1);
1739                    }
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1741                } break;
1742                case CHECK_PENDING_VERIFICATION: {
1743                    final int verificationId = msg.arg1;
1744                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1745
1746                    if ((state != null) && !state.timeoutExtended()) {
1747                        final InstallArgs args = state.getInstallArgs();
1748                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1749
1750                        Slog.i(TAG, "Verification timed out for " + originUri);
1751                        mPendingVerification.remove(verificationId);
1752
1753                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1754
1755                        final UserHandle user = args.getUser();
1756                        if (getDefaultVerificationResponse(user)
1757                                == PackageManager.VERIFICATION_ALLOW) {
1758                            Slog.i(TAG, "Continuing with installation of " + originUri);
1759                            state.setVerifierResponse(Binder.getCallingUid(),
1760                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_ALLOW, user);
1763                            try {
1764                                ret = args.copyApk(mContainerService, true);
1765                            } catch (RemoteException e) {
1766                                Slog.e(TAG, "Could not contact the ContainerService");
1767                            }
1768                        } else {
1769                            broadcastPackageVerified(verificationId, originUri,
1770                                    PackageManager.VERIFICATION_REJECT, user);
1771                        }
1772
1773                        Trace.asyncTraceEnd(
1774                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1775
1776                        processPendingInstall(args, ret);
1777                        mHandler.sendEmptyMessage(MCS_UNBIND);
1778                    }
1779                    break;
1780                }
1781                case PACKAGE_VERIFIED: {
1782                    final int verificationId = msg.arg1;
1783
1784                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1785                    if (state == null) {
1786                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1787                        break;
1788                    }
1789
1790                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1791
1792                    state.setVerifierResponse(response.callerUid, response.code);
1793
1794                    if (state.isVerificationComplete()) {
1795                        mPendingVerification.remove(verificationId);
1796
1797                        final InstallArgs args = state.getInstallArgs();
1798                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1799
1800                        int ret;
1801                        if (state.isInstallAllowed()) {
1802                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1803                            broadcastPackageVerified(verificationId, originUri,
1804                                    response.code, state.getInstallArgs().getUser());
1805                            try {
1806                                ret = args.copyApk(mContainerService, true);
1807                            } catch (RemoteException e) {
1808                                Slog.e(TAG, "Could not contact the ContainerService");
1809                            }
1810                        } else {
1811                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1812                        }
1813
1814                        Trace.asyncTraceEnd(
1815                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1816
1817                        processPendingInstall(args, ret);
1818                        mHandler.sendEmptyMessage(MCS_UNBIND);
1819                    }
1820
1821                    break;
1822                }
1823                case START_INTENT_FILTER_VERIFICATIONS: {
1824                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1825                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1826                            params.replacing, params.pkg);
1827                    break;
1828                }
1829                case INTENT_FILTER_VERIFIED: {
1830                    final int verificationId = msg.arg1;
1831
1832                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1833                            verificationId);
1834                    if (state == null) {
1835                        Slog.w(TAG, "Invalid IntentFilter verification token "
1836                                + verificationId + " received");
1837                        break;
1838                    }
1839
1840                    final int userId = state.getUserId();
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "Processing IntentFilter verification with token:"
1844                            + verificationId + " and userId:" + userId);
1845
1846                    final IntentFilterVerificationResponse response =
1847                            (IntentFilterVerificationResponse) msg.obj;
1848
1849                    state.setVerifierResponse(response.callerUid, response.code);
1850
1851                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1852                            "IntentFilter verification with token:" + verificationId
1853                            + " and userId:" + userId
1854                            + " is settings verifier response with response code:"
1855                            + response.code);
1856
1857                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1858                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1859                                + response.getFailedDomainsString());
1860                    }
1861
1862                    if (state.isVerificationComplete()) {
1863                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1864                    } else {
1865                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                                "IntentFilter verification with token:" + verificationId
1867                                + " was not said to be complete");
1868                    }
1869
1870                    break;
1871                }
1872                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1873                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1874                            mInstantAppResolverConnection,
1875                            (InstantAppRequest) msg.obj,
1876                            mInstantAppInstallerActivity,
1877                            mHandler);
1878                }
1879            }
1880        }
1881    }
1882
1883    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1884        @Override
1885        public void onGidsChanged(int appId, int userId) {
1886            mHandler.post(new Runnable() {
1887                @Override
1888                public void run() {
1889                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1890                }
1891            });
1892        }
1893        @Override
1894        public void onPermissionGranted(int uid, int userId) {
1895            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1896
1897            // Not critical; if this is lost, the application has to request again.
1898            synchronized (mPackages) {
1899                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1900            }
1901        }
1902        @Override
1903        public void onInstallPermissionGranted() {
1904            synchronized (mPackages) {
1905                scheduleWriteSettingsLocked();
1906            }
1907        }
1908        @Override
1909        public void onPermissionRevoked(int uid, int userId) {
1910            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1911
1912            synchronized (mPackages) {
1913                // Critical; after this call the application should never have the permission
1914                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1915            }
1916
1917            final int appId = UserHandle.getAppId(uid);
1918            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1919        }
1920        @Override
1921        public void onInstallPermissionRevoked() {
1922            synchronized (mPackages) {
1923                scheduleWriteSettingsLocked();
1924            }
1925        }
1926        @Override
1927        public void onPermissionUpdated(int userId) {
1928            synchronized (mPackages) {
1929                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1930            }
1931        }
1932        @Override
1933        public void onInstallPermissionUpdated() {
1934            synchronized (mPackages) {
1935                scheduleWriteSettingsLocked();
1936            }
1937        }
1938        @Override
1939        public void onPermissionRemoved() {
1940            synchronized (mPackages) {
1941                mSettings.writeLPr();
1942            }
1943        }
1944    };
1945
1946    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1947            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1948            boolean launchedForRestore, String installerPackage,
1949            IPackageInstallObserver2 installObserver) {
1950        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1951            // Send the removed broadcasts
1952            if (res.removedInfo != null) {
1953                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1954            }
1955
1956            // Now that we successfully installed the package, grant runtime
1957            // permissions if requested before broadcasting the install. Also
1958            // for legacy apps in permission review mode we clear the permission
1959            // review flag which is used to emulate runtime permissions for
1960            // legacy apps.
1961            if (grantPermissions) {
1962                final int callingUid = Binder.getCallingUid();
1963                mPermissionManager.grantRequestedRuntimePermissions(
1964                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1965                        mPermissionCallback);
1966            }
1967
1968            final boolean update = res.removedInfo != null
1969                    && res.removedInfo.removedPackage != null;
1970            final String installerPackageName =
1971                    res.installerPackageName != null
1972                            ? res.installerPackageName
1973                            : res.removedInfo != null
1974                                    ? res.removedInfo.installerPackageName
1975                                    : null;
1976
1977            // If this is the first time we have child packages for a disabled privileged
1978            // app that had no children, we grant requested runtime permissions to the new
1979            // children if the parent on the system image had them already granted.
1980            if (res.pkg.parentPackage != null) {
1981                final int callingUid = Binder.getCallingUid();
1982                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1983                        res.pkg, callingUid, mPermissionCallback);
1984            }
1985
1986            synchronized (mPackages) {
1987                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1988            }
1989
1990            final String packageName = res.pkg.applicationInfo.packageName;
1991
1992            // Determine the set of users who are adding this package for
1993            // the first time vs. those who are seeing an update.
1994            int[] firstUsers = EMPTY_INT_ARRAY;
1995            int[] updateUsers = EMPTY_INT_ARRAY;
1996            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1997            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1998            for (int newUser : res.newUsers) {
1999                if (ps.getInstantApp(newUser)) {
2000                    continue;
2001                }
2002                if (allNewUsers) {
2003                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2004                    continue;
2005                }
2006                boolean isNew = true;
2007                for (int origUser : res.origUsers) {
2008                    if (origUser == newUser) {
2009                        isNew = false;
2010                        break;
2011                    }
2012                }
2013                if (isNew) {
2014                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2015                } else {
2016                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2017                }
2018            }
2019
2020            // Send installed broadcasts if the package is not a static shared lib.
2021            if (res.pkg.staticSharedLibName == null) {
2022                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2023
2024                // Send added for users that see the package for the first time
2025                // sendPackageAddedForNewUsers also deals with system apps
2026                int appId = UserHandle.getAppId(res.uid);
2027                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2028                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2029                        virtualPreload /*startReceiver*/, appId, firstUsers);
2030
2031                // Send added for users that don't see the package for the first time
2032                Bundle extras = new Bundle(1);
2033                extras.putInt(Intent.EXTRA_UID, res.uid);
2034                if (update) {
2035                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2036                }
2037                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2038                        extras, 0 /*flags*/,
2039                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2040                if (installerPackageName != null) {
2041                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                            extras, 0 /*flags*/,
2043                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2044                }
2045
2046                // Send replaced for users that don't see the package for the first time
2047                if (update) {
2048                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2049                            packageName, extras, 0 /*flags*/,
2050                            null /*targetPackage*/, null /*finishedReceiver*/,
2051                            updateUsers);
2052                    if (installerPackageName != null) {
2053                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2054                                extras, 0 /*flags*/,
2055                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2056                    }
2057                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2058                            null /*package*/, null /*extras*/, 0 /*flags*/,
2059                            packageName /*targetPackage*/,
2060                            null /*finishedReceiver*/, updateUsers);
2061                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2062                    // First-install and we did a restore, so we're responsible for the
2063                    // first-launch broadcast.
2064                    if (DEBUG_BACKUP) {
2065                        Slog.i(TAG, "Post-restore of " + packageName
2066                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2067                    }
2068                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2069                }
2070
2071                // Send broadcast package appeared if forward locked/external for all users
2072                // treat asec-hosted packages like removable media on upgrade
2073                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2074                    if (DEBUG_INSTALL) {
2075                        Slog.i(TAG, "upgrading pkg " + res.pkg
2076                                + " is ASEC-hosted -> AVAILABLE");
2077                    }
2078                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2079                    ArrayList<String> pkgList = new ArrayList<>(1);
2080                    pkgList.add(packageName);
2081                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2082                }
2083            }
2084
2085            // Work that needs to happen on first install within each user
2086            if (firstUsers != null && firstUsers.length > 0) {
2087                synchronized (mPackages) {
2088                    for (int userId : firstUsers) {
2089                        // If this app is a browser and it's newly-installed for some
2090                        // users, clear any default-browser state in those users. The
2091                        // app's nature doesn't depend on the user, so we can just check
2092                        // its browser nature in any user and generalize.
2093                        if (packageIsBrowser(packageName, userId)) {
2094                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2095                        }
2096
2097                        // We may also need to apply pending (restored) runtime
2098                        // permission grants within these users.
2099                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2100                    }
2101                }
2102            }
2103
2104            // Log current value of "unknown sources" setting
2105            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2106                    getUnknownSourcesSettings());
2107
2108            // Remove the replaced package's older resources safely now
2109            // We delete after a gc for applications  on sdcard.
2110            if (res.removedInfo != null && res.removedInfo.args != null) {
2111                Runtime.getRuntime().gc();
2112                synchronized (mInstallLock) {
2113                    res.removedInfo.args.doPostDeleteLI(true);
2114                }
2115            } else {
2116                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2117                // and not block here.
2118                VMRuntime.getRuntime().requestConcurrentGC();
2119            }
2120
2121            // Notify DexManager that the package was installed for new users.
2122            // The updated users should already be indexed and the package code paths
2123            // should not change.
2124            // Don't notify the manager for ephemeral apps as they are not expected to
2125            // survive long enough to benefit of background optimizations.
2126            for (int userId : firstUsers) {
2127                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2128                // There's a race currently where some install events may interleave with an uninstall.
2129                // This can lead to package info being null (b/36642664).
2130                if (info != null) {
2131                    mDexManager.notifyPackageInstalled(info, userId);
2132                }
2133            }
2134        }
2135
2136        // If someone is watching installs - notify them
2137        if (installObserver != null) {
2138            try {
2139                Bundle extras = extrasForInstallResult(res);
2140                installObserver.onPackageInstalled(res.name, res.returnCode,
2141                        res.returnMsg, extras);
2142            } catch (RemoteException e) {
2143                Slog.i(TAG, "Observer no longer exists.");
2144            }
2145        }
2146    }
2147
2148    private StorageEventListener mStorageListener = new StorageEventListener() {
2149        @Override
2150        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2151            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2152                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2153                    final String volumeUuid = vol.getFsUuid();
2154
2155                    // Clean up any users or apps that were removed or recreated
2156                    // while this volume was missing
2157                    sUserManager.reconcileUsers(volumeUuid);
2158                    reconcileApps(volumeUuid);
2159
2160                    // Clean up any install sessions that expired or were
2161                    // cancelled while this volume was missing
2162                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2163
2164                    loadPrivatePackages(vol);
2165
2166                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2167                    unloadPrivatePackages(vol);
2168                }
2169            }
2170        }
2171
2172        @Override
2173        public void onVolumeForgotten(String fsUuid) {
2174            if (TextUtils.isEmpty(fsUuid)) {
2175                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2176                return;
2177            }
2178
2179            // Remove any apps installed on the forgotten volume
2180            synchronized (mPackages) {
2181                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2182                for (PackageSetting ps : packages) {
2183                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2184                    deletePackageVersioned(new VersionedPackage(ps.name,
2185                            PackageManager.VERSION_CODE_HIGHEST),
2186                            new LegacyPackageDeleteObserver(null).getBinder(),
2187                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2188                    // Try very hard to release any references to this package
2189                    // so we don't risk the system server being killed due to
2190                    // open FDs
2191                    AttributeCache.instance().removePackage(ps.name);
2192                }
2193
2194                mSettings.onVolumeForgotten(fsUuid);
2195                mSettings.writeLPr();
2196            }
2197        }
2198    };
2199
2200    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2201        Bundle extras = null;
2202        switch (res.returnCode) {
2203            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2204                extras = new Bundle();
2205                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2206                        res.origPermission);
2207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2208                        res.origPackage);
2209                break;
2210            }
2211            case PackageManager.INSTALL_SUCCEEDED: {
2212                extras = new Bundle();
2213                extras.putBoolean(Intent.EXTRA_REPLACING,
2214                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2215                break;
2216            }
2217        }
2218        return extras;
2219    }
2220
2221    void scheduleWriteSettingsLocked() {
2222        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2223            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2224        }
2225    }
2226
2227    void scheduleWritePackageListLocked(int userId) {
2228        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2229            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2230            msg.arg1 = userId;
2231            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2232        }
2233    }
2234
2235    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2236        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2237        scheduleWritePackageRestrictionsLocked(userId);
2238    }
2239
2240    void scheduleWritePackageRestrictionsLocked(int userId) {
2241        final int[] userIds = (userId == UserHandle.USER_ALL)
2242                ? sUserManager.getUserIds() : new int[]{userId};
2243        for (int nextUserId : userIds) {
2244            if (!sUserManager.exists(nextUserId)) return;
2245            mDirtyUsers.add(nextUserId);
2246            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2247                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2248            }
2249        }
2250    }
2251
2252    public static PackageManagerService main(Context context, Installer installer,
2253            boolean factoryTest, boolean onlyCore) {
2254        // Self-check for initial settings.
2255        PackageManagerServiceCompilerMapping.checkProperties();
2256
2257        PackageManagerService m = new PackageManagerService(context, installer,
2258                factoryTest, onlyCore);
2259        m.enableSystemUserPackages();
2260        ServiceManager.addService("package", m);
2261        final PackageManagerNative pmn = m.new PackageManagerNative();
2262        ServiceManager.addService("package_native", pmn);
2263        return m;
2264    }
2265
2266    private void enableSystemUserPackages() {
2267        if (!UserManager.isSplitSystemUser()) {
2268            return;
2269        }
2270        // For system user, enable apps based on the following conditions:
2271        // - app is whitelisted or belong to one of these groups:
2272        //   -- system app which has no launcher icons
2273        //   -- system app which has INTERACT_ACROSS_USERS permission
2274        //   -- system IME app
2275        // - app is not in the blacklist
2276        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2277        Set<String> enableApps = new ArraySet<>();
2278        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2279                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2280                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2281        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2282        enableApps.addAll(wlApps);
2283        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2284                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2285        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2286        enableApps.removeAll(blApps);
2287        Log.i(TAG, "Applications installed for system user: " + enableApps);
2288        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2289                UserHandle.SYSTEM);
2290        final int allAppsSize = allAps.size();
2291        synchronized (mPackages) {
2292            for (int i = 0; i < allAppsSize; i++) {
2293                String pName = allAps.get(i);
2294                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2295                // Should not happen, but we shouldn't be failing if it does
2296                if (pkgSetting == null) {
2297                    continue;
2298                }
2299                boolean install = enableApps.contains(pName);
2300                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2301                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2302                            + " for system user");
2303                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2304                }
2305            }
2306            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2307        }
2308    }
2309
2310    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2311        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2312                Context.DISPLAY_SERVICE);
2313        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2314    }
2315
2316    /**
2317     * Requests that files preopted on a secondary system partition be copied to the data partition
2318     * if possible.  Note that the actual copying of the files is accomplished by init for security
2319     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2320     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2321     */
2322    private static void requestCopyPreoptedFiles() {
2323        final int WAIT_TIME_MS = 100;
2324        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2325        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2326            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2327            // We will wait for up to 100 seconds.
2328            final long timeStart = SystemClock.uptimeMillis();
2329            final long timeEnd = timeStart + 100 * 1000;
2330            long timeNow = timeStart;
2331            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2332                try {
2333                    Thread.sleep(WAIT_TIME_MS);
2334                } catch (InterruptedException e) {
2335                    // Do nothing
2336                }
2337                timeNow = SystemClock.uptimeMillis();
2338                if (timeNow > timeEnd) {
2339                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2340                    Slog.wtf(TAG, "cppreopt did not finish!");
2341                    break;
2342                }
2343            }
2344
2345            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2346        }
2347    }
2348
2349    public PackageManagerService(Context context, Installer installer,
2350            boolean factoryTest, boolean onlyCore) {
2351        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2352        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2353        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2354                SystemClock.uptimeMillis());
2355
2356        if (mSdkVersion <= 0) {
2357            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2358        }
2359
2360        mContext = context;
2361
2362        mPermissionReviewRequired = context.getResources().getBoolean(
2363                R.bool.config_permissionReviewRequired);
2364
2365        mFactoryTest = factoryTest;
2366        mOnlyCore = onlyCore;
2367        mMetrics = new DisplayMetrics();
2368        mInstaller = installer;
2369
2370        // Create sub-components that provide services / data. Order here is important.
2371        synchronized (mInstallLock) {
2372        synchronized (mPackages) {
2373            // Expose private service for system components to use.
2374            LocalServices.addService(
2375                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2376            sUserManager = new UserManagerService(context, this,
2377                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2378            mPermissionManager = PermissionManagerService.create(context,
2379                    new DefaultPermissionGrantedCallback() {
2380                        @Override
2381                        public void onDefaultRuntimePermissionsGranted(int userId) {
2382                            synchronized(mPackages) {
2383                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2384                            }
2385                        }
2386                    }, mPackages /*externalLock*/);
2387            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2388            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2389        }
2390        }
2391        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2392                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2393        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2394                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2395        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403
2404        String separateProcesses = SystemProperties.get("debug.separate_processes");
2405        if (separateProcesses != null && separateProcesses.length() > 0) {
2406            if ("*".equals(separateProcesses)) {
2407                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2408                mSeparateProcesses = null;
2409                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2410            } else {
2411                mDefParseFlags = 0;
2412                mSeparateProcesses = separateProcesses.split(",");
2413                Slog.w(TAG, "Running with debug.separate_processes: "
2414                        + separateProcesses);
2415            }
2416        } else {
2417            mDefParseFlags = 0;
2418            mSeparateProcesses = null;
2419        }
2420
2421        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2422                "*dexopt*");
2423        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2424        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2425
2426        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2427                FgThread.get().getLooper());
2428
2429        getDefaultDisplayMetrics(context, mMetrics);
2430
2431        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2432        SystemConfig systemConfig = SystemConfig.getInstance();
2433        mGlobalGids = systemConfig.getGlobalGids();
2434        mSystemPermissions = systemConfig.getSystemPermissions();
2435        mAvailableFeatures = systemConfig.getAvailableFeatures();
2436        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2437
2438        mProtectedPackages = new ProtectedPackages(mContext);
2439
2440        synchronized (mInstallLock) {
2441        // writer
2442        synchronized (mPackages) {
2443            mHandlerThread = new ServiceThread(TAG,
2444                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2445            mHandlerThread.start();
2446            mHandler = new PackageHandler(mHandlerThread.getLooper());
2447            mProcessLoggingHandler = new ProcessLoggingHandler();
2448            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2449            mInstantAppRegistry = new InstantAppRegistry(this);
2450
2451            File dataDir = Environment.getDataDirectory();
2452            mAppInstallDir = new File(dataDir, "app");
2453            mAppLib32InstallDir = new File(dataDir, "app-lib");
2454            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2455
2456            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2457            final int builtInLibCount = libConfig.size();
2458            for (int i = 0; i < builtInLibCount; i++) {
2459                String name = libConfig.keyAt(i);
2460                String path = libConfig.valueAt(i);
2461                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2462                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2463            }
2464
2465            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2466
2467            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2468            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2470
2471            // Clean up orphaned packages for which the code path doesn't exist
2472            // and they are an update to a system app - caused by bug/32321269
2473            final int packageSettingCount = mSettings.mPackages.size();
2474            for (int i = packageSettingCount - 1; i >= 0; i--) {
2475                PackageSetting ps = mSettings.mPackages.valueAt(i);
2476                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2477                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2478                    mSettings.mPackages.removeAt(i);
2479                    mSettings.enableSystemPackageLPw(ps.name);
2480                }
2481            }
2482
2483            if (mFirstBoot) {
2484                requestCopyPreoptedFiles();
2485            }
2486
2487            String customResolverActivity = Resources.getSystem().getString(
2488                    R.string.config_customResolverActivity);
2489            if (TextUtils.isEmpty(customResolverActivity)) {
2490                customResolverActivity = null;
2491            } else {
2492                mCustomResolverComponentName = ComponentName.unflattenFromString(
2493                        customResolverActivity);
2494            }
2495
2496            long startTime = SystemClock.uptimeMillis();
2497
2498            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2499                    startTime);
2500
2501            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2502            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2503
2504            if (bootClassPath == null) {
2505                Slog.w(TAG, "No BOOTCLASSPATH found!");
2506            }
2507
2508            if (systemServerClassPath == null) {
2509                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2510            }
2511
2512            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2513
2514            final VersionInfo ver = mSettings.getInternalVersion();
2515            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2516            if (mIsUpgrade) {
2517                logCriticalInfo(Log.INFO,
2518                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2519            }
2520
2521            // when upgrading from pre-M, promote system app permissions from install to runtime
2522            mPromoteSystemApps =
2523                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2524
2525            // When upgrading from pre-N, we need to handle package extraction like first boot,
2526            // as there is no profiling data available.
2527            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2528
2529            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2530
2531            // save off the names of pre-existing system packages prior to scanning; we don't
2532            // want to automatically grant runtime permissions for new system apps
2533            if (mPromoteSystemApps) {
2534                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2535                while (pkgSettingIter.hasNext()) {
2536                    PackageSetting ps = pkgSettingIter.next();
2537                    if (isSystemApp(ps)) {
2538                        mExistingSystemPackages.add(ps.name);
2539                    }
2540                }
2541            }
2542
2543            mCacheDir = preparePackageParserCache(mIsUpgrade);
2544
2545            // Set flag to monitor and not change apk file paths when
2546            // scanning install directories.
2547            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2548
2549            if (mIsUpgrade || mFirstBoot) {
2550                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2551            }
2552
2553            // Collect vendor overlay packages. (Do this before scanning any apps.)
2554            // For security and version matching reason, only consider
2555            // overlay packages if they reside in the right directory.
2556            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2557                    | PackageParser.PARSE_IS_SYSTEM
2558                    | PackageParser.PARSE_IS_SYSTEM_DIR
2559                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2560
2561            mParallelPackageParserCallback.findStaticOverlayPackages();
2562
2563            // Find base frameworks (resource packages without code).
2564            scanDirTracedLI(frameworkDir, mDefParseFlags
2565                    | PackageParser.PARSE_IS_SYSTEM
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR
2567                    | PackageParser.PARSE_IS_PRIVILEGED,
2568                    scanFlags | SCAN_NO_DEX, 0);
2569
2570            // Collected privileged system packages.
2571            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2572            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM
2574                    | PackageParser.PARSE_IS_SYSTEM_DIR
2575                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2576
2577            // Collect ordinary system packages.
2578            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2579            scanDirTracedLI(systemAppDir, mDefParseFlags
2580                    | PackageParser.PARSE_IS_SYSTEM
2581                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2582
2583            // Collect all vendor packages.
2584            File vendorAppDir = new File("/vendor/app");
2585            try {
2586                vendorAppDir = vendorAppDir.getCanonicalFile();
2587            } catch (IOException e) {
2588                // failed to look up canonical path, continue with original one
2589            }
2590            scanDirTracedLI(vendorAppDir, mDefParseFlags
2591                    | PackageParser.PARSE_IS_SYSTEM
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2593
2594            // Collect all OEM packages.
2595            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2596            scanDirTracedLI(oemAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2600
2601            // Prune any system packages that no longer exist.
2602            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2603            // Stub packages must either be replaced with full versions in the /data
2604            // partition or be disabled.
2605            final List<String> stubSystemApps = new ArrayList<>();
2606            if (!mOnlyCore) {
2607                // do this first before mucking with mPackages for the "expecting better" case
2608                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2609                while (pkgIterator.hasNext()) {
2610                    final PackageParser.Package pkg = pkgIterator.next();
2611                    if (pkg.isStub) {
2612                        stubSystemApps.add(pkg.packageName);
2613                    }
2614                }
2615
2616                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2617                while (psit.hasNext()) {
2618                    PackageSetting ps = psit.next();
2619
2620                    /*
2621                     * If this is not a system app, it can't be a
2622                     * disable system app.
2623                     */
2624                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2625                        continue;
2626                    }
2627
2628                    /*
2629                     * If the package is scanned, it's not erased.
2630                     */
2631                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2632                    if (scannedPkg != null) {
2633                        /*
2634                         * If the system app is both scanned and in the
2635                         * disabled packages list, then it must have been
2636                         * added via OTA. Remove it from the currently
2637                         * scanned package so the previously user-installed
2638                         * application can be scanned.
2639                         */
2640                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2641                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2642                                    + ps.name + "; removing system app.  Last known codePath="
2643                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2644                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2645                                    + scannedPkg.mVersionCode);
2646                            removePackageLI(scannedPkg, true);
2647                            mExpectingBetter.put(ps.name, ps.codePath);
2648                        }
2649
2650                        continue;
2651                    }
2652
2653                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2654                        psit.remove();
2655                        logCriticalInfo(Log.WARN, "System package " + ps.name
2656                                + " no longer exists; it's data will be wiped");
2657                        // Actual deletion of code and data will be handled by later
2658                        // reconciliation step
2659                    } else {
2660                        // we still have a disabled system package, but, it still might have
2661                        // been removed. check the code path still exists and check there's
2662                        // still a package. the latter can happen if an OTA keeps the same
2663                        // code path, but, changes the package name.
2664                        final PackageSetting disabledPs =
2665                                mSettings.getDisabledSystemPkgLPr(ps.name);
2666                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2667                                || disabledPs.pkg == null) {
2668                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2669                        }
2670                    }
2671                }
2672            }
2673
2674            //look for any incomplete package installations
2675            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2676            for (int i = 0; i < deletePkgsList.size(); i++) {
2677                // Actual deletion of code and data will be handled by later
2678                // reconciliation step
2679                final String packageName = deletePkgsList.get(i).name;
2680                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2681                synchronized (mPackages) {
2682                    mSettings.removePackageLPw(packageName);
2683                }
2684            }
2685
2686            //delete tmp files
2687            deleteTempPackageFiles();
2688
2689            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2690
2691            // Remove any shared userIDs that have no associated packages
2692            mSettings.pruneSharedUsersLPw();
2693            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2694            final int systemPackagesCount = mPackages.size();
2695            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2696                    + " ms, packageCount: " + systemPackagesCount
2697                    + " , timePerPackage: "
2698                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2699                    + " , cached: " + cachedSystemApps);
2700            if (mIsUpgrade && systemPackagesCount > 0) {
2701                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2702                        ((int) systemScanTime) / systemPackagesCount);
2703            }
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                // Remove disable package settings for updated system apps that were
2714                // removed via an OTA. If the update is no longer present, remove the
2715                // app completely. Otherwise, revoke their system privileges.
2716                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2717                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2718                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2719
2720                    final String msg;
2721                    if (deletedPkg == null) {
2722                        // should have found an update, but, we didn't; remove everything
2723                        msg = "Updated system package " + deletedAppName
2724                                + " no longer exists; removing its data";
2725                        // Actual deletion of code and data will be handled by later
2726                        // reconciliation step
2727                    } else {
2728                        // found an update; revoke system privileges
2729                        msg = "Updated system package + " + deletedAppName
2730                                + " no longer exists; revoking system privileges";
2731
2732                        // Don't do anything if a stub is removed from the system image. If
2733                        // we were to remove the uncompressed version from the /data partition,
2734                        // this is where it'd be done.
2735
2736                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2739                    }
2740                    logCriticalInfo(Log.WARN, msg);
2741                }
2742
2743                /*
2744                 * Make sure all system apps that we expected to appear on
2745                 * the userdata partition actually showed up. If they never
2746                 * appeared, crawl back and revive the system version.
2747                 */
2748                for (int i = 0; i < mExpectingBetter.size(); i++) {
2749                    final String packageName = mExpectingBetter.keyAt(i);
2750                    if (!mPackages.containsKey(packageName)) {
2751                        final File scanFile = mExpectingBetter.valueAt(i);
2752
2753                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2754                                + " but never showed up; reverting to system");
2755
2756                        int reparseFlags = mDefParseFlags;
2757                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2758                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2760                                    | PackageParser.PARSE_IS_PRIVILEGED;
2761                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2764                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2765                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2766                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2767                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2770                                    | PackageParser.PARSE_IS_OEM;
2771                        } else {
2772                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2773                            continue;
2774                        }
2775
2776                        mSettings.enableSystemPackageLPw(packageName);
2777
2778                        try {
2779                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2780                        } catch (PackageManagerException e) {
2781                            Slog.e(TAG, "Failed to parse original system package: "
2782                                    + e.getMessage());
2783                        }
2784                    }
2785                }
2786
2787                // Uncompress and install any stubbed system applications.
2788                // This must be done last to ensure all stubs are replaced or disabled.
2789                decompressSystemApplications(stubSystemApps, scanFlags);
2790
2791                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2792                                - cachedSystemApps;
2793
2794                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2795                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2796                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2797                        + " ms, packageCount: " + dataPackagesCount
2798                        + " , timePerPackage: "
2799                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2800                        + " , cached: " + cachedNonSystemApps);
2801                if (mIsUpgrade && dataPackagesCount > 0) {
2802                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2803                            ((int) dataScanTime) / dataPackagesCount);
2804                }
2805            }
2806            mExpectingBetter.clear();
2807
2808            // Resolve the storage manager.
2809            mStorageManagerPackage = getStorageManagerPackageName();
2810
2811            // Resolve protected action filters. Only the setup wizard is allowed to
2812            // have a high priority filter for these actions.
2813            mSetupWizardPackage = getSetupWizardPackageName();
2814            if (mProtectedFilters.size() > 0) {
2815                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2816                    Slog.i(TAG, "No setup wizard;"
2817                        + " All protected intents capped to priority 0");
2818                }
2819                for (ActivityIntentInfo filter : mProtectedFilters) {
2820                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2821                        if (DEBUG_FILTERS) {
2822                            Slog.i(TAG, "Found setup wizard;"
2823                                + " allow priority " + filter.getPriority() + ";"
2824                                + " package: " + filter.activity.info.packageName
2825                                + " activity: " + filter.activity.className
2826                                + " priority: " + filter.getPriority());
2827                        }
2828                        // skip setup wizard; allow it to keep the high priority filter
2829                        continue;
2830                    }
2831                    if (DEBUG_FILTERS) {
2832                        Slog.i(TAG, "Protected action; cap priority to 0;"
2833                                + " package: " + filter.activity.info.packageName
2834                                + " activity: " + filter.activity.className
2835                                + " origPrio: " + filter.getPriority());
2836                    }
2837                    filter.setPriority(0);
2838                }
2839            }
2840            mDeferProtectedFilters = false;
2841            mProtectedFilters.clear();
2842
2843            // Now that we know all of the shared libraries, update all clients to have
2844            // the correct library paths.
2845            updateAllSharedLibrariesLPw(null);
2846
2847            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2848                // NOTE: We ignore potential failures here during a system scan (like
2849                // the rest of the commands above) because there's precious little we
2850                // can do about it. A settings error is reported, though.
2851                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2852            }
2853
2854            // Now that we know all the packages we are keeping,
2855            // read and update their last usage times.
2856            mPackageUsage.read(mPackages);
2857            mCompilerStats.read();
2858
2859            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2860                    SystemClock.uptimeMillis());
2861            Slog.i(TAG, "Time to scan packages: "
2862                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2863                    + " seconds");
2864
2865            // If the platform SDK has changed since the last time we booted,
2866            // we need to re-grant app permission to catch any new ones that
2867            // appear.  This is really a hack, and means that apps can in some
2868            // cases get permissions that the user didn't initially explicitly
2869            // allow...  it would be nice to have some better way to handle
2870            // this situation.
2871            int updateFlags = UPDATE_PERMISSIONS_ALL;
2872            if (ver.sdkVersion != mSdkVersion) {
2873                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2874                        + mSdkVersion + "; regranting permissions for internal storage");
2875                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2876            }
2877            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2878            ver.sdkVersion = mSdkVersion;
2879
2880            // If this is the first boot or an update from pre-M, and it is a normal
2881            // boot, then we need to initialize the default preferred apps across
2882            // all defined users.
2883            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2884                for (UserInfo user : sUserManager.getUsers(true)) {
2885                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2886                    applyFactoryDefaultBrowserLPw(user.id);
2887                    primeDomainVerificationsLPw(user.id);
2888                }
2889            }
2890
2891            // Prepare storage for system user really early during boot,
2892            // since core system apps like SettingsProvider and SystemUI
2893            // can't wait for user to start
2894            final int storageFlags;
2895            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2896                storageFlags = StorageManager.FLAG_STORAGE_DE;
2897            } else {
2898                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2899            }
2900            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2901                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2902                    true /* onlyCoreApps */);
2903            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2904                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2905                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2906                traceLog.traceBegin("AppDataFixup");
2907                try {
2908                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2909                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2910                } catch (InstallerException e) {
2911                    Slog.w(TAG, "Trouble fixing GIDs", e);
2912                }
2913                traceLog.traceEnd();
2914
2915                traceLog.traceBegin("AppDataPrepare");
2916                if (deferPackages == null || deferPackages.isEmpty()) {
2917                    return;
2918                }
2919                int count = 0;
2920                for (String pkgName : deferPackages) {
2921                    PackageParser.Package pkg = null;
2922                    synchronized (mPackages) {
2923                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2924                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2925                            pkg = ps.pkg;
2926                        }
2927                    }
2928                    if (pkg != null) {
2929                        synchronized (mInstallLock) {
2930                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2931                                    true /* maybeMigrateAppData */);
2932                        }
2933                        count++;
2934                    }
2935                }
2936                traceLog.traceEnd();
2937                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2938            }, "prepareAppData");
2939
2940            // If this is first boot after an OTA, and a normal boot, then
2941            // we need to clear code cache directories.
2942            // Note that we do *not* clear the application profiles. These remain valid
2943            // across OTAs and are used to drive profile verification (post OTA) and
2944            // profile compilation (without waiting to collect a fresh set of profiles).
2945            if (mIsUpgrade && !onlyCore) {
2946                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2947                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2948                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2949                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2950                        // No apps are running this early, so no need to freeze
2951                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2952                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2953                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2954                    }
2955                }
2956                ver.fingerprint = Build.FINGERPRINT;
2957            }
2958
2959            checkDefaultBrowser();
2960
2961            // clear only after permissions and other defaults have been updated
2962            mExistingSystemPackages.clear();
2963            mPromoteSystemApps = false;
2964
2965            // All the changes are done during package scanning.
2966            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2967
2968            // can downgrade to reader
2969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2970            mSettings.writeLPr();
2971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2972            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2973                    SystemClock.uptimeMillis());
2974
2975            if (!mOnlyCore) {
2976                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2977                mRequiredInstallerPackage = getRequiredInstallerLPr();
2978                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2979                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2980                if (mIntentFilterVerifierComponent != null) {
2981                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2982                            mIntentFilterVerifierComponent);
2983                } else {
2984                    mIntentFilterVerifier = null;
2985                }
2986                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2987                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2988                        SharedLibraryInfo.VERSION_UNDEFINED);
2989                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2990                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2991                        SharedLibraryInfo.VERSION_UNDEFINED);
2992            } else {
2993                mRequiredVerifierPackage = null;
2994                mRequiredInstallerPackage = null;
2995                mRequiredUninstallerPackage = null;
2996                mIntentFilterVerifierComponent = null;
2997                mIntentFilterVerifier = null;
2998                mServicesSystemSharedLibraryPackageName = null;
2999                mSharedSystemSharedLibraryPackageName = null;
3000            }
3001
3002            mInstallerService = new PackageInstallerService(context, this);
3003            final Pair<ComponentName, String> instantAppResolverComponent =
3004                    getInstantAppResolverLPr();
3005            if (instantAppResolverComponent != null) {
3006                if (DEBUG_EPHEMERAL) {
3007                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3008                }
3009                mInstantAppResolverConnection = new EphemeralResolverConnection(
3010                        mContext, instantAppResolverComponent.first,
3011                        instantAppResolverComponent.second);
3012                mInstantAppResolverSettingsComponent =
3013                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3014            } else {
3015                mInstantAppResolverConnection = null;
3016                mInstantAppResolverSettingsComponent = null;
3017            }
3018            updateInstantAppInstallerLocked(null);
3019
3020            // Read and update the usage of dex files.
3021            // Do this at the end of PM init so that all the packages have their
3022            // data directory reconciled.
3023            // At this point we know the code paths of the packages, so we can validate
3024            // the disk file and build the internal cache.
3025            // The usage file is expected to be small so loading and verifying it
3026            // should take a fairly small time compare to the other activities (e.g. package
3027            // scanning).
3028            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3029            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3030            for (int userId : currentUserIds) {
3031                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3032            }
3033            mDexManager.load(userPackages);
3034            if (mIsUpgrade) {
3035                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3036                        (int) (SystemClock.uptimeMillis() - startTime));
3037            }
3038        } // synchronized (mPackages)
3039        } // synchronized (mInstallLock)
3040
3041        // Now after opening every single application zip, make sure they
3042        // are all flushed.  Not really needed, but keeps things nice and
3043        // tidy.
3044        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3045        Runtime.getRuntime().gc();
3046        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3047
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3049        FallbackCategoryProvider.loadFallbacks();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        // The initial scanning above does many calls into installd while
3053        // holding the mPackages lock, but we're mostly interested in yelling
3054        // once we have a booted system.
3055        mInstaller.setWarnIfHeld(mPackages);
3056
3057        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3058    }
3059
3060    /**
3061     * Uncompress and install stub applications.
3062     * <p>In order to save space on the system partition, some applications are shipped in a
3063     * compressed form. In addition the compressed bits for the full application, the
3064     * system image contains a tiny stub comprised of only the Android manifest.
3065     * <p>During the first boot, attempt to uncompress and install the full application. If
3066     * the application can't be installed for any reason, disable the stub and prevent
3067     * uncompressing the full application during future boots.
3068     * <p>In order to forcefully attempt an installation of a full application, go to app
3069     * settings and enable the application.
3070     */
3071    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3072        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3073            final String pkgName = stubSystemApps.get(i);
3074            // skip if the system package is already disabled
3075            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3076                stubSystemApps.remove(i);
3077                continue;
3078            }
3079            // skip if the package isn't installed (?!); this should never happen
3080            final PackageParser.Package pkg = mPackages.get(pkgName);
3081            if (pkg == null) {
3082                stubSystemApps.remove(i);
3083                continue;
3084            }
3085            // skip if the package has been disabled by the user
3086            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3087            if (ps != null) {
3088                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3089                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3090                    stubSystemApps.remove(i);
3091                    continue;
3092                }
3093            }
3094
3095            if (DEBUG_COMPRESSION) {
3096                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3097            }
3098
3099            // uncompress the binary to its eventual destination on /data
3100            final File scanFile = decompressPackage(pkg);
3101            if (scanFile == null) {
3102                continue;
3103            }
3104
3105            // install the package to replace the stub on /system
3106            try {
3107                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3108                removePackageLI(pkg, true /*chatty*/);
3109                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3110                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3111                        UserHandle.USER_SYSTEM, "android");
3112                stubSystemApps.remove(i);
3113                continue;
3114            } catch (PackageManagerException e) {
3115                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3116            }
3117
3118            // any failed attempt to install the package will be cleaned up later
3119        }
3120
3121        // disable any stub still left; these failed to install the full application
3122        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3123            final String pkgName = stubSystemApps.get(i);
3124            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3125            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3126                    UserHandle.USER_SYSTEM, "android");
3127            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3128        }
3129    }
3130
3131    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3132        if (DEBUG_COMPRESSION) {
3133            Slog.i(TAG, "Decompress file"
3134                    + "; src: " + srcFile.getAbsolutePath()
3135                    + ", dst: " + dstFile.getAbsolutePath());
3136        }
3137        try (
3138                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3139                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3140        ) {
3141            Streams.copy(fileIn, fileOut);
3142            Os.chmod(dstFile.getAbsolutePath(), 0644);
3143            return PackageManager.INSTALL_SUCCEEDED;
3144        } catch (IOException e) {
3145            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3146                    + "; src: " + srcFile.getAbsolutePath()
3147                    + ", dst: " + dstFile.getAbsolutePath());
3148        }
3149        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3150    }
3151
3152    private File[] getCompressedFiles(String codePath) {
3153        final File stubCodePath = new File(codePath);
3154        final String stubName = stubCodePath.getName();
3155
3156        // The layout of a compressed package on a given partition is as follows :
3157        //
3158        // Compressed artifacts:
3159        //
3160        // /partition/ModuleName/foo.gz
3161        // /partation/ModuleName/bar.gz
3162        //
3163        // Stub artifact:
3164        //
3165        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3166        //
3167        // In other words, stub is on the same partition as the compressed artifacts
3168        // and in a directory that's suffixed with "-Stub".
3169        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3170        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3171            return null;
3172        }
3173
3174        final File stubParentDir = stubCodePath.getParentFile();
3175        if (stubParentDir == null) {
3176            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3177            return null;
3178        }
3179
3180        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3181        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3182            @Override
3183            public boolean accept(File dir, String name) {
3184                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3185            }
3186        });
3187
3188        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3189            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3190        }
3191
3192        return files;
3193    }
3194
3195    private boolean compressedFileExists(String codePath) {
3196        final File[] compressedFiles = getCompressedFiles(codePath);
3197        return compressedFiles != null && compressedFiles.length > 0;
3198    }
3199
3200    /**
3201     * Decompresses the given package on the system image onto
3202     * the /data partition.
3203     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3204     */
3205    private File decompressPackage(PackageParser.Package pkg) {
3206        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3207        if (compressedFiles == null || compressedFiles.length == 0) {
3208            if (DEBUG_COMPRESSION) {
3209                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3210            }
3211            return null;
3212        }
3213        final File dstCodePath =
3214                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3215        int ret = PackageManager.INSTALL_SUCCEEDED;
3216        try {
3217            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3218            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3219            for (File srcFile : compressedFiles) {
3220                final String srcFileName = srcFile.getName();
3221                final String dstFileName = srcFileName.substring(
3222                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3223                final File dstFile = new File(dstCodePath, dstFileName);
3224                ret = decompressFile(srcFile, dstFile);
3225                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3226                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3227                            + "; pkg: " + pkg.packageName
3228                            + ", file: " + dstFileName);
3229                    break;
3230                }
3231            }
3232        } catch (ErrnoException e) {
3233            logCriticalInfo(Log.ERROR, "Failed to decompress"
3234                    + "; pkg: " + pkg.packageName
3235                    + ", err: " + e.errno);
3236        }
3237        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3238            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3239            NativeLibraryHelper.Handle handle = null;
3240            try {
3241                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3242                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3243                        null /*abiOverride*/);
3244            } catch (IOException e) {
3245                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3246                        + "; pkg: " + pkg.packageName);
3247                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3248            } finally {
3249                IoUtils.closeQuietly(handle);
3250            }
3251        }
3252        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3253            if (dstCodePath == null || !dstCodePath.exists()) {
3254                return null;
3255            }
3256            removeCodePathLI(dstCodePath);
3257            return null;
3258        }
3259
3260        return dstCodePath;
3261    }
3262
3263    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3264        // we're only interested in updating the installer appliction when 1) it's not
3265        // already set or 2) the modified package is the installer
3266        if (mInstantAppInstallerActivity != null
3267                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3268                        .equals(modifiedPackage)) {
3269            return;
3270        }
3271        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3272    }
3273
3274    private static File preparePackageParserCache(boolean isUpgrade) {
3275        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3276            return null;
3277        }
3278
3279        // Disable package parsing on eng builds to allow for faster incremental development.
3280        if (Build.IS_ENG) {
3281            return null;
3282        }
3283
3284        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3285            Slog.i(TAG, "Disabling package parser cache due to system property.");
3286            return null;
3287        }
3288
3289        // The base directory for the package parser cache lives under /data/system/.
3290        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3291                "package_cache");
3292        if (cacheBaseDir == null) {
3293            return null;
3294        }
3295
3296        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3297        // This also serves to "GC" unused entries when the package cache version changes (which
3298        // can only happen during upgrades).
3299        if (isUpgrade) {
3300            FileUtils.deleteContents(cacheBaseDir);
3301        }
3302
3303
3304        // Return the versioned package cache directory. This is something like
3305        // "/data/system/package_cache/1"
3306        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3307
3308        // The following is a workaround to aid development on non-numbered userdebug
3309        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3310        // the system partition is newer.
3311        //
3312        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3313        // that starts with "eng." to signify that this is an engineering build and not
3314        // destined for release.
3315        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3316            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3317
3318            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3319            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3320            // in general and should not be used for production changes. In this specific case,
3321            // we know that they will work.
3322            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3323            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3324                FileUtils.deleteContents(cacheBaseDir);
3325                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3326            }
3327        }
3328
3329        return cacheDir;
3330    }
3331
3332    @Override
3333    public boolean isFirstBoot() {
3334        // allow instant applications
3335        return mFirstBoot;
3336    }
3337
3338    @Override
3339    public boolean isOnlyCoreApps() {
3340        // allow instant applications
3341        return mOnlyCore;
3342    }
3343
3344    @Override
3345    public boolean isUpgrade() {
3346        // allow instant applications
3347        // The system property allows testing ota flow when upgraded to the same image.
3348        return mIsUpgrade || SystemProperties.getBoolean(
3349                "persist.pm.mock-upgrade", false /* default */);
3350    }
3351
3352    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3353        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3354
3355        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3356                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3357                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3358        if (matches.size() == 1) {
3359            return matches.get(0).getComponentInfo().packageName;
3360        } else if (matches.size() == 0) {
3361            Log.e(TAG, "There should probably be a verifier, but, none were found");
3362            return null;
3363        }
3364        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3365    }
3366
3367    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3368        synchronized (mPackages) {
3369            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3370            if (libraryEntry == null) {
3371                throw new IllegalStateException("Missing required shared library:" + name);
3372            }
3373            return libraryEntry.apk;
3374        }
3375    }
3376
3377    private @NonNull String getRequiredInstallerLPr() {
3378        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3379        intent.addCategory(Intent.CATEGORY_DEFAULT);
3380        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3381
3382        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3383                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3384                UserHandle.USER_SYSTEM);
3385        if (matches.size() == 1) {
3386            ResolveInfo resolveInfo = matches.get(0);
3387            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3388                throw new RuntimeException("The installer must be a privileged app");
3389            }
3390            return matches.get(0).getComponentInfo().packageName;
3391        } else {
3392            throw new RuntimeException("There must be exactly one installer; found " + matches);
3393        }
3394    }
3395
3396    private @NonNull String getRequiredUninstallerLPr() {
3397        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3398        intent.addCategory(Intent.CATEGORY_DEFAULT);
3399        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3400
3401        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3402                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3403                UserHandle.USER_SYSTEM);
3404        if (resolveInfo == null ||
3405                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3406            throw new RuntimeException("There must be exactly one uninstaller; found "
3407                    + resolveInfo);
3408        }
3409        return resolveInfo.getComponentInfo().packageName;
3410    }
3411
3412    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3413        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3414
3415        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3416                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3417                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3418        ResolveInfo best = null;
3419        final int N = matches.size();
3420        for (int i = 0; i < N; i++) {
3421            final ResolveInfo cur = matches.get(i);
3422            final String packageName = cur.getComponentInfo().packageName;
3423            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3424                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3425                continue;
3426            }
3427
3428            if (best == null || cur.priority > best.priority) {
3429                best = cur;
3430            }
3431        }
3432
3433        if (best != null) {
3434            return best.getComponentInfo().getComponentName();
3435        }
3436        Slog.w(TAG, "Intent filter verifier not found");
3437        return null;
3438    }
3439
3440    @Override
3441    public @Nullable ComponentName getInstantAppResolverComponent() {
3442        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3443            return null;
3444        }
3445        synchronized (mPackages) {
3446            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3447            if (instantAppResolver == null) {
3448                return null;
3449            }
3450            return instantAppResolver.first;
3451        }
3452    }
3453
3454    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3455        final String[] packageArray =
3456                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3457        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3458            if (DEBUG_EPHEMERAL) {
3459                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3460            }
3461            return null;
3462        }
3463
3464        final int callingUid = Binder.getCallingUid();
3465        final int resolveFlags =
3466                MATCH_DIRECT_BOOT_AWARE
3467                | MATCH_DIRECT_BOOT_UNAWARE
3468                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3469        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3470        final Intent resolverIntent = new Intent(actionName);
3471        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3472                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3473        // temporarily look for the old action
3474        if (resolvers.size() == 0) {
3475            if (DEBUG_EPHEMERAL) {
3476                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3477            }
3478            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3479            resolverIntent.setAction(actionName);
3480            resolvers = queryIntentServicesInternal(resolverIntent, null,
3481                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3482        }
3483        final int N = resolvers.size();
3484        if (N == 0) {
3485            if (DEBUG_EPHEMERAL) {
3486                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3487            }
3488            return null;
3489        }
3490
3491        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3492        for (int i = 0; i < N; i++) {
3493            final ResolveInfo info = resolvers.get(i);
3494
3495            if (info.serviceInfo == null) {
3496                continue;
3497            }
3498
3499            final String packageName = info.serviceInfo.packageName;
3500            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3501                if (DEBUG_EPHEMERAL) {
3502                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3503                            + " pkg: " + packageName + ", info:" + info);
3504                }
3505                continue;
3506            }
3507
3508            if (DEBUG_EPHEMERAL) {
3509                Slog.v(TAG, "Ephemeral resolver found;"
3510                        + " pkg: " + packageName + ", info:" + info);
3511            }
3512            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3513        }
3514        if (DEBUG_EPHEMERAL) {
3515            Slog.v(TAG, "Ephemeral resolver NOT found");
3516        }
3517        return null;
3518    }
3519
3520    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3521        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3522        intent.addCategory(Intent.CATEGORY_DEFAULT);
3523        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3524
3525        final int resolveFlags =
3526                MATCH_DIRECT_BOOT_AWARE
3527                | MATCH_DIRECT_BOOT_UNAWARE
3528                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3529        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3530                resolveFlags, UserHandle.USER_SYSTEM);
3531        // temporarily look for the old action
3532        if (matches.isEmpty()) {
3533            if (DEBUG_EPHEMERAL) {
3534                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3535            }
3536            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3537            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3538                    resolveFlags, UserHandle.USER_SYSTEM);
3539        }
3540        Iterator<ResolveInfo> iter = matches.iterator();
3541        while (iter.hasNext()) {
3542            final ResolveInfo rInfo = iter.next();
3543            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3544            if (ps != null) {
3545                final PermissionsState permissionsState = ps.getPermissionsState();
3546                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3547                    continue;
3548                }
3549            }
3550            iter.remove();
3551        }
3552        if (matches.size() == 0) {
3553            return null;
3554        } else if (matches.size() == 1) {
3555            return (ActivityInfo) matches.get(0).getComponentInfo();
3556        } else {
3557            throw new RuntimeException(
3558                    "There must be at most one ephemeral installer; found " + matches);
3559        }
3560    }
3561
3562    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3563            @NonNull ComponentName resolver) {
3564        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3565                .addCategory(Intent.CATEGORY_DEFAULT)
3566                .setPackage(resolver.getPackageName());
3567        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3568        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3569                UserHandle.USER_SYSTEM);
3570        // temporarily look for the old action
3571        if (matches.isEmpty()) {
3572            if (DEBUG_EPHEMERAL) {
3573                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3574            }
3575            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3576            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3577                    UserHandle.USER_SYSTEM);
3578        }
3579        if (matches.isEmpty()) {
3580            return null;
3581        }
3582        return matches.get(0).getComponentInfo().getComponentName();
3583    }
3584
3585    private void primeDomainVerificationsLPw(int userId) {
3586        if (DEBUG_DOMAIN_VERIFICATION) {
3587            Slog.d(TAG, "Priming domain verifications in user " + userId);
3588        }
3589
3590        SystemConfig systemConfig = SystemConfig.getInstance();
3591        ArraySet<String> packages = systemConfig.getLinkedApps();
3592
3593        for (String packageName : packages) {
3594            PackageParser.Package pkg = mPackages.get(packageName);
3595            if (pkg != null) {
3596                if (!pkg.isSystemApp()) {
3597                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3598                    continue;
3599                }
3600
3601                ArraySet<String> domains = null;
3602                for (PackageParser.Activity a : pkg.activities) {
3603                    for (ActivityIntentInfo filter : a.intents) {
3604                        if (hasValidDomains(filter)) {
3605                            if (domains == null) {
3606                                domains = new ArraySet<String>();
3607                            }
3608                            domains.addAll(filter.getHostsList());
3609                        }
3610                    }
3611                }
3612
3613                if (domains != null && domains.size() > 0) {
3614                    if (DEBUG_DOMAIN_VERIFICATION) {
3615                        Slog.v(TAG, "      + " + packageName);
3616                    }
3617                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3618                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3619                    // and then 'always' in the per-user state actually used for intent resolution.
3620                    final IntentFilterVerificationInfo ivi;
3621                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3622                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3623                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3624                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3625                } else {
3626                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3627                            + "' does not handle web links");
3628                }
3629            } else {
3630                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3631            }
3632        }
3633
3634        scheduleWritePackageRestrictionsLocked(userId);
3635        scheduleWriteSettingsLocked();
3636    }
3637
3638    private void applyFactoryDefaultBrowserLPw(int userId) {
3639        // The default browser app's package name is stored in a string resource,
3640        // with a product-specific overlay used for vendor customization.
3641        String browserPkg = mContext.getResources().getString(
3642                com.android.internal.R.string.default_browser);
3643        if (!TextUtils.isEmpty(browserPkg)) {
3644            // non-empty string => required to be a known package
3645            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3646            if (ps == null) {
3647                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3648                browserPkg = null;
3649            } else {
3650                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3651            }
3652        }
3653
3654        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3655        // default.  If there's more than one, just leave everything alone.
3656        if (browserPkg == null) {
3657            calculateDefaultBrowserLPw(userId);
3658        }
3659    }
3660
3661    private void calculateDefaultBrowserLPw(int userId) {
3662        List<String> allBrowsers = resolveAllBrowserApps(userId);
3663        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3664        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3665    }
3666
3667    private List<String> resolveAllBrowserApps(int userId) {
3668        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3669        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3670                PackageManager.MATCH_ALL, userId);
3671
3672        final int count = list.size();
3673        List<String> result = new ArrayList<String>(count);
3674        for (int i=0; i<count; i++) {
3675            ResolveInfo info = list.get(i);
3676            if (info.activityInfo == null
3677                    || !info.handleAllWebDataURI
3678                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3679                    || result.contains(info.activityInfo.packageName)) {
3680                continue;
3681            }
3682            result.add(info.activityInfo.packageName);
3683        }
3684
3685        return result;
3686    }
3687
3688    private boolean packageIsBrowser(String packageName, int userId) {
3689        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3690                PackageManager.MATCH_ALL, userId);
3691        final int N = list.size();
3692        for (int i = 0; i < N; i++) {
3693            ResolveInfo info = list.get(i);
3694            if (packageName.equals(info.activityInfo.packageName)) {
3695                return true;
3696            }
3697        }
3698        return false;
3699    }
3700
3701    private void checkDefaultBrowser() {
3702        final int myUserId = UserHandle.myUserId();
3703        final String packageName = getDefaultBrowserPackageName(myUserId);
3704        if (packageName != null) {
3705            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3706            if (info == null) {
3707                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3708                synchronized (mPackages) {
3709                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3710                }
3711            }
3712        }
3713    }
3714
3715    @Override
3716    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3717            throws RemoteException {
3718        try {
3719            return super.onTransact(code, data, reply, flags);
3720        } catch (RuntimeException e) {
3721            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3722                Slog.wtf(TAG, "Package Manager Crash", e);
3723            }
3724            throw e;
3725        }
3726    }
3727
3728    static int[] appendInts(int[] cur, int[] add) {
3729        if (add == null) return cur;
3730        if (cur == null) return add;
3731        final int N = add.length;
3732        for (int i=0; i<N; i++) {
3733            cur = appendInt(cur, add[i]);
3734        }
3735        return cur;
3736    }
3737
3738    /**
3739     * Returns whether or not a full application can see an instant application.
3740     * <p>
3741     * Currently, there are three cases in which this can occur:
3742     * <ol>
3743     * <li>The calling application is a "special" process. The special
3744     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3745     *     and {@code 0}</li>
3746     * <li>The calling application has the permission
3747     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3748     * <li>The calling application is the default launcher on the
3749     *     system partition.</li>
3750     * </ol>
3751     */
3752    private boolean canViewInstantApps(int callingUid, int userId) {
3753        if (callingUid == Process.SYSTEM_UID
3754                || callingUid == Process.SHELL_UID
3755                || callingUid == Process.ROOT_UID) {
3756            return true;
3757        }
3758        if (mContext.checkCallingOrSelfPermission(
3759                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3765            if (homeComponent != null
3766                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3767                return true;
3768            }
3769        }
3770        return false;
3771    }
3772
3773    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3774        if (!sUserManager.exists(userId)) return null;
3775        if (ps == null) {
3776            return null;
3777        }
3778        PackageParser.Package p = ps.pkg;
3779        if (p == null) {
3780            return null;
3781        }
3782        final int callingUid = Binder.getCallingUid();
3783        // Filter out ephemeral app metadata:
3784        //   * The system/shell/root can see metadata for any app
3785        //   * An installed app can see metadata for 1) other installed apps
3786        //     and 2) ephemeral apps that have explicitly interacted with it
3787        //   * Ephemeral apps can only see their own data and exposed installed apps
3788        //   * Holding a signature permission allows seeing instant apps
3789        if (filterAppAccessLPr(ps, callingUid, userId)) {
3790            return null;
3791        }
3792
3793        final PermissionsState permissionsState = ps.getPermissionsState();
3794
3795        // Compute GIDs only if requested
3796        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3797                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3798        // Compute granted permissions only if package has requested permissions
3799        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3800                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3801        final PackageUserState state = ps.readUserState(userId);
3802
3803        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3804                && ps.isSystem()) {
3805            flags |= MATCH_ANY_USER;
3806        }
3807
3808        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3809                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3810
3811        if (packageInfo == null) {
3812            return null;
3813        }
3814
3815        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3816                resolveExternalPackageNameLPr(p);
3817
3818        return packageInfo;
3819    }
3820
3821    @Override
3822    public void checkPackageStartable(String packageName, int userId) {
3823        final int callingUid = Binder.getCallingUid();
3824        if (getInstantAppPackageName(callingUid) != null) {
3825            throw new SecurityException("Instant applications don't have access to this method");
3826        }
3827        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3828        synchronized (mPackages) {
3829            final PackageSetting ps = mSettings.mPackages.get(packageName);
3830            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3831                throw new SecurityException("Package " + packageName + " was not found!");
3832            }
3833
3834            if (!ps.getInstalled(userId)) {
3835                throw new SecurityException(
3836                        "Package " + packageName + " was not installed for user " + userId + "!");
3837            }
3838
3839            if (mSafeMode && !ps.isSystem()) {
3840                throw new SecurityException("Package " + packageName + " not a system app!");
3841            }
3842
3843            if (mFrozenPackages.contains(packageName)) {
3844                throw new SecurityException("Package " + packageName + " is currently frozen!");
3845            }
3846
3847            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3848                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3849            }
3850        }
3851    }
3852
3853    @Override
3854    public boolean isPackageAvailable(String packageName, int userId) {
3855        if (!sUserManager.exists(userId)) return false;
3856        final int callingUid = Binder.getCallingUid();
3857        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3858                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3859        synchronized (mPackages) {
3860            PackageParser.Package p = mPackages.get(packageName);
3861            if (p != null) {
3862                final PackageSetting ps = (PackageSetting) p.mExtras;
3863                if (filterAppAccessLPr(ps, callingUid, userId)) {
3864                    return false;
3865                }
3866                if (ps != null) {
3867                    final PackageUserState state = ps.readUserState(userId);
3868                    if (state != null) {
3869                        return PackageParser.isAvailable(state);
3870                    }
3871                }
3872            }
3873        }
3874        return false;
3875    }
3876
3877    @Override
3878    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3879        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3880                flags, Binder.getCallingUid(), userId);
3881    }
3882
3883    @Override
3884    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3885            int flags, int userId) {
3886        return getPackageInfoInternal(versionedPackage.getPackageName(),
3887                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3888    }
3889
3890    /**
3891     * Important: The provided filterCallingUid is used exclusively to filter out packages
3892     * that can be seen based on user state. It's typically the original caller uid prior
3893     * to clearing. Because it can only be provided by trusted code, it's value can be
3894     * trusted and will be used as-is; unlike userId which will be validated by this method.
3895     */
3896    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3897            int flags, int filterCallingUid, int userId) {
3898        if (!sUserManager.exists(userId)) return null;
3899        flags = updateFlagsForPackage(flags, userId, packageName);
3900        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3901                false /* requireFullPermission */, false /* checkShell */, "get package info");
3902
3903        // reader
3904        synchronized (mPackages) {
3905            // Normalize package name to handle renamed packages and static libs
3906            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3907
3908            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3909            if (matchFactoryOnly) {
3910                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3911                if (ps != null) {
3912                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3913                        return null;
3914                    }
3915                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3916                        return null;
3917                    }
3918                    return generatePackageInfo(ps, flags, userId);
3919                }
3920            }
3921
3922            PackageParser.Package p = mPackages.get(packageName);
3923            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3924                return null;
3925            }
3926            if (DEBUG_PACKAGE_INFO)
3927                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3928            if (p != null) {
3929                final PackageSetting ps = (PackageSetting) p.mExtras;
3930                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3931                    return null;
3932                }
3933                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3934                    return null;
3935                }
3936                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3937            }
3938            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3939                final PackageSetting ps = mSettings.mPackages.get(packageName);
3940                if (ps == null) return null;
3941                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3942                    return null;
3943                }
3944                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3945                    return null;
3946                }
3947                return generatePackageInfo(ps, flags, userId);
3948            }
3949        }
3950        return null;
3951    }
3952
3953    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3954        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3955            return true;
3956        }
3957        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3958            return true;
3959        }
3960        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3961            return true;
3962        }
3963        return false;
3964    }
3965
3966    private boolean isComponentVisibleToInstantApp(
3967            @Nullable ComponentName component, @ComponentType int type) {
3968        if (type == TYPE_ACTIVITY) {
3969            final PackageParser.Activity activity = mActivities.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_RECEIVER) {
3974            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3975            return activity != null
3976                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3977                    : false;
3978        } else if (type == TYPE_SERVICE) {
3979            final PackageParser.Service service = mServices.mServices.get(component);
3980            return service != null
3981                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_PROVIDER) {
3984            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3985            return provider != null
3986                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_UNKNOWN) {
3989            return isComponentVisibleToInstantApp(component);
3990        }
3991        return false;
3992    }
3993
3994    /**
3995     * Returns whether or not access to the application should be filtered.
3996     * <p>
3997     * Access may be limited based upon whether the calling or target applications
3998     * are instant applications.
3999     *
4000     * @see #canAccessInstantApps(int)
4001     */
4002    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4003            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4004        // if we're in an isolated process, get the real calling UID
4005        if (Process.isIsolated(callingUid)) {
4006            callingUid = mIsolatedOwners.get(callingUid);
4007        }
4008        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4009        final boolean callerIsInstantApp = instantAppPkgName != null;
4010        if (ps == null) {
4011            if (callerIsInstantApp) {
4012                // pretend the application exists, but, needs to be filtered
4013                return true;
4014            }
4015            return false;
4016        }
4017        // if the target and caller are the same application, don't filter
4018        if (isCallerSameApp(ps.name, callingUid)) {
4019            return false;
4020        }
4021        if (callerIsInstantApp) {
4022            // request for a specific component; if it hasn't been explicitly exposed, filter
4023            if (component != null) {
4024                return !isComponentVisibleToInstantApp(component, componentType);
4025            }
4026            // request for application; if no components have been explicitly exposed, filter
4027            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4028        }
4029        if (ps.getInstantApp(userId)) {
4030            // caller can see all components of all instant applications, don't filter
4031            if (canViewInstantApps(callingUid, userId)) {
4032                return false;
4033            }
4034            // request for a specific instant application component, filter
4035            if (component != null) {
4036                return true;
4037            }
4038            // request for an instant application; if the caller hasn't been granted access, filter
4039            return !mInstantAppRegistry.isInstantAccessGranted(
4040                    userId, UserHandle.getAppId(callingUid), ps.appId);
4041        }
4042        return false;
4043    }
4044
4045    /**
4046     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4047     */
4048    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4049        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4050    }
4051
4052    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4053            int flags) {
4054        // Callers can access only the libs they depend on, otherwise they need to explicitly
4055        // ask for the shared libraries given the caller is allowed to access all static libs.
4056        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4057            // System/shell/root get to see all static libs
4058            final int appId = UserHandle.getAppId(uid);
4059            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4060                    || appId == Process.ROOT_UID) {
4061                return false;
4062            }
4063        }
4064
4065        // No package means no static lib as it is always on internal storage
4066        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4067            return false;
4068        }
4069
4070        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4071                ps.pkg.staticSharedLibVersion);
4072        if (libEntry == null) {
4073            return false;
4074        }
4075
4076        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4077        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4078        if (uidPackageNames == null) {
4079            return true;
4080        }
4081
4082        for (String uidPackageName : uidPackageNames) {
4083            if (ps.name.equals(uidPackageName)) {
4084                return false;
4085            }
4086            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4087            if (uidPs != null) {
4088                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4089                        libEntry.info.getName());
4090                if (index < 0) {
4091                    continue;
4092                }
4093                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4094                    return false;
4095                }
4096            }
4097        }
4098        return true;
4099    }
4100
4101    @Override
4102    public String[] currentToCanonicalPackageNames(String[] names) {
4103        final int callingUid = Binder.getCallingUid();
4104        if (getInstantAppPackageName(callingUid) != null) {
4105            return names;
4106        }
4107        final String[] out = new String[names.length];
4108        // reader
4109        synchronized (mPackages) {
4110            final int callingUserId = UserHandle.getUserId(callingUid);
4111            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4112            for (int i=names.length-1; i>=0; i--) {
4113                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4114                boolean translateName = false;
4115                if (ps != null && ps.realName != null) {
4116                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4117                    translateName = !targetIsInstantApp
4118                            || canViewInstantApps
4119                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4120                                    UserHandle.getAppId(callingUid), ps.appId);
4121                }
4122                out[i] = translateName ? ps.realName : names[i];
4123            }
4124        }
4125        return out;
4126    }
4127
4128    @Override
4129    public String[] canonicalToCurrentPackageNames(String[] names) {
4130        final int callingUid = Binder.getCallingUid();
4131        if (getInstantAppPackageName(callingUid) != null) {
4132            return names;
4133        }
4134        final String[] out = new String[names.length];
4135        // reader
4136        synchronized (mPackages) {
4137            final int callingUserId = UserHandle.getUserId(callingUid);
4138            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4139            for (int i=names.length-1; i>=0; i--) {
4140                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4141                boolean translateName = false;
4142                if (cur != null) {
4143                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4144                    final boolean targetIsInstantApp =
4145                            ps != null && ps.getInstantApp(callingUserId);
4146                    translateName = !targetIsInstantApp
4147                            || canViewInstantApps
4148                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4149                                    UserHandle.getAppId(callingUid), ps.appId);
4150                }
4151                out[i] = translateName ? cur : names[i];
4152            }
4153        }
4154        return out;
4155    }
4156
4157    @Override
4158    public int getPackageUid(String packageName, int flags, int userId) {
4159        if (!sUserManager.exists(userId)) return -1;
4160        final int callingUid = Binder.getCallingUid();
4161        flags = updateFlagsForPackage(flags, userId, packageName);
4162        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4163                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4164
4165        // reader
4166        synchronized (mPackages) {
4167            final PackageParser.Package p = mPackages.get(packageName);
4168            if (p != null && p.isMatch(flags)) {
4169                PackageSetting ps = (PackageSetting) p.mExtras;
4170                if (filterAppAccessLPr(ps, callingUid, userId)) {
4171                    return -1;
4172                }
4173                return UserHandle.getUid(userId, p.applicationInfo.uid);
4174            }
4175            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4176                final PackageSetting ps = mSettings.mPackages.get(packageName);
4177                if (ps != null && ps.isMatch(flags)
4178                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4179                    return UserHandle.getUid(userId, ps.appId);
4180                }
4181            }
4182        }
4183
4184        return -1;
4185    }
4186
4187    @Override
4188    public int[] getPackageGids(String packageName, int flags, int userId) {
4189        if (!sUserManager.exists(userId)) return null;
4190        final int callingUid = Binder.getCallingUid();
4191        flags = updateFlagsForPackage(flags, userId, packageName);
4192        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4193                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4194
4195        // reader
4196        synchronized (mPackages) {
4197            final PackageParser.Package p = mPackages.get(packageName);
4198            if (p != null && p.isMatch(flags)) {
4199                PackageSetting ps = (PackageSetting) p.mExtras;
4200                if (filterAppAccessLPr(ps, callingUid, userId)) {
4201                    return null;
4202                }
4203                // TODO: Shouldn't this be checking for package installed state for userId and
4204                // return null?
4205                return ps.getPermissionsState().computeGids(userId);
4206            }
4207            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4208                final PackageSetting ps = mSettings.mPackages.get(packageName);
4209                if (ps != null && ps.isMatch(flags)
4210                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4211                    return ps.getPermissionsState().computeGids(userId);
4212                }
4213            }
4214        }
4215
4216        return null;
4217    }
4218
4219    @Override
4220    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4221        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4222    }
4223
4224    @Override
4225    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4226            int flags) {
4227        final List<PermissionInfo> permissionList =
4228                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4229        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4230    }
4231
4232    @Override
4233    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4234        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4235    }
4236
4237    @Override
4238    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4239        final List<PermissionGroupInfo> permissionList =
4240                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4241        return (permissionList == null)
4242                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4243    }
4244
4245    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4246            int filterCallingUid, int userId) {
4247        if (!sUserManager.exists(userId)) return null;
4248        PackageSetting ps = mSettings.mPackages.get(packageName);
4249        if (ps != null) {
4250            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4251                return null;
4252            }
4253            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4254                return null;
4255            }
4256            if (ps.pkg == null) {
4257                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4258                if (pInfo != null) {
4259                    return pInfo.applicationInfo;
4260                }
4261                return null;
4262            }
4263            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4264                    ps.readUserState(userId), userId);
4265            if (ai != null) {
4266                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4267            }
4268            return ai;
4269        }
4270        return null;
4271    }
4272
4273    @Override
4274    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4275        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4276    }
4277
4278    /**
4279     * Important: The provided filterCallingUid is used exclusively to filter out applications
4280     * that can be seen based on user state. It's typically the original caller uid prior
4281     * to clearing. Because it can only be provided by trusted code, it's value can be
4282     * trusted and will be used as-is; unlike userId which will be validated by this method.
4283     */
4284    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4285            int filterCallingUid, int userId) {
4286        if (!sUserManager.exists(userId)) return null;
4287        flags = updateFlagsForApplication(flags, userId, packageName);
4288        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4289                false /* requireFullPermission */, false /* checkShell */, "get application info");
4290
4291        // writer
4292        synchronized (mPackages) {
4293            // Normalize package name to handle renamed packages and static libs
4294            packageName = resolveInternalPackageNameLPr(packageName,
4295                    PackageManager.VERSION_CODE_HIGHEST);
4296
4297            PackageParser.Package p = mPackages.get(packageName);
4298            if (DEBUG_PACKAGE_INFO) Log.v(
4299                    TAG, "getApplicationInfo " + packageName
4300                    + ": " + p);
4301            if (p != null) {
4302                PackageSetting ps = mSettings.mPackages.get(packageName);
4303                if (ps == null) return null;
4304                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4305                    return null;
4306                }
4307                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4308                    return null;
4309                }
4310                // Note: isEnabledLP() does not apply here - always return info
4311                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4312                        p, flags, ps.readUserState(userId), userId);
4313                if (ai != null) {
4314                    ai.packageName = resolveExternalPackageNameLPr(p);
4315                }
4316                return ai;
4317            }
4318            if ("android".equals(packageName)||"system".equals(packageName)) {
4319                return mAndroidApplication;
4320            }
4321            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4322                // Already generates the external package name
4323                return generateApplicationInfoFromSettingsLPw(packageName,
4324                        flags, filterCallingUid, userId);
4325            }
4326        }
4327        return null;
4328    }
4329
4330    private String normalizePackageNameLPr(String packageName) {
4331        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4332        return normalizedPackageName != null ? normalizedPackageName : packageName;
4333    }
4334
4335    @Override
4336    public void deletePreloadsFileCache() {
4337        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4338            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4339        }
4340        File dir = Environment.getDataPreloadsFileCacheDirectory();
4341        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4342        FileUtils.deleteContents(dir);
4343    }
4344
4345    @Override
4346    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4347            final int storageFlags, final IPackageDataObserver observer) {
4348        mContext.enforceCallingOrSelfPermission(
4349                android.Manifest.permission.CLEAR_APP_CACHE, null);
4350        mHandler.post(() -> {
4351            boolean success = false;
4352            try {
4353                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4354                success = true;
4355            } catch (IOException e) {
4356                Slog.w(TAG, e);
4357            }
4358            if (observer != null) {
4359                try {
4360                    observer.onRemoveCompleted(null, success);
4361                } catch (RemoteException e) {
4362                    Slog.w(TAG, e);
4363                }
4364            }
4365        });
4366    }
4367
4368    @Override
4369    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4370            final int storageFlags, final IntentSender pi) {
4371        mContext.enforceCallingOrSelfPermission(
4372                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4373        mHandler.post(() -> {
4374            boolean success = false;
4375            try {
4376                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4377                success = true;
4378            } catch (IOException e) {
4379                Slog.w(TAG, e);
4380            }
4381            if (pi != null) {
4382                try {
4383                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4384                } catch (SendIntentException e) {
4385                    Slog.w(TAG, e);
4386                }
4387            }
4388        });
4389    }
4390
4391    /**
4392     * Blocking call to clear various types of cached data across the system
4393     * until the requested bytes are available.
4394     */
4395    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4396        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4397        final File file = storage.findPathForUuid(volumeUuid);
4398        if (file.getUsableSpace() >= bytes) return;
4399
4400        if (ENABLE_FREE_CACHE_V2) {
4401            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4402                    volumeUuid);
4403            final boolean aggressive = (storageFlags
4404                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4405            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4406
4407            // 1. Pre-flight to determine if we have any chance to succeed
4408            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4409            if (internalVolume && (aggressive || SystemProperties
4410                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4411                deletePreloadsFileCache();
4412                if (file.getUsableSpace() >= bytes) return;
4413            }
4414
4415            // 3. Consider parsed APK data (aggressive only)
4416            if (internalVolume && aggressive) {
4417                FileUtils.deleteContents(mCacheDir);
4418                if (file.getUsableSpace() >= bytes) return;
4419            }
4420
4421            // 4. Consider cached app data (above quotas)
4422            try {
4423                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4424                        Installer.FLAG_FREE_CACHE_V2);
4425            } catch (InstallerException ignored) {
4426            }
4427            if (file.getUsableSpace() >= bytes) return;
4428
4429            // 5. Consider shared libraries with refcount=0 and age>min cache period
4430            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4431                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4432                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4433                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4434                return;
4435            }
4436
4437            // 6. Consider dexopt output (aggressive only)
4438            // TODO: Implement
4439
4440            // 7. Consider installed instant apps unused longer than min cache period
4441            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4442                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4443                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4444                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4445                return;
4446            }
4447
4448            // 8. Consider cached app data (below quotas)
4449            try {
4450                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4451                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4452            } catch (InstallerException ignored) {
4453            }
4454            if (file.getUsableSpace() >= bytes) return;
4455
4456            // 9. Consider DropBox entries
4457            // TODO: Implement
4458
4459            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4460            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4461                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4462                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4463                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4464                return;
4465            }
4466        } else {
4467            try {
4468                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4469            } catch (InstallerException ignored) {
4470            }
4471            if (file.getUsableSpace() >= bytes) return;
4472        }
4473
4474        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4475    }
4476
4477    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4478            throws IOException {
4479        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4480        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4481
4482        List<VersionedPackage> packagesToDelete = null;
4483        final long now = System.currentTimeMillis();
4484
4485        synchronized (mPackages) {
4486            final int[] allUsers = sUserManager.getUserIds();
4487            final int libCount = mSharedLibraries.size();
4488            for (int i = 0; i < libCount; i++) {
4489                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4490                if (versionedLib == null) {
4491                    continue;
4492                }
4493                final int versionCount = versionedLib.size();
4494                for (int j = 0; j < versionCount; j++) {
4495                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4496                    // Skip packages that are not static shared libs.
4497                    if (!libInfo.isStatic()) {
4498                        break;
4499                    }
4500                    // Important: We skip static shared libs used for some user since
4501                    // in such a case we need to keep the APK on the device. The check for
4502                    // a lib being used for any user is performed by the uninstall call.
4503                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4504                    // Resolve the package name - we use synthetic package names internally
4505                    final String internalPackageName = resolveInternalPackageNameLPr(
4506                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4507                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4508                    // Skip unused static shared libs cached less than the min period
4509                    // to prevent pruning a lib needed by a subsequently installed package.
4510                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4511                        continue;
4512                    }
4513                    if (packagesToDelete == null) {
4514                        packagesToDelete = new ArrayList<>();
4515                    }
4516                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4517                            declaringPackage.getVersionCode()));
4518                }
4519            }
4520        }
4521
4522        if (packagesToDelete != null) {
4523            final int packageCount = packagesToDelete.size();
4524            for (int i = 0; i < packageCount; i++) {
4525                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4526                // Delete the package synchronously (will fail of the lib used for any user).
4527                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4528                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4529                                == PackageManager.DELETE_SUCCEEDED) {
4530                    if (volume.getUsableSpace() >= neededSpace) {
4531                        return true;
4532                    }
4533                }
4534            }
4535        }
4536
4537        return false;
4538    }
4539
4540    /**
4541     * Update given flags based on encryption status of current user.
4542     */
4543    private int updateFlags(int flags, int userId) {
4544        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4545                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4546            // Caller expressed an explicit opinion about what encryption
4547            // aware/unaware components they want to see, so fall through and
4548            // give them what they want
4549        } else {
4550            // Caller expressed no opinion, so match based on user state
4551            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4552                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4553            } else {
4554                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4555            }
4556        }
4557        return flags;
4558    }
4559
4560    private UserManagerInternal getUserManagerInternal() {
4561        if (mUserManagerInternal == null) {
4562            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4563        }
4564        return mUserManagerInternal;
4565    }
4566
4567    private DeviceIdleController.LocalService getDeviceIdleController() {
4568        if (mDeviceIdleController == null) {
4569            mDeviceIdleController =
4570                    LocalServices.getService(DeviceIdleController.LocalService.class);
4571        }
4572        return mDeviceIdleController;
4573    }
4574
4575    /**
4576     * Update given flags when being used to request {@link PackageInfo}.
4577     */
4578    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4579        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4580        boolean triaged = true;
4581        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4582                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4583            // Caller is asking for component details, so they'd better be
4584            // asking for specific encryption matching behavior, or be triaged
4585            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4586                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4587                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4588                triaged = false;
4589            }
4590        }
4591        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4592                | PackageManager.MATCH_SYSTEM_ONLY
4593                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4594            triaged = false;
4595        }
4596        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4597            mPermissionManager.enforceCrossUserPermission(
4598                    Binder.getCallingUid(), userId, false, false,
4599                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4600                    + Debug.getCallers(5));
4601        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4602                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4603            // If the caller wants all packages and has a restricted profile associated with it,
4604            // then match all users. This is to make sure that launchers that need to access work
4605            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4606            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4607            flags |= PackageManager.MATCH_ANY_USER;
4608        }
4609        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4610            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4611                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4612        }
4613        return updateFlags(flags, userId);
4614    }
4615
4616    /**
4617     * Update given flags when being used to request {@link ApplicationInfo}.
4618     */
4619    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4620        return updateFlagsForPackage(flags, userId, cookie);
4621    }
4622
4623    /**
4624     * Update given flags when being used to request {@link ComponentInfo}.
4625     */
4626    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4627        if (cookie instanceof Intent) {
4628            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4629                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4630            }
4631        }
4632
4633        boolean triaged = true;
4634        // Caller is asking for component details, so they'd better be
4635        // asking for specific encryption matching behavior, or be triaged
4636        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4637                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4638                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4639            triaged = false;
4640        }
4641        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4642            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4643                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4644        }
4645
4646        return updateFlags(flags, userId);
4647    }
4648
4649    /**
4650     * Update given intent when being used to request {@link ResolveInfo}.
4651     */
4652    private Intent updateIntentForResolve(Intent intent) {
4653        if (intent.getSelector() != null) {
4654            intent = intent.getSelector();
4655        }
4656        if (DEBUG_PREFERRED) {
4657            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4658        }
4659        return intent;
4660    }
4661
4662    /**
4663     * Update given flags when being used to request {@link ResolveInfo}.
4664     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4665     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4666     * flag set. However, this flag is only honoured in three circumstances:
4667     * <ul>
4668     * <li>when called from a system process</li>
4669     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4670     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4671     * action and a {@code android.intent.category.BROWSABLE} category</li>
4672     * </ul>
4673     */
4674    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4675        return updateFlagsForResolve(flags, userId, intent, callingUid,
4676                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4677    }
4678    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4679            boolean wantInstantApps) {
4680        return updateFlagsForResolve(flags, userId, intent, callingUid,
4681                wantInstantApps, false /*onlyExposedExplicitly*/);
4682    }
4683    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4684            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4685        // Safe mode means we shouldn't match any third-party components
4686        if (mSafeMode) {
4687            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4688        }
4689        if (getInstantAppPackageName(callingUid) != null) {
4690            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4691            if (onlyExposedExplicitly) {
4692                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4693            }
4694            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4695            flags |= PackageManager.MATCH_INSTANT;
4696        } else {
4697            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4698            final boolean allowMatchInstant =
4699                    (wantInstantApps
4700                            && Intent.ACTION_VIEW.equals(intent.getAction())
4701                            && hasWebURI(intent))
4702                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4703            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4704                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4705            if (!allowMatchInstant) {
4706                flags &= ~PackageManager.MATCH_INSTANT;
4707            }
4708        }
4709        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4710    }
4711
4712    @Override
4713    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4714        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4715    }
4716
4717    /**
4718     * Important: The provided filterCallingUid is used exclusively to filter out activities
4719     * that can be seen based on user state. It's typically the original caller uid prior
4720     * to clearing. Because it can only be provided by trusted code, it's value can be
4721     * trusted and will be used as-is; unlike userId which will be validated by this method.
4722     */
4723    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4724            int filterCallingUid, int userId) {
4725        if (!sUserManager.exists(userId)) return null;
4726        flags = updateFlagsForComponent(flags, userId, component);
4727        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4728                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4729        synchronized (mPackages) {
4730            PackageParser.Activity a = mActivities.mActivities.get(component);
4731
4732            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4733            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4734                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4735                if (ps == null) return null;
4736                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4737                    return null;
4738                }
4739                return PackageParser.generateActivityInfo(
4740                        a, flags, ps.readUserState(userId), userId);
4741            }
4742            if (mResolveComponentName.equals(component)) {
4743                return PackageParser.generateActivityInfo(
4744                        mResolveActivity, flags, new PackageUserState(), userId);
4745            }
4746        }
4747        return null;
4748    }
4749
4750    @Override
4751    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4752            String resolvedType) {
4753        synchronized (mPackages) {
4754            if (component.equals(mResolveComponentName)) {
4755                // The resolver supports EVERYTHING!
4756                return true;
4757            }
4758            final int callingUid = Binder.getCallingUid();
4759            final int callingUserId = UserHandle.getUserId(callingUid);
4760            PackageParser.Activity a = mActivities.mActivities.get(component);
4761            if (a == null) {
4762                return false;
4763            }
4764            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4765            if (ps == null) {
4766                return false;
4767            }
4768            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4769                return false;
4770            }
4771            for (int i=0; i<a.intents.size(); i++) {
4772                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4773                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4774                    return true;
4775                }
4776            }
4777            return false;
4778        }
4779    }
4780
4781    @Override
4782    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4783        if (!sUserManager.exists(userId)) return null;
4784        final int callingUid = Binder.getCallingUid();
4785        flags = updateFlagsForComponent(flags, userId, component);
4786        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4787                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4788        synchronized (mPackages) {
4789            PackageParser.Activity a = mReceivers.mActivities.get(component);
4790            if (DEBUG_PACKAGE_INFO) Log.v(
4791                TAG, "getReceiverInfo " + component + ": " + a);
4792            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4793                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4794                if (ps == null) return null;
4795                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4796                    return null;
4797                }
4798                return PackageParser.generateActivityInfo(
4799                        a, flags, ps.readUserState(userId), userId);
4800            }
4801        }
4802        return null;
4803    }
4804
4805    @Override
4806    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4807            int flags, int userId) {
4808        if (!sUserManager.exists(userId)) return null;
4809        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4810        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4811            return null;
4812        }
4813
4814        flags = updateFlagsForPackage(flags, userId, null);
4815
4816        final boolean canSeeStaticLibraries =
4817                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4818                        == PERMISSION_GRANTED
4819                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4820                        == PERMISSION_GRANTED
4821                || canRequestPackageInstallsInternal(packageName,
4822                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4823                        false  /* throwIfPermNotDeclared*/)
4824                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4825                        == PERMISSION_GRANTED;
4826
4827        synchronized (mPackages) {
4828            List<SharedLibraryInfo> result = null;
4829
4830            final int libCount = mSharedLibraries.size();
4831            for (int i = 0; i < libCount; i++) {
4832                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4833                if (versionedLib == null) {
4834                    continue;
4835                }
4836
4837                final int versionCount = versionedLib.size();
4838                for (int j = 0; j < versionCount; j++) {
4839                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4840                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4841                        break;
4842                    }
4843                    final long identity = Binder.clearCallingIdentity();
4844                    try {
4845                        PackageInfo packageInfo = getPackageInfoVersioned(
4846                                libInfo.getDeclaringPackage(), flags
4847                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4848                        if (packageInfo == null) {
4849                            continue;
4850                        }
4851                    } finally {
4852                        Binder.restoreCallingIdentity(identity);
4853                    }
4854
4855                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4856                            libInfo.getVersion(), libInfo.getType(),
4857                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4858                            flags, userId));
4859
4860                    if (result == null) {
4861                        result = new ArrayList<>();
4862                    }
4863                    result.add(resLibInfo);
4864                }
4865            }
4866
4867            return result != null ? new ParceledListSlice<>(result) : null;
4868        }
4869    }
4870
4871    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4872            SharedLibraryInfo libInfo, int flags, int userId) {
4873        List<VersionedPackage> versionedPackages = null;
4874        final int packageCount = mSettings.mPackages.size();
4875        for (int i = 0; i < packageCount; i++) {
4876            PackageSetting ps = mSettings.mPackages.valueAt(i);
4877
4878            if (ps == null) {
4879                continue;
4880            }
4881
4882            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4883                continue;
4884            }
4885
4886            final String libName = libInfo.getName();
4887            if (libInfo.isStatic()) {
4888                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4889                if (libIdx < 0) {
4890                    continue;
4891                }
4892                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4893                    continue;
4894                }
4895                if (versionedPackages == null) {
4896                    versionedPackages = new ArrayList<>();
4897                }
4898                // If the dependent is a static shared lib, use the public package name
4899                String dependentPackageName = ps.name;
4900                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4901                    dependentPackageName = ps.pkg.manifestPackageName;
4902                }
4903                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4904            } else if (ps.pkg != null) {
4905                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4906                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4907                    if (versionedPackages == null) {
4908                        versionedPackages = new ArrayList<>();
4909                    }
4910                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4911                }
4912            }
4913        }
4914
4915        return versionedPackages;
4916    }
4917
4918    @Override
4919    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4920        if (!sUserManager.exists(userId)) return null;
4921        final int callingUid = Binder.getCallingUid();
4922        flags = updateFlagsForComponent(flags, userId, component);
4923        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4924                false /* requireFullPermission */, false /* checkShell */, "get service info");
4925        synchronized (mPackages) {
4926            PackageParser.Service s = mServices.mServices.get(component);
4927            if (DEBUG_PACKAGE_INFO) Log.v(
4928                TAG, "getServiceInfo " + component + ": " + s);
4929            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4930                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4931                if (ps == null) return null;
4932                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4933                    return null;
4934                }
4935                return PackageParser.generateServiceInfo(
4936                        s, flags, ps.readUserState(userId), userId);
4937            }
4938        }
4939        return null;
4940    }
4941
4942    @Override
4943    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4944        if (!sUserManager.exists(userId)) return null;
4945        final int callingUid = Binder.getCallingUid();
4946        flags = updateFlagsForComponent(flags, userId, component);
4947        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4948                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4949        synchronized (mPackages) {
4950            PackageParser.Provider p = mProviders.mProviders.get(component);
4951            if (DEBUG_PACKAGE_INFO) Log.v(
4952                TAG, "getProviderInfo " + component + ": " + p);
4953            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4954                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4955                if (ps == null) return null;
4956                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4957                    return null;
4958                }
4959                return PackageParser.generateProviderInfo(
4960                        p, flags, ps.readUserState(userId), userId);
4961            }
4962        }
4963        return null;
4964    }
4965
4966    @Override
4967    public String[] getSystemSharedLibraryNames() {
4968        // allow instant applications
4969        synchronized (mPackages) {
4970            Set<String> libs = null;
4971            final int libCount = mSharedLibraries.size();
4972            for (int i = 0; i < libCount; i++) {
4973                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4974                if (versionedLib == null) {
4975                    continue;
4976                }
4977                final int versionCount = versionedLib.size();
4978                for (int j = 0; j < versionCount; j++) {
4979                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4980                    if (!libEntry.info.isStatic()) {
4981                        if (libs == null) {
4982                            libs = new ArraySet<>();
4983                        }
4984                        libs.add(libEntry.info.getName());
4985                        break;
4986                    }
4987                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4988                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4989                            UserHandle.getUserId(Binder.getCallingUid()),
4990                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4991                        if (libs == null) {
4992                            libs = new ArraySet<>();
4993                        }
4994                        libs.add(libEntry.info.getName());
4995                        break;
4996                    }
4997                }
4998            }
4999
5000            if (libs != null) {
5001                String[] libsArray = new String[libs.size()];
5002                libs.toArray(libsArray);
5003                return libsArray;
5004            }
5005
5006            return null;
5007        }
5008    }
5009
5010    @Override
5011    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5012        // allow instant applications
5013        synchronized (mPackages) {
5014            return mServicesSystemSharedLibraryPackageName;
5015        }
5016    }
5017
5018    @Override
5019    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5020        // allow instant applications
5021        synchronized (mPackages) {
5022            return mSharedSystemSharedLibraryPackageName;
5023        }
5024    }
5025
5026    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5027        for (int i = userList.length - 1; i >= 0; --i) {
5028            final int userId = userList[i];
5029            // don't add instant app to the list of updates
5030            if (pkgSetting.getInstantApp(userId)) {
5031                continue;
5032            }
5033            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5034            if (changedPackages == null) {
5035                changedPackages = new SparseArray<>();
5036                mChangedPackages.put(userId, changedPackages);
5037            }
5038            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5039            if (sequenceNumbers == null) {
5040                sequenceNumbers = new HashMap<>();
5041                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5042            }
5043            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5044            if (sequenceNumber != null) {
5045                changedPackages.remove(sequenceNumber);
5046            }
5047            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5048            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5049        }
5050        mChangedPackagesSequenceNumber++;
5051    }
5052
5053    @Override
5054    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5055        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5056            return null;
5057        }
5058        synchronized (mPackages) {
5059            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5060                return null;
5061            }
5062            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5063            if (changedPackages == null) {
5064                return null;
5065            }
5066            final List<String> packageNames =
5067                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5068            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5069                final String packageName = changedPackages.get(i);
5070                if (packageName != null) {
5071                    packageNames.add(packageName);
5072                }
5073            }
5074            return packageNames.isEmpty()
5075                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5076        }
5077    }
5078
5079    @Override
5080    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5081        // allow instant applications
5082        ArrayList<FeatureInfo> res;
5083        synchronized (mAvailableFeatures) {
5084            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5085            res.addAll(mAvailableFeatures.values());
5086        }
5087        final FeatureInfo fi = new FeatureInfo();
5088        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5089                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5090        res.add(fi);
5091
5092        return new ParceledListSlice<>(res);
5093    }
5094
5095    @Override
5096    public boolean hasSystemFeature(String name, int version) {
5097        // allow instant applications
5098        synchronized (mAvailableFeatures) {
5099            final FeatureInfo feat = mAvailableFeatures.get(name);
5100            if (feat == null) {
5101                return false;
5102            } else {
5103                return feat.version >= version;
5104            }
5105        }
5106    }
5107
5108    @Override
5109    public int checkPermission(String permName, String pkgName, int userId) {
5110        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5111    }
5112
5113    @Override
5114    public int checkUidPermission(String permName, int uid) {
5115        final int callingUid = Binder.getCallingUid();
5116        final int callingUserId = UserHandle.getUserId(callingUid);
5117        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5118        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5119        final int userId = UserHandle.getUserId(uid);
5120        if (!sUserManager.exists(userId)) {
5121            return PackageManager.PERMISSION_DENIED;
5122        }
5123
5124        synchronized (mPackages) {
5125            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5126            if (obj != null) {
5127                if (obj instanceof SharedUserSetting) {
5128                    if (isCallerInstantApp) {
5129                        return PackageManager.PERMISSION_DENIED;
5130                    }
5131                } else if (obj instanceof PackageSetting) {
5132                    final PackageSetting ps = (PackageSetting) obj;
5133                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5134                        return PackageManager.PERMISSION_DENIED;
5135                    }
5136                }
5137                final SettingBase settingBase = (SettingBase) obj;
5138                final PermissionsState permissionsState = settingBase.getPermissionsState();
5139                if (permissionsState.hasPermission(permName, userId)) {
5140                    if (isUidInstantApp) {
5141                        if (mSettings.mPermissions.isPermissionInstant(permName)) {
5142                            return PackageManager.PERMISSION_GRANTED;
5143                        }
5144                    } else {
5145                        return PackageManager.PERMISSION_GRANTED;
5146                    }
5147                }
5148                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5149                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5150                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5151                    return PackageManager.PERMISSION_GRANTED;
5152                }
5153            } else {
5154                ArraySet<String> perms = mSystemPermissions.get(uid);
5155                if (perms != null) {
5156                    if (perms.contains(permName)) {
5157                        return PackageManager.PERMISSION_GRANTED;
5158                    }
5159                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5160                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5161                        return PackageManager.PERMISSION_GRANTED;
5162                    }
5163                }
5164            }
5165        }
5166
5167        return PackageManager.PERMISSION_DENIED;
5168    }
5169
5170    @Override
5171    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5172        if (UserHandle.getCallingUserId() != userId) {
5173            mContext.enforceCallingPermission(
5174                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5175                    "isPermissionRevokedByPolicy for user " + userId);
5176        }
5177
5178        if (checkPermission(permission, packageName, userId)
5179                == PackageManager.PERMISSION_GRANTED) {
5180            return false;
5181        }
5182
5183        final int callingUid = Binder.getCallingUid();
5184        if (getInstantAppPackageName(callingUid) != null) {
5185            if (!isCallerSameApp(packageName, callingUid)) {
5186                return false;
5187            }
5188        } else {
5189            if (isInstantApp(packageName, userId)) {
5190                return false;
5191            }
5192        }
5193
5194        final long identity = Binder.clearCallingIdentity();
5195        try {
5196            final int flags = getPermissionFlags(permission, packageName, userId);
5197            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5198        } finally {
5199            Binder.restoreCallingIdentity(identity);
5200        }
5201    }
5202
5203    @Override
5204    public String getPermissionControllerPackageName() {
5205        synchronized (mPackages) {
5206            return mRequiredInstallerPackage;
5207        }
5208    }
5209
5210    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5211        return mPermissionManager.addDynamicPermission(
5212                info, async, getCallingUid(), new PermissionCallback() {
5213                    @Override
5214                    public void onPermissionChanged() {
5215                        if (!async) {
5216                            mSettings.writeLPr();
5217                        } else {
5218                            scheduleWriteSettingsLocked();
5219                        }
5220                    }
5221                });
5222    }
5223
5224    @Override
5225    public boolean addPermission(PermissionInfo info) {
5226        synchronized (mPackages) {
5227            return addDynamicPermission(info, false);
5228        }
5229    }
5230
5231    @Override
5232    public boolean addPermissionAsync(PermissionInfo info) {
5233        synchronized (mPackages) {
5234            return addDynamicPermission(info, true);
5235        }
5236    }
5237
5238    @Override
5239    public void removePermission(String permName) {
5240        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5241    }
5242
5243    @Override
5244    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5245        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5246                getCallingUid(), userId, mPermissionCallback);
5247    }
5248
5249    @Override
5250    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5251        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5252                getCallingUid(), userId, mPermissionCallback);
5253    }
5254
5255    /**
5256     * Get the first event id for the permission.
5257     *
5258     * <p>There are four events for each permission: <ul>
5259     *     <li>Request permission: first id + 0</li>
5260     *     <li>Grant permission: first id + 1</li>
5261     *     <li>Request for permission denied: first id + 2</li>
5262     *     <li>Revoke permission: first id + 3</li>
5263     * </ul></p>
5264     *
5265     * @param name name of the permission
5266     *
5267     * @return The first event id for the permission
5268     */
5269    private static int getBaseEventId(@NonNull String name) {
5270        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5271
5272        if (eventIdIndex == -1) {
5273            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5274                    || Build.IS_USER) {
5275                Log.i(TAG, "Unknown permission " + name);
5276
5277                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5278            } else {
5279                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5280                //
5281                // Also update
5282                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5283                // - metrics_constants.proto
5284                throw new IllegalStateException("Unknown permission " + name);
5285            }
5286        }
5287
5288        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5289    }
5290
5291    /**
5292     * Log that a permission was revoked.
5293     *
5294     * @param context Context of the caller
5295     * @param name name of the permission
5296     * @param packageName package permission if for
5297     */
5298    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5299            @NonNull String packageName) {
5300        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5301    }
5302
5303    /**
5304     * Log that a permission request was granted.
5305     *
5306     * @param context Context of the caller
5307     * @param name name of the permission
5308     * @param packageName package permission if for
5309     */
5310    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5311            @NonNull String packageName) {
5312        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5313    }
5314
5315    @Override
5316    public void resetRuntimePermissions() {
5317        mContext.enforceCallingOrSelfPermission(
5318                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5319                "revokeRuntimePermission");
5320
5321        int callingUid = Binder.getCallingUid();
5322        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5323            mContext.enforceCallingOrSelfPermission(
5324                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5325                    "resetRuntimePermissions");
5326        }
5327
5328        synchronized (mPackages) {
5329            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5330            for (int userId : UserManagerService.getInstance().getUserIds()) {
5331                final int packageCount = mPackages.size();
5332                for (int i = 0; i < packageCount; i++) {
5333                    PackageParser.Package pkg = mPackages.valueAt(i);
5334                    if (!(pkg.mExtras instanceof PackageSetting)) {
5335                        continue;
5336                    }
5337                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5338                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5339                }
5340            }
5341        }
5342    }
5343
5344    @Override
5345    public int getPermissionFlags(String permName, String packageName, int userId) {
5346        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5347    }
5348
5349    @Override
5350    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5351            int flagValues, int userId) {
5352        mPermissionManager.updatePermissionFlags(
5353                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5354                mPermissionCallback);
5355    }
5356
5357    /**
5358     * Update the permission flags for all packages and runtime permissions of a user in order
5359     * to allow device or profile owner to remove POLICY_FIXED.
5360     */
5361    @Override
5362    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5363        synchronized (mPackages) {
5364            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5365                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5366                    mPermissionCallback);
5367            if (changed) {
5368                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5369            }
5370        }
5371    }
5372
5373    @Override
5374    public boolean shouldShowRequestPermissionRationale(String permissionName,
5375            String packageName, int userId) {
5376        if (UserHandle.getCallingUserId() != userId) {
5377            mContext.enforceCallingPermission(
5378                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5379                    "canShowRequestPermissionRationale for user " + userId);
5380        }
5381
5382        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5383        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5384            return false;
5385        }
5386
5387        if (checkPermission(permissionName, packageName, userId)
5388                == PackageManager.PERMISSION_GRANTED) {
5389            return false;
5390        }
5391
5392        final int flags;
5393
5394        final long identity = Binder.clearCallingIdentity();
5395        try {
5396            flags = getPermissionFlags(permissionName,
5397                    packageName, userId);
5398        } finally {
5399            Binder.restoreCallingIdentity(identity);
5400        }
5401
5402        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5403                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5404                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5405
5406        if ((flags & fixedFlags) != 0) {
5407            return false;
5408        }
5409
5410        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5411    }
5412
5413    @Override
5414    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5415        mContext.enforceCallingOrSelfPermission(
5416                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5417                "addOnPermissionsChangeListener");
5418
5419        synchronized (mPackages) {
5420            mOnPermissionChangeListeners.addListenerLocked(listener);
5421        }
5422    }
5423
5424    @Override
5425    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5426        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5427            throw new SecurityException("Instant applications don't have access to this method");
5428        }
5429        synchronized (mPackages) {
5430            mOnPermissionChangeListeners.removeListenerLocked(listener);
5431        }
5432    }
5433
5434    @Override
5435    public boolean isProtectedBroadcast(String actionName) {
5436        // allow instant applications
5437        synchronized (mProtectedBroadcasts) {
5438            if (mProtectedBroadcasts.contains(actionName)) {
5439                return true;
5440            } else if (actionName != null) {
5441                // TODO: remove these terrible hacks
5442                if (actionName.startsWith("android.net.netmon.lingerExpired")
5443                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5444                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5445                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5446                    return true;
5447                }
5448            }
5449        }
5450        return false;
5451    }
5452
5453    @Override
5454    public int checkSignatures(String pkg1, String pkg2) {
5455        synchronized (mPackages) {
5456            final PackageParser.Package p1 = mPackages.get(pkg1);
5457            final PackageParser.Package p2 = mPackages.get(pkg2);
5458            if (p1 == null || p1.mExtras == null
5459                    || p2 == null || p2.mExtras == null) {
5460                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5461            }
5462            final int callingUid = Binder.getCallingUid();
5463            final int callingUserId = UserHandle.getUserId(callingUid);
5464            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5465            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5466            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5467                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5468                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5469            }
5470            return compareSignatures(p1.mSignatures, p2.mSignatures);
5471        }
5472    }
5473
5474    @Override
5475    public int checkUidSignatures(int uid1, int uid2) {
5476        final int callingUid = Binder.getCallingUid();
5477        final int callingUserId = UserHandle.getUserId(callingUid);
5478        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5479        // Map to base uids.
5480        uid1 = UserHandle.getAppId(uid1);
5481        uid2 = UserHandle.getAppId(uid2);
5482        // reader
5483        synchronized (mPackages) {
5484            Signature[] s1;
5485            Signature[] s2;
5486            Object obj = mSettings.getUserIdLPr(uid1);
5487            if (obj != null) {
5488                if (obj instanceof SharedUserSetting) {
5489                    if (isCallerInstantApp) {
5490                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5491                    }
5492                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5493                } else if (obj instanceof PackageSetting) {
5494                    final PackageSetting ps = (PackageSetting) obj;
5495                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5496                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5497                    }
5498                    s1 = ps.signatures.mSignatures;
5499                } else {
5500                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5501                }
5502            } else {
5503                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5504            }
5505            obj = mSettings.getUserIdLPr(uid2);
5506            if (obj != null) {
5507                if (obj instanceof SharedUserSetting) {
5508                    if (isCallerInstantApp) {
5509                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5510                    }
5511                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5512                } else if (obj instanceof PackageSetting) {
5513                    final PackageSetting ps = (PackageSetting) obj;
5514                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5515                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5516                    }
5517                    s2 = ps.signatures.mSignatures;
5518                } else {
5519                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5520                }
5521            } else {
5522                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5523            }
5524            return compareSignatures(s1, s2);
5525        }
5526    }
5527
5528    /**
5529     * This method should typically only be used when granting or revoking
5530     * permissions, since the app may immediately restart after this call.
5531     * <p>
5532     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5533     * guard your work against the app being relaunched.
5534     */
5535    private void killUid(int appId, int userId, String reason) {
5536        final long identity = Binder.clearCallingIdentity();
5537        try {
5538            IActivityManager am = ActivityManager.getService();
5539            if (am != null) {
5540                try {
5541                    am.killUid(appId, userId, reason);
5542                } catch (RemoteException e) {
5543                    /* ignore - same process */
5544                }
5545            }
5546        } finally {
5547            Binder.restoreCallingIdentity(identity);
5548        }
5549    }
5550
5551    /**
5552     * Compares two sets of signatures. Returns:
5553     * <br />
5554     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5555     * <br />
5556     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5557     * <br />
5558     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5559     * <br />
5560     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5561     * <br />
5562     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5563     */
5564    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5565        if (s1 == null) {
5566            return s2 == null
5567                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5568                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5569        }
5570
5571        if (s2 == null) {
5572            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5573        }
5574
5575        if (s1.length != s2.length) {
5576            return PackageManager.SIGNATURE_NO_MATCH;
5577        }
5578
5579        // Since both signature sets are of size 1, we can compare without HashSets.
5580        if (s1.length == 1) {
5581            return s1[0].equals(s2[0]) ?
5582                    PackageManager.SIGNATURE_MATCH :
5583                    PackageManager.SIGNATURE_NO_MATCH;
5584        }
5585
5586        ArraySet<Signature> set1 = new ArraySet<Signature>();
5587        for (Signature sig : s1) {
5588            set1.add(sig);
5589        }
5590        ArraySet<Signature> set2 = new ArraySet<Signature>();
5591        for (Signature sig : s2) {
5592            set2.add(sig);
5593        }
5594        // Make sure s2 contains all signatures in s1.
5595        if (set1.equals(set2)) {
5596            return PackageManager.SIGNATURE_MATCH;
5597        }
5598        return PackageManager.SIGNATURE_NO_MATCH;
5599    }
5600
5601    /**
5602     * If the database version for this type of package (internal storage or
5603     * external storage) is less than the version where package signatures
5604     * were updated, return true.
5605     */
5606    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5607        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5608        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5609    }
5610
5611    /**
5612     * Used for backward compatibility to make sure any packages with
5613     * certificate chains get upgraded to the new style. {@code existingSigs}
5614     * will be in the old format (since they were stored on disk from before the
5615     * system upgrade) and {@code scannedSigs} will be in the newer format.
5616     */
5617    private int compareSignaturesCompat(PackageSignatures existingSigs,
5618            PackageParser.Package scannedPkg) {
5619        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5620            return PackageManager.SIGNATURE_NO_MATCH;
5621        }
5622
5623        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5624        for (Signature sig : existingSigs.mSignatures) {
5625            existingSet.add(sig);
5626        }
5627        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5628        for (Signature sig : scannedPkg.mSignatures) {
5629            try {
5630                Signature[] chainSignatures = sig.getChainSignatures();
5631                for (Signature chainSig : chainSignatures) {
5632                    scannedCompatSet.add(chainSig);
5633                }
5634            } catch (CertificateEncodingException e) {
5635                scannedCompatSet.add(sig);
5636            }
5637        }
5638        /*
5639         * Make sure the expanded scanned set contains all signatures in the
5640         * existing one.
5641         */
5642        if (scannedCompatSet.equals(existingSet)) {
5643            // Migrate the old signatures to the new scheme.
5644            existingSigs.assignSignatures(scannedPkg.mSignatures);
5645            // The new KeySets will be re-added later in the scanning process.
5646            synchronized (mPackages) {
5647                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5648            }
5649            return PackageManager.SIGNATURE_MATCH;
5650        }
5651        return PackageManager.SIGNATURE_NO_MATCH;
5652    }
5653
5654    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5655        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5656        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5657    }
5658
5659    private int compareSignaturesRecover(PackageSignatures existingSigs,
5660            PackageParser.Package scannedPkg) {
5661        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5662            return PackageManager.SIGNATURE_NO_MATCH;
5663        }
5664
5665        String msg = null;
5666        try {
5667            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5668                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5669                        + scannedPkg.packageName);
5670                return PackageManager.SIGNATURE_MATCH;
5671            }
5672        } catch (CertificateException e) {
5673            msg = e.getMessage();
5674        }
5675
5676        logCriticalInfo(Log.INFO,
5677                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5678        return PackageManager.SIGNATURE_NO_MATCH;
5679    }
5680
5681    @Override
5682    public List<String> getAllPackages() {
5683        final int callingUid = Binder.getCallingUid();
5684        final int callingUserId = UserHandle.getUserId(callingUid);
5685        synchronized (mPackages) {
5686            if (canViewInstantApps(callingUid, callingUserId)) {
5687                return new ArrayList<String>(mPackages.keySet());
5688            }
5689            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5690            final List<String> result = new ArrayList<>();
5691            if (instantAppPkgName != null) {
5692                // caller is an instant application; filter unexposed applications
5693                for (PackageParser.Package pkg : mPackages.values()) {
5694                    if (!pkg.visibleToInstantApps) {
5695                        continue;
5696                    }
5697                    result.add(pkg.packageName);
5698                }
5699            } else {
5700                // caller is a normal application; filter instant applications
5701                for (PackageParser.Package pkg : mPackages.values()) {
5702                    final PackageSetting ps =
5703                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5704                    if (ps != null
5705                            && ps.getInstantApp(callingUserId)
5706                            && !mInstantAppRegistry.isInstantAccessGranted(
5707                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5708                        continue;
5709                    }
5710                    result.add(pkg.packageName);
5711                }
5712            }
5713            return result;
5714        }
5715    }
5716
5717    @Override
5718    public String[] getPackagesForUid(int uid) {
5719        final int callingUid = Binder.getCallingUid();
5720        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5721        final int userId = UserHandle.getUserId(uid);
5722        uid = UserHandle.getAppId(uid);
5723        // reader
5724        synchronized (mPackages) {
5725            Object obj = mSettings.getUserIdLPr(uid);
5726            if (obj instanceof SharedUserSetting) {
5727                if (isCallerInstantApp) {
5728                    return null;
5729                }
5730                final SharedUserSetting sus = (SharedUserSetting) obj;
5731                final int N = sus.packages.size();
5732                String[] res = new String[N];
5733                final Iterator<PackageSetting> it = sus.packages.iterator();
5734                int i = 0;
5735                while (it.hasNext()) {
5736                    PackageSetting ps = it.next();
5737                    if (ps.getInstalled(userId)) {
5738                        res[i++] = ps.name;
5739                    } else {
5740                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5741                    }
5742                }
5743                return res;
5744            } else if (obj instanceof PackageSetting) {
5745                final PackageSetting ps = (PackageSetting) obj;
5746                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5747                    return new String[]{ps.name};
5748                }
5749            }
5750        }
5751        return null;
5752    }
5753
5754    @Override
5755    public String getNameForUid(int uid) {
5756        final int callingUid = Binder.getCallingUid();
5757        if (getInstantAppPackageName(callingUid) != null) {
5758            return null;
5759        }
5760        synchronized (mPackages) {
5761            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5762            if (obj instanceof SharedUserSetting) {
5763                final SharedUserSetting sus = (SharedUserSetting) obj;
5764                return sus.name + ":" + sus.userId;
5765            } else if (obj instanceof PackageSetting) {
5766                final PackageSetting ps = (PackageSetting) obj;
5767                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5768                    return null;
5769                }
5770                return ps.name;
5771            }
5772            return null;
5773        }
5774    }
5775
5776    @Override
5777    public String[] getNamesForUids(int[] uids) {
5778        if (uids == null || uids.length == 0) {
5779            return null;
5780        }
5781        final int callingUid = Binder.getCallingUid();
5782        if (getInstantAppPackageName(callingUid) != null) {
5783            return null;
5784        }
5785        final String[] names = new String[uids.length];
5786        synchronized (mPackages) {
5787            for (int i = uids.length - 1; i >= 0; i--) {
5788                final int uid = uids[i];
5789                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5790                if (obj instanceof SharedUserSetting) {
5791                    final SharedUserSetting sus = (SharedUserSetting) obj;
5792                    names[i] = "shared:" + sus.name;
5793                } else if (obj instanceof PackageSetting) {
5794                    final PackageSetting ps = (PackageSetting) obj;
5795                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5796                        names[i] = null;
5797                    } else {
5798                        names[i] = ps.name;
5799                    }
5800                } else {
5801                    names[i] = null;
5802                }
5803            }
5804        }
5805        return names;
5806    }
5807
5808    @Override
5809    public int getUidForSharedUser(String sharedUserName) {
5810        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5811            return -1;
5812        }
5813        if (sharedUserName == null) {
5814            return -1;
5815        }
5816        // reader
5817        synchronized (mPackages) {
5818            SharedUserSetting suid;
5819            try {
5820                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5821                if (suid != null) {
5822                    return suid.userId;
5823                }
5824            } catch (PackageManagerException ignore) {
5825                // can't happen, but, still need to catch it
5826            }
5827            return -1;
5828        }
5829    }
5830
5831    @Override
5832    public int getFlagsForUid(int uid) {
5833        final int callingUid = Binder.getCallingUid();
5834        if (getInstantAppPackageName(callingUid) != null) {
5835            return 0;
5836        }
5837        synchronized (mPackages) {
5838            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5839            if (obj instanceof SharedUserSetting) {
5840                final SharedUserSetting sus = (SharedUserSetting) obj;
5841                return sus.pkgFlags;
5842            } else if (obj instanceof PackageSetting) {
5843                final PackageSetting ps = (PackageSetting) obj;
5844                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5845                    return 0;
5846                }
5847                return ps.pkgFlags;
5848            }
5849        }
5850        return 0;
5851    }
5852
5853    @Override
5854    public int getPrivateFlagsForUid(int uid) {
5855        final int callingUid = Binder.getCallingUid();
5856        if (getInstantAppPackageName(callingUid) != null) {
5857            return 0;
5858        }
5859        synchronized (mPackages) {
5860            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5861            if (obj instanceof SharedUserSetting) {
5862                final SharedUserSetting sus = (SharedUserSetting) obj;
5863                return sus.pkgPrivateFlags;
5864            } else if (obj instanceof PackageSetting) {
5865                final PackageSetting ps = (PackageSetting) obj;
5866                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5867                    return 0;
5868                }
5869                return ps.pkgPrivateFlags;
5870            }
5871        }
5872        return 0;
5873    }
5874
5875    @Override
5876    public boolean isUidPrivileged(int uid) {
5877        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5878            return false;
5879        }
5880        uid = UserHandle.getAppId(uid);
5881        // reader
5882        synchronized (mPackages) {
5883            Object obj = mSettings.getUserIdLPr(uid);
5884            if (obj instanceof SharedUserSetting) {
5885                final SharedUserSetting sus = (SharedUserSetting) obj;
5886                final Iterator<PackageSetting> it = sus.packages.iterator();
5887                while (it.hasNext()) {
5888                    if (it.next().isPrivileged()) {
5889                        return true;
5890                    }
5891                }
5892            } else if (obj instanceof PackageSetting) {
5893                final PackageSetting ps = (PackageSetting) obj;
5894                return ps.isPrivileged();
5895            }
5896        }
5897        return false;
5898    }
5899
5900    @Override
5901    public String[] getAppOpPermissionPackages(String permName) {
5902        return mPermissionManager.getAppOpPermissionPackages(permName);
5903    }
5904
5905    @Override
5906    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5907            int flags, int userId) {
5908        return resolveIntentInternal(
5909                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5910    }
5911
5912    /**
5913     * Normally instant apps can only be resolved when they're visible to the caller.
5914     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5915     * since we need to allow the system to start any installed application.
5916     */
5917    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5918            int flags, int userId, boolean resolveForStart) {
5919        try {
5920            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5921
5922            if (!sUserManager.exists(userId)) return null;
5923            final int callingUid = Binder.getCallingUid();
5924            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5925            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5926                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5927
5928            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5929            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5930                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5931            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5932
5933            final ResolveInfo bestChoice =
5934                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5935            return bestChoice;
5936        } finally {
5937            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5938        }
5939    }
5940
5941    @Override
5942    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5943        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5944            throw new SecurityException(
5945                    "findPersistentPreferredActivity can only be run by the system");
5946        }
5947        if (!sUserManager.exists(userId)) {
5948            return null;
5949        }
5950        final int callingUid = Binder.getCallingUid();
5951        intent = updateIntentForResolve(intent);
5952        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5953        final int flags = updateFlagsForResolve(
5954                0, userId, intent, callingUid, false /*includeInstantApps*/);
5955        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5956                userId);
5957        synchronized (mPackages) {
5958            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5959                    userId);
5960        }
5961    }
5962
5963    @Override
5964    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5965            IntentFilter filter, int match, ComponentName activity) {
5966        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5967            return;
5968        }
5969        final int userId = UserHandle.getCallingUserId();
5970        if (DEBUG_PREFERRED) {
5971            Log.v(TAG, "setLastChosenActivity intent=" + intent
5972                + " resolvedType=" + resolvedType
5973                + " flags=" + flags
5974                + " filter=" + filter
5975                + " match=" + match
5976                + " activity=" + activity);
5977            filter.dump(new PrintStreamPrinter(System.out), "    ");
5978        }
5979        intent.setComponent(null);
5980        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5981                userId);
5982        // Find any earlier preferred or last chosen entries and nuke them
5983        findPreferredActivity(intent, resolvedType,
5984                flags, query, 0, false, true, false, userId);
5985        // Add the new activity as the last chosen for this filter
5986        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5987                "Setting last chosen");
5988    }
5989
5990    @Override
5991    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5993            return null;
5994        }
5995        final int userId = UserHandle.getCallingUserId();
5996        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5997        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5998                userId);
5999        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6000                false, false, false, userId);
6001    }
6002
6003    /**
6004     * Returns whether or not instant apps have been disabled remotely.
6005     */
6006    private boolean isEphemeralDisabled() {
6007        return mEphemeralAppsDisabled;
6008    }
6009
6010    private boolean isInstantAppAllowed(
6011            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6012            boolean skipPackageCheck) {
6013        if (mInstantAppResolverConnection == null) {
6014            return false;
6015        }
6016        if (mInstantAppInstallerActivity == null) {
6017            return false;
6018        }
6019        if (intent.getComponent() != null) {
6020            return false;
6021        }
6022        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6023            return false;
6024        }
6025        if (!skipPackageCheck && intent.getPackage() != null) {
6026            return false;
6027        }
6028        final boolean isWebUri = hasWebURI(intent);
6029        if (!isWebUri || intent.getData().getHost() == null) {
6030            return false;
6031        }
6032        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6033        // Or if there's already an ephemeral app installed that handles the action
6034        synchronized (mPackages) {
6035            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6036            for (int n = 0; n < count; n++) {
6037                final ResolveInfo info = resolvedActivities.get(n);
6038                final String packageName = info.activityInfo.packageName;
6039                final PackageSetting ps = mSettings.mPackages.get(packageName);
6040                if (ps != null) {
6041                    // only check domain verification status if the app is not a browser
6042                    if (!info.handleAllWebDataURI) {
6043                        // Try to get the status from User settings first
6044                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6045                        final int status = (int) (packedStatus >> 32);
6046                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6047                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6048                            if (DEBUG_EPHEMERAL) {
6049                                Slog.v(TAG, "DENY instant app;"
6050                                    + " pkg: " + packageName + ", status: " + status);
6051                            }
6052                            return false;
6053                        }
6054                    }
6055                    if (ps.getInstantApp(userId)) {
6056                        if (DEBUG_EPHEMERAL) {
6057                            Slog.v(TAG, "DENY instant app installed;"
6058                                    + " pkg: " + packageName);
6059                        }
6060                        return false;
6061                    }
6062                }
6063            }
6064        }
6065        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6066        return true;
6067    }
6068
6069    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6070            Intent origIntent, String resolvedType, String callingPackage,
6071            Bundle verificationBundle, int userId) {
6072        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6073                new InstantAppRequest(responseObj, origIntent, resolvedType,
6074                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6075        mHandler.sendMessage(msg);
6076    }
6077
6078    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6079            int flags, List<ResolveInfo> query, int userId) {
6080        if (query != null) {
6081            final int N = query.size();
6082            if (N == 1) {
6083                return query.get(0);
6084            } else if (N > 1) {
6085                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6086                // If there is more than one activity with the same priority,
6087                // then let the user decide between them.
6088                ResolveInfo r0 = query.get(0);
6089                ResolveInfo r1 = query.get(1);
6090                if (DEBUG_INTENT_MATCHING || debug) {
6091                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6092                            + r1.activityInfo.name + "=" + r1.priority);
6093                }
6094                // If the first activity has a higher priority, or a different
6095                // default, then it is always desirable to pick it.
6096                if (r0.priority != r1.priority
6097                        || r0.preferredOrder != r1.preferredOrder
6098                        || r0.isDefault != r1.isDefault) {
6099                    return query.get(0);
6100                }
6101                // If we have saved a preference for a preferred activity for
6102                // this Intent, use that.
6103                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6104                        flags, query, r0.priority, true, false, debug, userId);
6105                if (ri != null) {
6106                    return ri;
6107                }
6108                // If we have an ephemeral app, use it
6109                for (int i = 0; i < N; i++) {
6110                    ri = query.get(i);
6111                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6112                        final String packageName = ri.activityInfo.packageName;
6113                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6114                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6115                        final int status = (int)(packedStatus >> 32);
6116                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6117                            return ri;
6118                        }
6119                    }
6120                }
6121                ri = new ResolveInfo(mResolveInfo);
6122                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6123                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6124                // If all of the options come from the same package, show the application's
6125                // label and icon instead of the generic resolver's.
6126                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6127                // and then throw away the ResolveInfo itself, meaning that the caller loses
6128                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6129                // a fallback for this case; we only set the target package's resources on
6130                // the ResolveInfo, not the ActivityInfo.
6131                final String intentPackage = intent.getPackage();
6132                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6133                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6134                    ri.resolvePackageName = intentPackage;
6135                    if (userNeedsBadging(userId)) {
6136                        ri.noResourceId = true;
6137                    } else {
6138                        ri.icon = appi.icon;
6139                    }
6140                    ri.iconResourceId = appi.icon;
6141                    ri.labelRes = appi.labelRes;
6142                }
6143                ri.activityInfo.applicationInfo = new ApplicationInfo(
6144                        ri.activityInfo.applicationInfo);
6145                if (userId != 0) {
6146                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6147                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6148                }
6149                // Make sure that the resolver is displayable in car mode
6150                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6151                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6152                return ri;
6153            }
6154        }
6155        return null;
6156    }
6157
6158    /**
6159     * Return true if the given list is not empty and all of its contents have
6160     * an activityInfo with the given package name.
6161     */
6162    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6163        if (ArrayUtils.isEmpty(list)) {
6164            return false;
6165        }
6166        for (int i = 0, N = list.size(); i < N; i++) {
6167            final ResolveInfo ri = list.get(i);
6168            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6169            if (ai == null || !packageName.equals(ai.packageName)) {
6170                return false;
6171            }
6172        }
6173        return true;
6174    }
6175
6176    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6177            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6178        final int N = query.size();
6179        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6180                .get(userId);
6181        // Get the list of persistent preferred activities that handle the intent
6182        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6183        List<PersistentPreferredActivity> pprefs = ppir != null
6184                ? ppir.queryIntent(intent, resolvedType,
6185                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6186                        userId)
6187                : null;
6188        if (pprefs != null && pprefs.size() > 0) {
6189            final int M = pprefs.size();
6190            for (int i=0; i<M; i++) {
6191                final PersistentPreferredActivity ppa = pprefs.get(i);
6192                if (DEBUG_PREFERRED || debug) {
6193                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6194                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6195                            + "\n  component=" + ppa.mComponent);
6196                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6197                }
6198                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6199                        flags | MATCH_DISABLED_COMPONENTS, userId);
6200                if (DEBUG_PREFERRED || debug) {
6201                    Slog.v(TAG, "Found persistent preferred activity:");
6202                    if (ai != null) {
6203                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6204                    } else {
6205                        Slog.v(TAG, "  null");
6206                    }
6207                }
6208                if (ai == null) {
6209                    // This previously registered persistent preferred activity
6210                    // component is no longer known. Ignore it and do NOT remove it.
6211                    continue;
6212                }
6213                for (int j=0; j<N; j++) {
6214                    final ResolveInfo ri = query.get(j);
6215                    if (!ri.activityInfo.applicationInfo.packageName
6216                            .equals(ai.applicationInfo.packageName)) {
6217                        continue;
6218                    }
6219                    if (!ri.activityInfo.name.equals(ai.name)) {
6220                        continue;
6221                    }
6222                    //  Found a persistent preference that can handle the intent.
6223                    if (DEBUG_PREFERRED || debug) {
6224                        Slog.v(TAG, "Returning persistent preferred activity: " +
6225                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6226                    }
6227                    return ri;
6228                }
6229            }
6230        }
6231        return null;
6232    }
6233
6234    // TODO: handle preferred activities missing while user has amnesia
6235    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6236            List<ResolveInfo> query, int priority, boolean always,
6237            boolean removeMatches, boolean debug, int userId) {
6238        if (!sUserManager.exists(userId)) return null;
6239        final int callingUid = Binder.getCallingUid();
6240        flags = updateFlagsForResolve(
6241                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6242        intent = updateIntentForResolve(intent);
6243        // writer
6244        synchronized (mPackages) {
6245            // Try to find a matching persistent preferred activity.
6246            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6247                    debug, userId);
6248
6249            // If a persistent preferred activity matched, use it.
6250            if (pri != null) {
6251                return pri;
6252            }
6253
6254            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6255            // Get the list of preferred activities that handle the intent
6256            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6257            List<PreferredActivity> prefs = pir != null
6258                    ? pir.queryIntent(intent, resolvedType,
6259                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6260                            userId)
6261                    : null;
6262            if (prefs != null && prefs.size() > 0) {
6263                boolean changed = false;
6264                try {
6265                    // First figure out how good the original match set is.
6266                    // We will only allow preferred activities that came
6267                    // from the same match quality.
6268                    int match = 0;
6269
6270                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6271
6272                    final int N = query.size();
6273                    for (int j=0; j<N; j++) {
6274                        final ResolveInfo ri = query.get(j);
6275                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6276                                + ": 0x" + Integer.toHexString(match));
6277                        if (ri.match > match) {
6278                            match = ri.match;
6279                        }
6280                    }
6281
6282                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6283                            + Integer.toHexString(match));
6284
6285                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6286                    final int M = prefs.size();
6287                    for (int i=0; i<M; i++) {
6288                        final PreferredActivity pa = prefs.get(i);
6289                        if (DEBUG_PREFERRED || debug) {
6290                            Slog.v(TAG, "Checking PreferredActivity ds="
6291                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6292                                    + "\n  component=" + pa.mPref.mComponent);
6293                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6294                        }
6295                        if (pa.mPref.mMatch != match) {
6296                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6297                                    + Integer.toHexString(pa.mPref.mMatch));
6298                            continue;
6299                        }
6300                        // If it's not an "always" type preferred activity and that's what we're
6301                        // looking for, skip it.
6302                        if (always && !pa.mPref.mAlways) {
6303                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6304                            continue;
6305                        }
6306                        final ActivityInfo ai = getActivityInfo(
6307                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6308                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6309                                userId);
6310                        if (DEBUG_PREFERRED || debug) {
6311                            Slog.v(TAG, "Found preferred activity:");
6312                            if (ai != null) {
6313                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6314                            } else {
6315                                Slog.v(TAG, "  null");
6316                            }
6317                        }
6318                        if (ai == null) {
6319                            // This previously registered preferred activity
6320                            // component is no longer known.  Most likely an update
6321                            // to the app was installed and in the new version this
6322                            // component no longer exists.  Clean it up by removing
6323                            // it from the preferred activities list, and skip it.
6324                            Slog.w(TAG, "Removing dangling preferred activity: "
6325                                    + pa.mPref.mComponent);
6326                            pir.removeFilter(pa);
6327                            changed = true;
6328                            continue;
6329                        }
6330                        for (int j=0; j<N; j++) {
6331                            final ResolveInfo ri = query.get(j);
6332                            if (!ri.activityInfo.applicationInfo.packageName
6333                                    .equals(ai.applicationInfo.packageName)) {
6334                                continue;
6335                            }
6336                            if (!ri.activityInfo.name.equals(ai.name)) {
6337                                continue;
6338                            }
6339
6340                            if (removeMatches) {
6341                                pir.removeFilter(pa);
6342                                changed = true;
6343                                if (DEBUG_PREFERRED) {
6344                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6345                                }
6346                                break;
6347                            }
6348
6349                            // Okay we found a previously set preferred or last chosen app.
6350                            // If the result set is different from when this
6351                            // was created, and is not a subset of the preferred set, we need to
6352                            // clear it and re-ask the user their preference, if we're looking for
6353                            // an "always" type entry.
6354                            if (always && !pa.mPref.sameSet(query)) {
6355                                if (pa.mPref.isSuperset(query)) {
6356                                    // some components of the set are no longer present in
6357                                    // the query, but the preferred activity can still be reused
6358                                    if (DEBUG_PREFERRED) {
6359                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6360                                                + " still valid as only non-preferred components"
6361                                                + " were removed for " + intent + " type "
6362                                                + resolvedType);
6363                                    }
6364                                    // remove obsolete components and re-add the up-to-date filter
6365                                    PreferredActivity freshPa = new PreferredActivity(pa,
6366                                            pa.mPref.mMatch,
6367                                            pa.mPref.discardObsoleteComponents(query),
6368                                            pa.mPref.mComponent,
6369                                            pa.mPref.mAlways);
6370                                    pir.removeFilter(pa);
6371                                    pir.addFilter(freshPa);
6372                                    changed = true;
6373                                } else {
6374                                    Slog.i(TAG,
6375                                            "Result set changed, dropping preferred activity for "
6376                                                    + intent + " type " + resolvedType);
6377                                    if (DEBUG_PREFERRED) {
6378                                        Slog.v(TAG, "Removing preferred activity since set changed "
6379                                                + pa.mPref.mComponent);
6380                                    }
6381                                    pir.removeFilter(pa);
6382                                    // Re-add the filter as a "last chosen" entry (!always)
6383                                    PreferredActivity lastChosen = new PreferredActivity(
6384                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6385                                    pir.addFilter(lastChosen);
6386                                    changed = true;
6387                                    return null;
6388                                }
6389                            }
6390
6391                            // Yay! Either the set matched or we're looking for the last chosen
6392                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6393                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6394                            return ri;
6395                        }
6396                    }
6397                } finally {
6398                    if (changed) {
6399                        if (DEBUG_PREFERRED) {
6400                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6401                        }
6402                        scheduleWritePackageRestrictionsLocked(userId);
6403                    }
6404                }
6405            }
6406        }
6407        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6408        return null;
6409    }
6410
6411    /*
6412     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6413     */
6414    @Override
6415    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6416            int targetUserId) {
6417        mContext.enforceCallingOrSelfPermission(
6418                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6419        List<CrossProfileIntentFilter> matches =
6420                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6421        if (matches != null) {
6422            int size = matches.size();
6423            for (int i = 0; i < size; i++) {
6424                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6425            }
6426        }
6427        if (hasWebURI(intent)) {
6428            // cross-profile app linking works only towards the parent.
6429            final int callingUid = Binder.getCallingUid();
6430            final UserInfo parent = getProfileParent(sourceUserId);
6431            synchronized(mPackages) {
6432                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6433                        false /*includeInstantApps*/);
6434                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6435                        intent, resolvedType, flags, sourceUserId, parent.id);
6436                return xpDomainInfo != null;
6437            }
6438        }
6439        return false;
6440    }
6441
6442    private UserInfo getProfileParent(int userId) {
6443        final long identity = Binder.clearCallingIdentity();
6444        try {
6445            return sUserManager.getProfileParent(userId);
6446        } finally {
6447            Binder.restoreCallingIdentity(identity);
6448        }
6449    }
6450
6451    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6452            String resolvedType, int userId) {
6453        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6454        if (resolver != null) {
6455            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6456        }
6457        return null;
6458    }
6459
6460    @Override
6461    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6462            String resolvedType, int flags, int userId) {
6463        try {
6464            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6465
6466            return new ParceledListSlice<>(
6467                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6468        } finally {
6469            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6470        }
6471    }
6472
6473    /**
6474     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6475     * instant, returns {@code null}.
6476     */
6477    private String getInstantAppPackageName(int callingUid) {
6478        synchronized (mPackages) {
6479            // If the caller is an isolated app use the owner's uid for the lookup.
6480            if (Process.isIsolated(callingUid)) {
6481                callingUid = mIsolatedOwners.get(callingUid);
6482            }
6483            final int appId = UserHandle.getAppId(callingUid);
6484            final Object obj = mSettings.getUserIdLPr(appId);
6485            if (obj instanceof PackageSetting) {
6486                final PackageSetting ps = (PackageSetting) obj;
6487                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6488                return isInstantApp ? ps.pkg.packageName : null;
6489            }
6490        }
6491        return null;
6492    }
6493
6494    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6495            String resolvedType, int flags, int userId) {
6496        return queryIntentActivitiesInternal(
6497                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6498                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6499    }
6500
6501    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6502            String resolvedType, int flags, int filterCallingUid, int userId,
6503            boolean resolveForStart, boolean allowDynamicSplits) {
6504        if (!sUserManager.exists(userId)) return Collections.emptyList();
6505        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6506        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6507                false /* requireFullPermission */, false /* checkShell */,
6508                "query intent activities");
6509        final String pkgName = intent.getPackage();
6510        ComponentName comp = intent.getComponent();
6511        if (comp == null) {
6512            if (intent.getSelector() != null) {
6513                intent = intent.getSelector();
6514                comp = intent.getComponent();
6515            }
6516        }
6517
6518        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6519                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6520        if (comp != null) {
6521            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6522            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6523            if (ai != null) {
6524                // When specifying an explicit component, we prevent the activity from being
6525                // used when either 1) the calling package is normal and the activity is within
6526                // an ephemeral application or 2) the calling package is ephemeral and the
6527                // activity is not visible to ephemeral applications.
6528                final boolean matchInstantApp =
6529                        (flags & PackageManager.MATCH_INSTANT) != 0;
6530                final boolean matchVisibleToInstantAppOnly =
6531                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6532                final boolean matchExplicitlyVisibleOnly =
6533                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6534                final boolean isCallerInstantApp =
6535                        instantAppPkgName != null;
6536                final boolean isTargetSameInstantApp =
6537                        comp.getPackageName().equals(instantAppPkgName);
6538                final boolean isTargetInstantApp =
6539                        (ai.applicationInfo.privateFlags
6540                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6541                final boolean isTargetVisibleToInstantApp =
6542                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6543                final boolean isTargetExplicitlyVisibleToInstantApp =
6544                        isTargetVisibleToInstantApp
6545                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6546                final boolean isTargetHiddenFromInstantApp =
6547                        !isTargetVisibleToInstantApp
6548                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6549                final boolean blockResolution =
6550                        !isTargetSameInstantApp
6551                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6552                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6553                                        && isTargetHiddenFromInstantApp));
6554                if (!blockResolution) {
6555                    final ResolveInfo ri = new ResolveInfo();
6556                    ri.activityInfo = ai;
6557                    list.add(ri);
6558                }
6559            }
6560            return applyPostResolutionFilter(
6561                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6562        }
6563
6564        // reader
6565        boolean sortResult = false;
6566        boolean addEphemeral = false;
6567        List<ResolveInfo> result;
6568        final boolean ephemeralDisabled = isEphemeralDisabled();
6569        synchronized (mPackages) {
6570            if (pkgName == null) {
6571                List<CrossProfileIntentFilter> matchingFilters =
6572                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6573                // Check for results that need to skip the current profile.
6574                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6575                        resolvedType, flags, userId);
6576                if (xpResolveInfo != null) {
6577                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6578                    xpResult.add(xpResolveInfo);
6579                    return applyPostResolutionFilter(
6580                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6581                            allowDynamicSplits, filterCallingUid, userId);
6582                }
6583
6584                // Check for results in the current profile.
6585                result = filterIfNotSystemUser(mActivities.queryIntent(
6586                        intent, resolvedType, flags, userId), userId);
6587                addEphemeral = !ephemeralDisabled
6588                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6589                // Check for cross profile results.
6590                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6591                xpResolveInfo = queryCrossProfileIntents(
6592                        matchingFilters, intent, resolvedType, flags, userId,
6593                        hasNonNegativePriorityResult);
6594                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6595                    boolean isVisibleToUser = filterIfNotSystemUser(
6596                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6597                    if (isVisibleToUser) {
6598                        result.add(xpResolveInfo);
6599                        sortResult = true;
6600                    }
6601                }
6602                if (hasWebURI(intent)) {
6603                    CrossProfileDomainInfo xpDomainInfo = null;
6604                    final UserInfo parent = getProfileParent(userId);
6605                    if (parent != null) {
6606                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6607                                flags, userId, parent.id);
6608                    }
6609                    if (xpDomainInfo != null) {
6610                        if (xpResolveInfo != null) {
6611                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6612                            // in the result.
6613                            result.remove(xpResolveInfo);
6614                        }
6615                        if (result.size() == 0 && !addEphemeral) {
6616                            // No result in current profile, but found candidate in parent user.
6617                            // And we are not going to add emphemeral app, so we can return the
6618                            // result straight away.
6619                            result.add(xpDomainInfo.resolveInfo);
6620                            return applyPostResolutionFilter(result, instantAppPkgName,
6621                                    allowDynamicSplits, filterCallingUid, userId);
6622                        }
6623                    } else if (result.size() <= 1 && !addEphemeral) {
6624                        // No result in parent user and <= 1 result in current profile, and we
6625                        // are not going to add emphemeral app, so we can return the result without
6626                        // further processing.
6627                        return applyPostResolutionFilter(result, instantAppPkgName,
6628                                allowDynamicSplits, filterCallingUid, userId);
6629                    }
6630                    // We have more than one candidate (combining results from current and parent
6631                    // profile), so we need filtering and sorting.
6632                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6633                            intent, flags, result, xpDomainInfo, userId);
6634                    sortResult = true;
6635                }
6636            } else {
6637                final PackageParser.Package pkg = mPackages.get(pkgName);
6638                result = null;
6639                if (pkg != null) {
6640                    result = filterIfNotSystemUser(
6641                            mActivities.queryIntentForPackage(
6642                                    intent, resolvedType, flags, pkg.activities, userId),
6643                            userId);
6644                }
6645                if (result == null || result.size() == 0) {
6646                    // the caller wants to resolve for a particular package; however, there
6647                    // were no installed results, so, try to find an ephemeral result
6648                    addEphemeral = !ephemeralDisabled
6649                            && isInstantAppAllowed(
6650                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6651                    if (result == null) {
6652                        result = new ArrayList<>();
6653                    }
6654                }
6655            }
6656        }
6657        if (addEphemeral) {
6658            result = maybeAddInstantAppInstaller(
6659                    result, intent, resolvedType, flags, userId, resolveForStart);
6660        }
6661        if (sortResult) {
6662            Collections.sort(result, mResolvePrioritySorter);
6663        }
6664        return applyPostResolutionFilter(
6665                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6666    }
6667
6668    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6669            String resolvedType, int flags, int userId, boolean resolveForStart) {
6670        // first, check to see if we've got an instant app already installed
6671        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6672        ResolveInfo localInstantApp = null;
6673        boolean blockResolution = false;
6674        if (!alreadyResolvedLocally) {
6675            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6676                    flags
6677                        | PackageManager.GET_RESOLVED_FILTER
6678                        | PackageManager.MATCH_INSTANT
6679                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6680                    userId);
6681            for (int i = instantApps.size() - 1; i >= 0; --i) {
6682                final ResolveInfo info = instantApps.get(i);
6683                final String packageName = info.activityInfo.packageName;
6684                final PackageSetting ps = mSettings.mPackages.get(packageName);
6685                if (ps.getInstantApp(userId)) {
6686                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6687                    final int status = (int)(packedStatus >> 32);
6688                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6689                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6690                        // there's a local instant application installed, but, the user has
6691                        // chosen to never use it; skip resolution and don't acknowledge
6692                        // an instant application is even available
6693                        if (DEBUG_EPHEMERAL) {
6694                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6695                        }
6696                        blockResolution = true;
6697                        break;
6698                    } else {
6699                        // we have a locally installed instant application; skip resolution
6700                        // but acknowledge there's an instant application available
6701                        if (DEBUG_EPHEMERAL) {
6702                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6703                        }
6704                        localInstantApp = info;
6705                        break;
6706                    }
6707                }
6708            }
6709        }
6710        // no app installed, let's see if one's available
6711        AuxiliaryResolveInfo auxiliaryResponse = null;
6712        if (!blockResolution) {
6713            if (localInstantApp == null) {
6714                // we don't have an instant app locally, resolve externally
6715                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6716                final InstantAppRequest requestObject = new InstantAppRequest(
6717                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6718                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6719                        resolveForStart);
6720                auxiliaryResponse =
6721                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6722                                mContext, mInstantAppResolverConnection, requestObject);
6723                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6724            } else {
6725                // we have an instant application locally, but, we can't admit that since
6726                // callers shouldn't be able to determine prior browsing. create a dummy
6727                // auxiliary response so the downstream code behaves as if there's an
6728                // instant application available externally. when it comes time to start
6729                // the instant application, we'll do the right thing.
6730                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6731                auxiliaryResponse = new AuxiliaryResolveInfo(
6732                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6733                        ai.versionCode, null /*failureIntent*/);
6734            }
6735        }
6736        if (auxiliaryResponse != null) {
6737            if (DEBUG_EPHEMERAL) {
6738                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6739            }
6740            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6741            final PackageSetting ps =
6742                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6743            if (ps != null) {
6744                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6745                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6746                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6747                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6748                // make sure this resolver is the default
6749                ephemeralInstaller.isDefault = true;
6750                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6751                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6752                // add a non-generic filter
6753                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6754                ephemeralInstaller.filter.addDataPath(
6755                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6756                ephemeralInstaller.isInstantAppAvailable = true;
6757                result.add(ephemeralInstaller);
6758            }
6759        }
6760        return result;
6761    }
6762
6763    private static class CrossProfileDomainInfo {
6764        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6765        ResolveInfo resolveInfo;
6766        /* Best domain verification status of the activities found in the other profile */
6767        int bestDomainVerificationStatus;
6768    }
6769
6770    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6771            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6772        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6773                sourceUserId)) {
6774            return null;
6775        }
6776        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6777                resolvedType, flags, parentUserId);
6778
6779        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6780            return null;
6781        }
6782        CrossProfileDomainInfo result = null;
6783        int size = resultTargetUser.size();
6784        for (int i = 0; i < size; i++) {
6785            ResolveInfo riTargetUser = resultTargetUser.get(i);
6786            // Intent filter verification is only for filters that specify a host. So don't return
6787            // those that handle all web uris.
6788            if (riTargetUser.handleAllWebDataURI) {
6789                continue;
6790            }
6791            String packageName = riTargetUser.activityInfo.packageName;
6792            PackageSetting ps = mSettings.mPackages.get(packageName);
6793            if (ps == null) {
6794                continue;
6795            }
6796            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6797            int status = (int)(verificationState >> 32);
6798            if (result == null) {
6799                result = new CrossProfileDomainInfo();
6800                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6801                        sourceUserId, parentUserId);
6802                result.bestDomainVerificationStatus = status;
6803            } else {
6804                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6805                        result.bestDomainVerificationStatus);
6806            }
6807        }
6808        // Don't consider matches with status NEVER across profiles.
6809        if (result != null && result.bestDomainVerificationStatus
6810                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6811            return null;
6812        }
6813        return result;
6814    }
6815
6816    /**
6817     * Verification statuses are ordered from the worse to the best, except for
6818     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6819     */
6820    private int bestDomainVerificationStatus(int status1, int status2) {
6821        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6822            return status2;
6823        }
6824        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6825            return status1;
6826        }
6827        return (int) MathUtils.max(status1, status2);
6828    }
6829
6830    private boolean isUserEnabled(int userId) {
6831        long callingId = Binder.clearCallingIdentity();
6832        try {
6833            UserInfo userInfo = sUserManager.getUserInfo(userId);
6834            return userInfo != null && userInfo.isEnabled();
6835        } finally {
6836            Binder.restoreCallingIdentity(callingId);
6837        }
6838    }
6839
6840    /**
6841     * Filter out activities with systemUserOnly flag set, when current user is not System.
6842     *
6843     * @return filtered list
6844     */
6845    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6846        if (userId == UserHandle.USER_SYSTEM) {
6847            return resolveInfos;
6848        }
6849        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6850            ResolveInfo info = resolveInfos.get(i);
6851            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6852                resolveInfos.remove(i);
6853            }
6854        }
6855        return resolveInfos;
6856    }
6857
6858    /**
6859     * Filters out ephemeral activities.
6860     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6861     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6862     *
6863     * @param resolveInfos The pre-filtered list of resolved activities
6864     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6865     *          is performed.
6866     * @return A filtered list of resolved activities.
6867     */
6868    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6869            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6870        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6871            final ResolveInfo info = resolveInfos.get(i);
6872            // allow activities that are defined in the provided package
6873            if (allowDynamicSplits
6874                    && info.activityInfo.splitName != null
6875                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6876                            info.activityInfo.splitName)) {
6877                if (mInstantAppInstallerInfo == null) {
6878                    if (DEBUG_INSTALL) {
6879                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6880                    }
6881                    resolveInfos.remove(i);
6882                    continue;
6883                }
6884                // requested activity is defined in a split that hasn't been installed yet.
6885                // add the installer to the resolve list
6886                if (DEBUG_INSTALL) {
6887                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6888                }
6889                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6890                final ComponentName installFailureActivity = findInstallFailureActivity(
6891                        info.activityInfo.packageName,  filterCallingUid, userId);
6892                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6893                        info.activityInfo.packageName, info.activityInfo.splitName,
6894                        installFailureActivity,
6895                        info.activityInfo.applicationInfo.versionCode,
6896                        null /*failureIntent*/);
6897                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6898                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6899                // add a non-generic filter
6900                installerInfo.filter = new IntentFilter();
6901
6902                // This resolve info may appear in the chooser UI, so let us make it
6903                // look as the one it replaces as far as the user is concerned which
6904                // requires loading the correct label and icon for the resolve info.
6905                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6906                installerInfo.labelRes = info.resolveLabelResId();
6907                installerInfo.icon = info.resolveIconResId();
6908
6909                // propagate priority/preferred order/default
6910                installerInfo.priority = info.priority;
6911                installerInfo.preferredOrder = info.preferredOrder;
6912                installerInfo.isDefault = info.isDefault;
6913                resolveInfos.set(i, installerInfo);
6914                continue;
6915            }
6916            // caller is a full app, don't need to apply any other filtering
6917            if (ephemeralPkgName == null) {
6918                continue;
6919            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6920                // caller is same app; don't need to apply any other filtering
6921                continue;
6922            }
6923            // allow activities that have been explicitly exposed to ephemeral apps
6924            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6925            if (!isEphemeralApp
6926                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6927                continue;
6928            }
6929            resolveInfos.remove(i);
6930        }
6931        return resolveInfos;
6932    }
6933
6934    /**
6935     * Returns the activity component that can handle install failures.
6936     * <p>By default, the instant application installer handles failures. However, an
6937     * application may want to handle failures on its own. Applications do this by
6938     * creating an activity with an intent filter that handles the action
6939     * {@link Intent#ACTION_INSTALL_FAILURE}.
6940     */
6941    private @Nullable ComponentName findInstallFailureActivity(
6942            String packageName, int filterCallingUid, int userId) {
6943        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6944        failureActivityIntent.setPackage(packageName);
6945        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6946        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6947                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6948                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6949        final int NR = result.size();
6950        if (NR > 0) {
6951            for (int i = 0; i < NR; i++) {
6952                final ResolveInfo info = result.get(i);
6953                if (info.activityInfo.splitName != null) {
6954                    continue;
6955                }
6956                return new ComponentName(packageName, info.activityInfo.name);
6957            }
6958        }
6959        return null;
6960    }
6961
6962    /**
6963     * @param resolveInfos list of resolve infos in descending priority order
6964     * @return if the list contains a resolve info with non-negative priority
6965     */
6966    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6967        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6968    }
6969
6970    private static boolean hasWebURI(Intent intent) {
6971        if (intent.getData() == null) {
6972            return false;
6973        }
6974        final String scheme = intent.getScheme();
6975        if (TextUtils.isEmpty(scheme)) {
6976            return false;
6977        }
6978        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6979    }
6980
6981    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6982            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6983            int userId) {
6984        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6985
6986        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6987            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6988                    candidates.size());
6989        }
6990
6991        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6992        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6993        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6994        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6995        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6996        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6997
6998        synchronized (mPackages) {
6999            final int count = candidates.size();
7000            // First, try to use linked apps. Partition the candidates into four lists:
7001            // one for the final results, one for the "do not use ever", one for "undefined status"
7002            // and finally one for "browser app type".
7003            for (int n=0; n<count; n++) {
7004                ResolveInfo info = candidates.get(n);
7005                String packageName = info.activityInfo.packageName;
7006                PackageSetting ps = mSettings.mPackages.get(packageName);
7007                if (ps != null) {
7008                    // Add to the special match all list (Browser use case)
7009                    if (info.handleAllWebDataURI) {
7010                        matchAllList.add(info);
7011                        continue;
7012                    }
7013                    // Try to get the status from User settings first
7014                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7015                    int status = (int)(packedStatus >> 32);
7016                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7017                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7018                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7019                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7020                                    + " : linkgen=" + linkGeneration);
7021                        }
7022                        // Use link-enabled generation as preferredOrder, i.e.
7023                        // prefer newly-enabled over earlier-enabled.
7024                        info.preferredOrder = linkGeneration;
7025                        alwaysList.add(info);
7026                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7027                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7028                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7029                        }
7030                        neverList.add(info);
7031                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7032                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7033                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7034                        }
7035                        alwaysAskList.add(info);
7036                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7037                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7038                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7039                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7040                        }
7041                        undefinedList.add(info);
7042                    }
7043                }
7044            }
7045
7046            // We'll want to include browser possibilities in a few cases
7047            boolean includeBrowser = false;
7048
7049            // First try to add the "always" resolution(s) for the current user, if any
7050            if (alwaysList.size() > 0) {
7051                result.addAll(alwaysList);
7052            } else {
7053                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7054                result.addAll(undefinedList);
7055                // Maybe add one for the other profile.
7056                if (xpDomainInfo != null && (
7057                        xpDomainInfo.bestDomainVerificationStatus
7058                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7059                    result.add(xpDomainInfo.resolveInfo);
7060                }
7061                includeBrowser = true;
7062            }
7063
7064            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7065            // If there were 'always' entries their preferred order has been set, so we also
7066            // back that off to make the alternatives equivalent
7067            if (alwaysAskList.size() > 0) {
7068                for (ResolveInfo i : result) {
7069                    i.preferredOrder = 0;
7070                }
7071                result.addAll(alwaysAskList);
7072                includeBrowser = true;
7073            }
7074
7075            if (includeBrowser) {
7076                // Also add browsers (all of them or only the default one)
7077                if (DEBUG_DOMAIN_VERIFICATION) {
7078                    Slog.v(TAG, "   ...including browsers in candidate set");
7079                }
7080                if ((matchFlags & MATCH_ALL) != 0) {
7081                    result.addAll(matchAllList);
7082                } else {
7083                    // Browser/generic handling case.  If there's a default browser, go straight
7084                    // to that (but only if there is no other higher-priority match).
7085                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7086                    int maxMatchPrio = 0;
7087                    ResolveInfo defaultBrowserMatch = null;
7088                    final int numCandidates = matchAllList.size();
7089                    for (int n = 0; n < numCandidates; n++) {
7090                        ResolveInfo info = matchAllList.get(n);
7091                        // track the highest overall match priority...
7092                        if (info.priority > maxMatchPrio) {
7093                            maxMatchPrio = info.priority;
7094                        }
7095                        // ...and the highest-priority default browser match
7096                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7097                            if (defaultBrowserMatch == null
7098                                    || (defaultBrowserMatch.priority < info.priority)) {
7099                                if (debug) {
7100                                    Slog.v(TAG, "Considering default browser match " + info);
7101                                }
7102                                defaultBrowserMatch = info;
7103                            }
7104                        }
7105                    }
7106                    if (defaultBrowserMatch != null
7107                            && defaultBrowserMatch.priority >= maxMatchPrio
7108                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7109                    {
7110                        if (debug) {
7111                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7112                        }
7113                        result.add(defaultBrowserMatch);
7114                    } else {
7115                        result.addAll(matchAllList);
7116                    }
7117                }
7118
7119                // If there is nothing selected, add all candidates and remove the ones that the user
7120                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7121                if (result.size() == 0) {
7122                    result.addAll(candidates);
7123                    result.removeAll(neverList);
7124                }
7125            }
7126        }
7127        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7128            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7129                    result.size());
7130            for (ResolveInfo info : result) {
7131                Slog.v(TAG, "  + " + info.activityInfo);
7132            }
7133        }
7134        return result;
7135    }
7136
7137    // Returns a packed value as a long:
7138    //
7139    // high 'int'-sized word: link status: undefined/ask/never/always.
7140    // low 'int'-sized word: relative priority among 'always' results.
7141    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7142        long result = ps.getDomainVerificationStatusForUser(userId);
7143        // if none available, get the master status
7144        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7145            if (ps.getIntentFilterVerificationInfo() != null) {
7146                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7147            }
7148        }
7149        return result;
7150    }
7151
7152    private ResolveInfo querySkipCurrentProfileIntents(
7153            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7154            int flags, int sourceUserId) {
7155        if (matchingFilters != null) {
7156            int size = matchingFilters.size();
7157            for (int i = 0; i < size; i ++) {
7158                CrossProfileIntentFilter filter = matchingFilters.get(i);
7159                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7160                    // Checking if there are activities in the target user that can handle the
7161                    // intent.
7162                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7163                            resolvedType, flags, sourceUserId);
7164                    if (resolveInfo != null) {
7165                        return resolveInfo;
7166                    }
7167                }
7168            }
7169        }
7170        return null;
7171    }
7172
7173    // Return matching ResolveInfo in target user if any.
7174    private ResolveInfo queryCrossProfileIntents(
7175            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7176            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7177        if (matchingFilters != null) {
7178            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7179            // match the same intent. For performance reasons, it is better not to
7180            // run queryIntent twice for the same userId
7181            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7182            int size = matchingFilters.size();
7183            for (int i = 0; i < size; i++) {
7184                CrossProfileIntentFilter filter = matchingFilters.get(i);
7185                int targetUserId = filter.getTargetUserId();
7186                boolean skipCurrentProfile =
7187                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7188                boolean skipCurrentProfileIfNoMatchFound =
7189                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7190                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7191                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7192                    // Checking if there are activities in the target user that can handle the
7193                    // intent.
7194                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7195                            resolvedType, flags, sourceUserId);
7196                    if (resolveInfo != null) return resolveInfo;
7197                    alreadyTriedUserIds.put(targetUserId, true);
7198                }
7199            }
7200        }
7201        return null;
7202    }
7203
7204    /**
7205     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7206     * will forward the intent to the filter's target user.
7207     * Otherwise, returns null.
7208     */
7209    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7210            String resolvedType, int flags, int sourceUserId) {
7211        int targetUserId = filter.getTargetUserId();
7212        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7213                resolvedType, flags, targetUserId);
7214        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7215            // If all the matches in the target profile are suspended, return null.
7216            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7217                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7218                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7219                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7220                            targetUserId);
7221                }
7222            }
7223        }
7224        return null;
7225    }
7226
7227    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7228            int sourceUserId, int targetUserId) {
7229        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7230        long ident = Binder.clearCallingIdentity();
7231        boolean targetIsProfile;
7232        try {
7233            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7234        } finally {
7235            Binder.restoreCallingIdentity(ident);
7236        }
7237        String className;
7238        if (targetIsProfile) {
7239            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7240        } else {
7241            className = FORWARD_INTENT_TO_PARENT;
7242        }
7243        ComponentName forwardingActivityComponentName = new ComponentName(
7244                mAndroidApplication.packageName, className);
7245        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7246                sourceUserId);
7247        if (!targetIsProfile) {
7248            forwardingActivityInfo.showUserIcon = targetUserId;
7249            forwardingResolveInfo.noResourceId = true;
7250        }
7251        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7252        forwardingResolveInfo.priority = 0;
7253        forwardingResolveInfo.preferredOrder = 0;
7254        forwardingResolveInfo.match = 0;
7255        forwardingResolveInfo.isDefault = true;
7256        forwardingResolveInfo.filter = filter;
7257        forwardingResolveInfo.targetUserId = targetUserId;
7258        return forwardingResolveInfo;
7259    }
7260
7261    @Override
7262    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7263            Intent[] specifics, String[] specificTypes, Intent intent,
7264            String resolvedType, int flags, int userId) {
7265        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7266                specificTypes, intent, resolvedType, flags, userId));
7267    }
7268
7269    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7270            Intent[] specifics, String[] specificTypes, Intent intent,
7271            String resolvedType, int flags, int userId) {
7272        if (!sUserManager.exists(userId)) return Collections.emptyList();
7273        final int callingUid = Binder.getCallingUid();
7274        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7275                false /*includeInstantApps*/);
7276        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7277                false /*requireFullPermission*/, false /*checkShell*/,
7278                "query intent activity options");
7279        final String resultsAction = intent.getAction();
7280
7281        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7282                | PackageManager.GET_RESOLVED_FILTER, userId);
7283
7284        if (DEBUG_INTENT_MATCHING) {
7285            Log.v(TAG, "Query " + intent + ": " + results);
7286        }
7287
7288        int specificsPos = 0;
7289        int N;
7290
7291        // todo: note that the algorithm used here is O(N^2).  This
7292        // isn't a problem in our current environment, but if we start running
7293        // into situations where we have more than 5 or 10 matches then this
7294        // should probably be changed to something smarter...
7295
7296        // First we go through and resolve each of the specific items
7297        // that were supplied, taking care of removing any corresponding
7298        // duplicate items in the generic resolve list.
7299        if (specifics != null) {
7300            for (int i=0; i<specifics.length; i++) {
7301                final Intent sintent = specifics[i];
7302                if (sintent == null) {
7303                    continue;
7304                }
7305
7306                if (DEBUG_INTENT_MATCHING) {
7307                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7308                }
7309
7310                String action = sintent.getAction();
7311                if (resultsAction != null && resultsAction.equals(action)) {
7312                    // If this action was explicitly requested, then don't
7313                    // remove things that have it.
7314                    action = null;
7315                }
7316
7317                ResolveInfo ri = null;
7318                ActivityInfo ai = null;
7319
7320                ComponentName comp = sintent.getComponent();
7321                if (comp == null) {
7322                    ri = resolveIntent(
7323                        sintent,
7324                        specificTypes != null ? specificTypes[i] : null,
7325                            flags, userId);
7326                    if (ri == null) {
7327                        continue;
7328                    }
7329                    if (ri == mResolveInfo) {
7330                        // ACK!  Must do something better with this.
7331                    }
7332                    ai = ri.activityInfo;
7333                    comp = new ComponentName(ai.applicationInfo.packageName,
7334                            ai.name);
7335                } else {
7336                    ai = getActivityInfo(comp, flags, userId);
7337                    if (ai == null) {
7338                        continue;
7339                    }
7340                }
7341
7342                // Look for any generic query activities that are duplicates
7343                // of this specific one, and remove them from the results.
7344                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7345                N = results.size();
7346                int j;
7347                for (j=specificsPos; j<N; j++) {
7348                    ResolveInfo sri = results.get(j);
7349                    if ((sri.activityInfo.name.equals(comp.getClassName())
7350                            && sri.activityInfo.applicationInfo.packageName.equals(
7351                                    comp.getPackageName()))
7352                        || (action != null && sri.filter.matchAction(action))) {
7353                        results.remove(j);
7354                        if (DEBUG_INTENT_MATCHING) Log.v(
7355                            TAG, "Removing duplicate item from " + j
7356                            + " due to specific " + specificsPos);
7357                        if (ri == null) {
7358                            ri = sri;
7359                        }
7360                        j--;
7361                        N--;
7362                    }
7363                }
7364
7365                // Add this specific item to its proper place.
7366                if (ri == null) {
7367                    ri = new ResolveInfo();
7368                    ri.activityInfo = ai;
7369                }
7370                results.add(specificsPos, ri);
7371                ri.specificIndex = i;
7372                specificsPos++;
7373            }
7374        }
7375
7376        // Now we go through the remaining generic results and remove any
7377        // duplicate actions that are found here.
7378        N = results.size();
7379        for (int i=specificsPos; i<N-1; i++) {
7380            final ResolveInfo rii = results.get(i);
7381            if (rii.filter == null) {
7382                continue;
7383            }
7384
7385            // Iterate over all of the actions of this result's intent
7386            // filter...  typically this should be just one.
7387            final Iterator<String> it = rii.filter.actionsIterator();
7388            if (it == null) {
7389                continue;
7390            }
7391            while (it.hasNext()) {
7392                final String action = it.next();
7393                if (resultsAction != null && resultsAction.equals(action)) {
7394                    // If this action was explicitly requested, then don't
7395                    // remove things that have it.
7396                    continue;
7397                }
7398                for (int j=i+1; j<N; j++) {
7399                    final ResolveInfo rij = results.get(j);
7400                    if (rij.filter != null && rij.filter.hasAction(action)) {
7401                        results.remove(j);
7402                        if (DEBUG_INTENT_MATCHING) Log.v(
7403                            TAG, "Removing duplicate item from " + j
7404                            + " due to action " + action + " at " + i);
7405                        j--;
7406                        N--;
7407                    }
7408                }
7409            }
7410
7411            // If the caller didn't request filter information, drop it now
7412            // so we don't have to marshall/unmarshall it.
7413            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7414                rii.filter = null;
7415            }
7416        }
7417
7418        // Filter out the caller activity if so requested.
7419        if (caller != null) {
7420            N = results.size();
7421            for (int i=0; i<N; i++) {
7422                ActivityInfo ainfo = results.get(i).activityInfo;
7423                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7424                        && caller.getClassName().equals(ainfo.name)) {
7425                    results.remove(i);
7426                    break;
7427                }
7428            }
7429        }
7430
7431        // If the caller didn't request filter information,
7432        // drop them now so we don't have to
7433        // marshall/unmarshall it.
7434        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7435            N = results.size();
7436            for (int i=0; i<N; i++) {
7437                results.get(i).filter = null;
7438            }
7439        }
7440
7441        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7442        return results;
7443    }
7444
7445    @Override
7446    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7447            String resolvedType, int flags, int userId) {
7448        return new ParceledListSlice<>(
7449                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7450                        false /*allowDynamicSplits*/));
7451    }
7452
7453    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7454            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7455        if (!sUserManager.exists(userId)) return Collections.emptyList();
7456        final int callingUid = Binder.getCallingUid();
7457        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7458                false /*requireFullPermission*/, false /*checkShell*/,
7459                "query intent receivers");
7460        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7461        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7462                false /*includeInstantApps*/);
7463        ComponentName comp = intent.getComponent();
7464        if (comp == null) {
7465            if (intent.getSelector() != null) {
7466                intent = intent.getSelector();
7467                comp = intent.getComponent();
7468            }
7469        }
7470        if (comp != null) {
7471            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7472            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7473            if (ai != null) {
7474                // When specifying an explicit component, we prevent the activity from being
7475                // used when either 1) the calling package is normal and the activity is within
7476                // an instant application or 2) the calling package is ephemeral and the
7477                // activity is not visible to instant applications.
7478                final boolean matchInstantApp =
7479                        (flags & PackageManager.MATCH_INSTANT) != 0;
7480                final boolean matchVisibleToInstantAppOnly =
7481                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7482                final boolean matchExplicitlyVisibleOnly =
7483                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7484                final boolean isCallerInstantApp =
7485                        instantAppPkgName != null;
7486                final boolean isTargetSameInstantApp =
7487                        comp.getPackageName().equals(instantAppPkgName);
7488                final boolean isTargetInstantApp =
7489                        (ai.applicationInfo.privateFlags
7490                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7491                final boolean isTargetVisibleToInstantApp =
7492                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7493                final boolean isTargetExplicitlyVisibleToInstantApp =
7494                        isTargetVisibleToInstantApp
7495                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7496                final boolean isTargetHiddenFromInstantApp =
7497                        !isTargetVisibleToInstantApp
7498                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7499                final boolean blockResolution =
7500                        !isTargetSameInstantApp
7501                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7502                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7503                                        && isTargetHiddenFromInstantApp));
7504                if (!blockResolution) {
7505                    ResolveInfo ri = new ResolveInfo();
7506                    ri.activityInfo = ai;
7507                    list.add(ri);
7508                }
7509            }
7510            return applyPostResolutionFilter(
7511                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7512        }
7513
7514        // reader
7515        synchronized (mPackages) {
7516            String pkgName = intent.getPackage();
7517            if (pkgName == null) {
7518                final List<ResolveInfo> result =
7519                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7520                return applyPostResolutionFilter(
7521                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7522            }
7523            final PackageParser.Package pkg = mPackages.get(pkgName);
7524            if (pkg != null) {
7525                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7526                        intent, resolvedType, flags, pkg.receivers, userId);
7527                return applyPostResolutionFilter(
7528                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7529            }
7530            return Collections.emptyList();
7531        }
7532    }
7533
7534    @Override
7535    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7536        final int callingUid = Binder.getCallingUid();
7537        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7538    }
7539
7540    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7541            int userId, int callingUid) {
7542        if (!sUserManager.exists(userId)) return null;
7543        flags = updateFlagsForResolve(
7544                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7545        List<ResolveInfo> query = queryIntentServicesInternal(
7546                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7547        if (query != null) {
7548            if (query.size() >= 1) {
7549                // If there is more than one service with the same priority,
7550                // just arbitrarily pick the first one.
7551                return query.get(0);
7552            }
7553        }
7554        return null;
7555    }
7556
7557    @Override
7558    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7559            String resolvedType, int flags, int userId) {
7560        final int callingUid = Binder.getCallingUid();
7561        return new ParceledListSlice<>(queryIntentServicesInternal(
7562                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7563    }
7564
7565    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7566            String resolvedType, int flags, int userId, int callingUid,
7567            boolean includeInstantApps) {
7568        if (!sUserManager.exists(userId)) return Collections.emptyList();
7569        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7570                false /*requireFullPermission*/, false /*checkShell*/,
7571                "query intent receivers");
7572        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7573        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7574        ComponentName comp = intent.getComponent();
7575        if (comp == null) {
7576            if (intent.getSelector() != null) {
7577                intent = intent.getSelector();
7578                comp = intent.getComponent();
7579            }
7580        }
7581        if (comp != null) {
7582            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7583            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7584            if (si != null) {
7585                // When specifying an explicit component, we prevent the service from being
7586                // used when either 1) the service is in an instant application and the
7587                // caller is not the same instant application or 2) the calling package is
7588                // ephemeral and the activity is not visible to ephemeral applications.
7589                final boolean matchInstantApp =
7590                        (flags & PackageManager.MATCH_INSTANT) != 0;
7591                final boolean matchVisibleToInstantAppOnly =
7592                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7593                final boolean isCallerInstantApp =
7594                        instantAppPkgName != null;
7595                final boolean isTargetSameInstantApp =
7596                        comp.getPackageName().equals(instantAppPkgName);
7597                final boolean isTargetInstantApp =
7598                        (si.applicationInfo.privateFlags
7599                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7600                final boolean isTargetHiddenFromInstantApp =
7601                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7602                final boolean blockResolution =
7603                        !isTargetSameInstantApp
7604                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7605                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7606                                        && isTargetHiddenFromInstantApp));
7607                if (!blockResolution) {
7608                    final ResolveInfo ri = new ResolveInfo();
7609                    ri.serviceInfo = si;
7610                    list.add(ri);
7611                }
7612            }
7613            return list;
7614        }
7615
7616        // reader
7617        synchronized (mPackages) {
7618            String pkgName = intent.getPackage();
7619            if (pkgName == null) {
7620                return applyPostServiceResolutionFilter(
7621                        mServices.queryIntent(intent, resolvedType, flags, userId),
7622                        instantAppPkgName);
7623            }
7624            final PackageParser.Package pkg = mPackages.get(pkgName);
7625            if (pkg != null) {
7626                return applyPostServiceResolutionFilter(
7627                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7628                                userId),
7629                        instantAppPkgName);
7630            }
7631            return Collections.emptyList();
7632        }
7633    }
7634
7635    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7636            String instantAppPkgName) {
7637        if (instantAppPkgName == null) {
7638            return resolveInfos;
7639        }
7640        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7641            final ResolveInfo info = resolveInfos.get(i);
7642            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7643            // allow services that are defined in the provided package
7644            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7645                if (info.serviceInfo.splitName != null
7646                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7647                                info.serviceInfo.splitName)) {
7648                    // requested service is defined in a split that hasn't been installed yet.
7649                    // add the installer to the resolve list
7650                    if (DEBUG_EPHEMERAL) {
7651                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7652                    }
7653                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7654                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7655                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7656                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7657                            null /*failureIntent*/);
7658                    // make sure this resolver is the default
7659                    installerInfo.isDefault = true;
7660                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7661                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7662                    // add a non-generic filter
7663                    installerInfo.filter = new IntentFilter();
7664                    // load resources from the correct package
7665                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7666                    resolveInfos.set(i, installerInfo);
7667                }
7668                continue;
7669            }
7670            // allow services that have been explicitly exposed to ephemeral apps
7671            if (!isEphemeralApp
7672                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7673                continue;
7674            }
7675            resolveInfos.remove(i);
7676        }
7677        return resolveInfos;
7678    }
7679
7680    @Override
7681    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7682            String resolvedType, int flags, int userId) {
7683        return new ParceledListSlice<>(
7684                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7685    }
7686
7687    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7688            Intent intent, String resolvedType, int flags, int userId) {
7689        if (!sUserManager.exists(userId)) return Collections.emptyList();
7690        final int callingUid = Binder.getCallingUid();
7691        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7692        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7693                false /*includeInstantApps*/);
7694        ComponentName comp = intent.getComponent();
7695        if (comp == null) {
7696            if (intent.getSelector() != null) {
7697                intent = intent.getSelector();
7698                comp = intent.getComponent();
7699            }
7700        }
7701        if (comp != null) {
7702            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7703            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7704            if (pi != null) {
7705                // When specifying an explicit component, we prevent the provider from being
7706                // used when either 1) the provider is in an instant application and the
7707                // caller is not the same instant application or 2) the calling package is an
7708                // instant application and the provider is not visible to instant applications.
7709                final boolean matchInstantApp =
7710                        (flags & PackageManager.MATCH_INSTANT) != 0;
7711                final boolean matchVisibleToInstantAppOnly =
7712                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7713                final boolean isCallerInstantApp =
7714                        instantAppPkgName != null;
7715                final boolean isTargetSameInstantApp =
7716                        comp.getPackageName().equals(instantAppPkgName);
7717                final boolean isTargetInstantApp =
7718                        (pi.applicationInfo.privateFlags
7719                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7720                final boolean isTargetHiddenFromInstantApp =
7721                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7722                final boolean blockResolution =
7723                        !isTargetSameInstantApp
7724                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7725                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7726                                        && isTargetHiddenFromInstantApp));
7727                if (!blockResolution) {
7728                    final ResolveInfo ri = new ResolveInfo();
7729                    ri.providerInfo = pi;
7730                    list.add(ri);
7731                }
7732            }
7733            return list;
7734        }
7735
7736        // reader
7737        synchronized (mPackages) {
7738            String pkgName = intent.getPackage();
7739            if (pkgName == null) {
7740                return applyPostContentProviderResolutionFilter(
7741                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7742                        instantAppPkgName);
7743            }
7744            final PackageParser.Package pkg = mPackages.get(pkgName);
7745            if (pkg != null) {
7746                return applyPostContentProviderResolutionFilter(
7747                        mProviders.queryIntentForPackage(
7748                        intent, resolvedType, flags, pkg.providers, userId),
7749                        instantAppPkgName);
7750            }
7751            return Collections.emptyList();
7752        }
7753    }
7754
7755    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7756            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7757        if (instantAppPkgName == null) {
7758            return resolveInfos;
7759        }
7760        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7761            final ResolveInfo info = resolveInfos.get(i);
7762            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7763            // allow providers that are defined in the provided package
7764            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7765                if (info.providerInfo.splitName != null
7766                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7767                                info.providerInfo.splitName)) {
7768                    // requested provider is defined in a split that hasn't been installed yet.
7769                    // add the installer to the resolve list
7770                    if (DEBUG_EPHEMERAL) {
7771                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7772                    }
7773                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7774                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7775                            info.providerInfo.packageName, info.providerInfo.splitName,
7776                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7777                            null /*failureIntent*/);
7778                    // make sure this resolver is the default
7779                    installerInfo.isDefault = true;
7780                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7781                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7782                    // add a non-generic filter
7783                    installerInfo.filter = new IntentFilter();
7784                    // load resources from the correct package
7785                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7786                    resolveInfos.set(i, installerInfo);
7787                }
7788                continue;
7789            }
7790            // allow providers that have been explicitly exposed to instant applications
7791            if (!isEphemeralApp
7792                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7793                continue;
7794            }
7795            resolveInfos.remove(i);
7796        }
7797        return resolveInfos;
7798    }
7799
7800    @Override
7801    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7802        final int callingUid = Binder.getCallingUid();
7803        if (getInstantAppPackageName(callingUid) != null) {
7804            return ParceledListSlice.emptyList();
7805        }
7806        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7807        flags = updateFlagsForPackage(flags, userId, null);
7808        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7809        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7810                true /* requireFullPermission */, false /* checkShell */,
7811                "get installed packages");
7812
7813        // writer
7814        synchronized (mPackages) {
7815            ArrayList<PackageInfo> list;
7816            if (listUninstalled) {
7817                list = new ArrayList<>(mSettings.mPackages.size());
7818                for (PackageSetting ps : mSettings.mPackages.values()) {
7819                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7820                        continue;
7821                    }
7822                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7823                        continue;
7824                    }
7825                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7826                    if (pi != null) {
7827                        list.add(pi);
7828                    }
7829                }
7830            } else {
7831                list = new ArrayList<>(mPackages.size());
7832                for (PackageParser.Package p : mPackages.values()) {
7833                    final PackageSetting ps = (PackageSetting) p.mExtras;
7834                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7835                        continue;
7836                    }
7837                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7838                        continue;
7839                    }
7840                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7841                            p.mExtras, flags, userId);
7842                    if (pi != null) {
7843                        list.add(pi);
7844                    }
7845                }
7846            }
7847
7848            return new ParceledListSlice<>(list);
7849        }
7850    }
7851
7852    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7853            String[] permissions, boolean[] tmp, int flags, int userId) {
7854        int numMatch = 0;
7855        final PermissionsState permissionsState = ps.getPermissionsState();
7856        for (int i=0; i<permissions.length; i++) {
7857            final String permission = permissions[i];
7858            if (permissionsState.hasPermission(permission, userId)) {
7859                tmp[i] = true;
7860                numMatch++;
7861            } else {
7862                tmp[i] = false;
7863            }
7864        }
7865        if (numMatch == 0) {
7866            return;
7867        }
7868        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7869
7870        // The above might return null in cases of uninstalled apps or install-state
7871        // skew across users/profiles.
7872        if (pi != null) {
7873            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7874                if (numMatch == permissions.length) {
7875                    pi.requestedPermissions = permissions;
7876                } else {
7877                    pi.requestedPermissions = new String[numMatch];
7878                    numMatch = 0;
7879                    for (int i=0; i<permissions.length; i++) {
7880                        if (tmp[i]) {
7881                            pi.requestedPermissions[numMatch] = permissions[i];
7882                            numMatch++;
7883                        }
7884                    }
7885                }
7886            }
7887            list.add(pi);
7888        }
7889    }
7890
7891    @Override
7892    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7893            String[] permissions, int flags, int userId) {
7894        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7895        flags = updateFlagsForPackage(flags, userId, permissions);
7896        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7897                true /* requireFullPermission */, false /* checkShell */,
7898                "get packages holding permissions");
7899        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7900
7901        // writer
7902        synchronized (mPackages) {
7903            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7904            boolean[] tmpBools = new boolean[permissions.length];
7905            if (listUninstalled) {
7906                for (PackageSetting ps : mSettings.mPackages.values()) {
7907                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7908                            userId);
7909                }
7910            } else {
7911                for (PackageParser.Package pkg : mPackages.values()) {
7912                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7913                    if (ps != null) {
7914                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7915                                userId);
7916                    }
7917                }
7918            }
7919
7920            return new ParceledListSlice<PackageInfo>(list);
7921        }
7922    }
7923
7924    @Override
7925    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7926        final int callingUid = Binder.getCallingUid();
7927        if (getInstantAppPackageName(callingUid) != null) {
7928            return ParceledListSlice.emptyList();
7929        }
7930        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7931        flags = updateFlagsForApplication(flags, userId, null);
7932        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7933
7934        // writer
7935        synchronized (mPackages) {
7936            ArrayList<ApplicationInfo> list;
7937            if (listUninstalled) {
7938                list = new ArrayList<>(mSettings.mPackages.size());
7939                for (PackageSetting ps : mSettings.mPackages.values()) {
7940                    ApplicationInfo ai;
7941                    int effectiveFlags = flags;
7942                    if (ps.isSystem()) {
7943                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7944                    }
7945                    if (ps.pkg != null) {
7946                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7947                            continue;
7948                        }
7949                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7950                            continue;
7951                        }
7952                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7953                                ps.readUserState(userId), userId);
7954                        if (ai != null) {
7955                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7956                        }
7957                    } else {
7958                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7959                        // and already converts to externally visible package name
7960                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7961                                callingUid, effectiveFlags, userId);
7962                    }
7963                    if (ai != null) {
7964                        list.add(ai);
7965                    }
7966                }
7967            } else {
7968                list = new ArrayList<>(mPackages.size());
7969                for (PackageParser.Package p : mPackages.values()) {
7970                    if (p.mExtras != null) {
7971                        PackageSetting ps = (PackageSetting) p.mExtras;
7972                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7973                            continue;
7974                        }
7975                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7976                            continue;
7977                        }
7978                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7979                                ps.readUserState(userId), userId);
7980                        if (ai != null) {
7981                            ai.packageName = resolveExternalPackageNameLPr(p);
7982                            list.add(ai);
7983                        }
7984                    }
7985                }
7986            }
7987
7988            return new ParceledListSlice<>(list);
7989        }
7990    }
7991
7992    @Override
7993    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7994        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7995            return null;
7996        }
7997        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7998            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7999                    "getEphemeralApplications");
8000        }
8001        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8002                true /* requireFullPermission */, false /* checkShell */,
8003                "getEphemeralApplications");
8004        synchronized (mPackages) {
8005            List<InstantAppInfo> instantApps = mInstantAppRegistry
8006                    .getInstantAppsLPr(userId);
8007            if (instantApps != null) {
8008                return new ParceledListSlice<>(instantApps);
8009            }
8010        }
8011        return null;
8012    }
8013
8014    @Override
8015    public boolean isInstantApp(String packageName, int userId) {
8016        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8017                true /* requireFullPermission */, false /* checkShell */,
8018                "isInstantApp");
8019        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8020            return false;
8021        }
8022
8023        synchronized (mPackages) {
8024            int callingUid = Binder.getCallingUid();
8025            if (Process.isIsolated(callingUid)) {
8026                callingUid = mIsolatedOwners.get(callingUid);
8027            }
8028            final PackageSetting ps = mSettings.mPackages.get(packageName);
8029            PackageParser.Package pkg = mPackages.get(packageName);
8030            final boolean returnAllowed =
8031                    ps != null
8032                    && (isCallerSameApp(packageName, callingUid)
8033                            || canViewInstantApps(callingUid, userId)
8034                            || mInstantAppRegistry.isInstantAccessGranted(
8035                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8036            if (returnAllowed) {
8037                return ps.getInstantApp(userId);
8038            }
8039        }
8040        return false;
8041    }
8042
8043    @Override
8044    public byte[] getInstantAppCookie(String packageName, int userId) {
8045        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8046            return null;
8047        }
8048
8049        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8050                true /* requireFullPermission */, false /* checkShell */,
8051                "getInstantAppCookie");
8052        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8053            return null;
8054        }
8055        synchronized (mPackages) {
8056            return mInstantAppRegistry.getInstantAppCookieLPw(
8057                    packageName, userId);
8058        }
8059    }
8060
8061    @Override
8062    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8063        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8064            return true;
8065        }
8066
8067        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8068                true /* requireFullPermission */, true /* checkShell */,
8069                "setInstantAppCookie");
8070        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8071            return false;
8072        }
8073        synchronized (mPackages) {
8074            return mInstantAppRegistry.setInstantAppCookieLPw(
8075                    packageName, cookie, userId);
8076        }
8077    }
8078
8079    @Override
8080    public Bitmap getInstantAppIcon(String packageName, int userId) {
8081        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8082            return null;
8083        }
8084
8085        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8086            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8087                    "getInstantAppIcon");
8088        }
8089        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8090                true /* requireFullPermission */, false /* checkShell */,
8091                "getInstantAppIcon");
8092
8093        synchronized (mPackages) {
8094            return mInstantAppRegistry.getInstantAppIconLPw(
8095                    packageName, userId);
8096        }
8097    }
8098
8099    private boolean isCallerSameApp(String packageName, int uid) {
8100        PackageParser.Package pkg = mPackages.get(packageName);
8101        return pkg != null
8102                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8103    }
8104
8105    @Override
8106    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8107        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8108            return ParceledListSlice.emptyList();
8109        }
8110        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8111    }
8112
8113    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8114        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8115
8116        // reader
8117        synchronized (mPackages) {
8118            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8119            final int userId = UserHandle.getCallingUserId();
8120            while (i.hasNext()) {
8121                final PackageParser.Package p = i.next();
8122                if (p.applicationInfo == null) continue;
8123
8124                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8125                        && !p.applicationInfo.isDirectBootAware();
8126                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8127                        && p.applicationInfo.isDirectBootAware();
8128
8129                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8130                        && (!mSafeMode || isSystemApp(p))
8131                        && (matchesUnaware || matchesAware)) {
8132                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8133                    if (ps != null) {
8134                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8135                                ps.readUserState(userId), userId);
8136                        if (ai != null) {
8137                            finalList.add(ai);
8138                        }
8139                    }
8140                }
8141            }
8142        }
8143
8144        return finalList;
8145    }
8146
8147    @Override
8148    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8149        return resolveContentProviderInternal(name, flags, userId);
8150    }
8151
8152    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8153        if (!sUserManager.exists(userId)) return null;
8154        flags = updateFlagsForComponent(flags, userId, name);
8155        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8156        // reader
8157        synchronized (mPackages) {
8158            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8159            PackageSetting ps = provider != null
8160                    ? mSettings.mPackages.get(provider.owner.packageName)
8161                    : null;
8162            if (ps != null) {
8163                final boolean isInstantApp = ps.getInstantApp(userId);
8164                // normal application; filter out instant application provider
8165                if (instantAppPkgName == null && isInstantApp) {
8166                    return null;
8167                }
8168                // instant application; filter out other instant applications
8169                if (instantAppPkgName != null
8170                        && isInstantApp
8171                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8172                    return null;
8173                }
8174                // instant application; filter out non-exposed provider
8175                if (instantAppPkgName != null
8176                        && !isInstantApp
8177                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8178                    return null;
8179                }
8180                // provider not enabled
8181                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8182                    return null;
8183                }
8184                return PackageParser.generateProviderInfo(
8185                        provider, flags, ps.readUserState(userId), userId);
8186            }
8187            return null;
8188        }
8189    }
8190
8191    /**
8192     * @deprecated
8193     */
8194    @Deprecated
8195    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8196        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8197            return;
8198        }
8199        // reader
8200        synchronized (mPackages) {
8201            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8202                    .entrySet().iterator();
8203            final int userId = UserHandle.getCallingUserId();
8204            while (i.hasNext()) {
8205                Map.Entry<String, PackageParser.Provider> entry = i.next();
8206                PackageParser.Provider p = entry.getValue();
8207                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8208
8209                if (ps != null && p.syncable
8210                        && (!mSafeMode || (p.info.applicationInfo.flags
8211                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8212                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8213                            ps.readUserState(userId), userId);
8214                    if (info != null) {
8215                        outNames.add(entry.getKey());
8216                        outInfo.add(info);
8217                    }
8218                }
8219            }
8220        }
8221    }
8222
8223    @Override
8224    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8225            int uid, int flags, String metaDataKey) {
8226        final int callingUid = Binder.getCallingUid();
8227        final int userId = processName != null ? UserHandle.getUserId(uid)
8228                : UserHandle.getCallingUserId();
8229        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8230        flags = updateFlagsForComponent(flags, userId, processName);
8231        ArrayList<ProviderInfo> finalList = null;
8232        // reader
8233        synchronized (mPackages) {
8234            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8235            while (i.hasNext()) {
8236                final PackageParser.Provider p = i.next();
8237                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8238                if (ps != null && p.info.authority != null
8239                        && (processName == null
8240                                || (p.info.processName.equals(processName)
8241                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8242                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8243
8244                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8245                    // parameter.
8246                    if (metaDataKey != null
8247                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8248                        continue;
8249                    }
8250                    final ComponentName component =
8251                            new ComponentName(p.info.packageName, p.info.name);
8252                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8253                        continue;
8254                    }
8255                    if (finalList == null) {
8256                        finalList = new ArrayList<ProviderInfo>(3);
8257                    }
8258                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8259                            ps.readUserState(userId), userId);
8260                    if (info != null) {
8261                        finalList.add(info);
8262                    }
8263                }
8264            }
8265        }
8266
8267        if (finalList != null) {
8268            Collections.sort(finalList, mProviderInitOrderSorter);
8269            return new ParceledListSlice<ProviderInfo>(finalList);
8270        }
8271
8272        return ParceledListSlice.emptyList();
8273    }
8274
8275    @Override
8276    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8277        // reader
8278        synchronized (mPackages) {
8279            final int callingUid = Binder.getCallingUid();
8280            final int callingUserId = UserHandle.getUserId(callingUid);
8281            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8282            if (ps == null) return null;
8283            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8284                return null;
8285            }
8286            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8287            return PackageParser.generateInstrumentationInfo(i, flags);
8288        }
8289    }
8290
8291    @Override
8292    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8293            String targetPackage, int flags) {
8294        final int callingUid = Binder.getCallingUid();
8295        final int callingUserId = UserHandle.getUserId(callingUid);
8296        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8297        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8298            return ParceledListSlice.emptyList();
8299        }
8300        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8301    }
8302
8303    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8304            int flags) {
8305        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8306
8307        // reader
8308        synchronized (mPackages) {
8309            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8310            while (i.hasNext()) {
8311                final PackageParser.Instrumentation p = i.next();
8312                if (targetPackage == null
8313                        || targetPackage.equals(p.info.targetPackage)) {
8314                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8315                            flags);
8316                    if (ii != null) {
8317                        finalList.add(ii);
8318                    }
8319                }
8320            }
8321        }
8322
8323        return finalList;
8324    }
8325
8326    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8327        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8328        try {
8329            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8330        } finally {
8331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8332        }
8333    }
8334
8335    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8336        final File[] files = dir.listFiles();
8337        if (ArrayUtils.isEmpty(files)) {
8338            Log.d(TAG, "No files in app dir " + dir);
8339            return;
8340        }
8341
8342        if (DEBUG_PACKAGE_SCANNING) {
8343            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8344                    + " flags=0x" + Integer.toHexString(parseFlags));
8345        }
8346        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8347                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8348                mParallelPackageParserCallback);
8349
8350        // Submit files for parsing in parallel
8351        int fileCount = 0;
8352        for (File file : files) {
8353            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8354                    && !PackageInstallerService.isStageName(file.getName());
8355            if (!isPackage) {
8356                // Ignore entries which are not packages
8357                continue;
8358            }
8359            parallelPackageParser.submit(file, parseFlags);
8360            fileCount++;
8361        }
8362
8363        // Process results one by one
8364        for (; fileCount > 0; fileCount--) {
8365            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8366            Throwable throwable = parseResult.throwable;
8367            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8368
8369            if (throwable == null) {
8370                // Static shared libraries have synthetic package names
8371                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8372                    renameStaticSharedLibraryPackage(parseResult.pkg);
8373                }
8374                try {
8375                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8376                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8377                                currentTime, null);
8378                    }
8379                } catch (PackageManagerException e) {
8380                    errorCode = e.error;
8381                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8382                }
8383            } else if (throwable instanceof PackageParser.PackageParserException) {
8384                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8385                        throwable;
8386                errorCode = e.error;
8387                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8388            } else {
8389                throw new IllegalStateException("Unexpected exception occurred while parsing "
8390                        + parseResult.scanFile, throwable);
8391            }
8392
8393            // Delete invalid userdata apps
8394            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8395                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8396                logCriticalInfo(Log.WARN,
8397                        "Deleting invalid package at " + parseResult.scanFile);
8398                removeCodePathLI(parseResult.scanFile);
8399            }
8400        }
8401        parallelPackageParser.close();
8402    }
8403
8404    private static File getSettingsProblemFile() {
8405        File dataDir = Environment.getDataDirectory();
8406        File systemDir = new File(dataDir, "system");
8407        File fname = new File(systemDir, "uiderrors.txt");
8408        return fname;
8409    }
8410
8411    public static void reportSettingsProblem(int priority, String msg) {
8412        logCriticalInfo(priority, msg);
8413    }
8414
8415    public static void logCriticalInfo(int priority, String msg) {
8416        Slog.println(priority, TAG, msg);
8417        EventLogTags.writePmCriticalInfo(msg);
8418        try {
8419            File fname = getSettingsProblemFile();
8420            FileOutputStream out = new FileOutputStream(fname, true);
8421            PrintWriter pw = new FastPrintWriter(out);
8422            SimpleDateFormat formatter = new SimpleDateFormat();
8423            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8424            pw.println(dateString + ": " + msg);
8425            pw.close();
8426            FileUtils.setPermissions(
8427                    fname.toString(),
8428                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8429                    -1, -1);
8430        } catch (java.io.IOException e) {
8431        }
8432    }
8433
8434    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8435        if (srcFile.isDirectory()) {
8436            final File baseFile = new File(pkg.baseCodePath);
8437            long maxModifiedTime = baseFile.lastModified();
8438            if (pkg.splitCodePaths != null) {
8439                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8440                    final File splitFile = new File(pkg.splitCodePaths[i]);
8441                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8442                }
8443            }
8444            return maxModifiedTime;
8445        }
8446        return srcFile.lastModified();
8447    }
8448
8449    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8450            final int policyFlags) throws PackageManagerException {
8451        // When upgrading from pre-N MR1, verify the package time stamp using the package
8452        // directory and not the APK file.
8453        final long lastModifiedTime = mIsPreNMR1Upgrade
8454                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8455        if (ps != null
8456                && ps.codePath.equals(srcFile)
8457                && ps.timeStamp == lastModifiedTime
8458                && !isCompatSignatureUpdateNeeded(pkg)
8459                && !isRecoverSignatureUpdateNeeded(pkg)) {
8460            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8462            ArraySet<PublicKey> signingKs;
8463            synchronized (mPackages) {
8464                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8465            }
8466            if (ps.signatures.mSignatures != null
8467                    && ps.signatures.mSignatures.length != 0
8468                    && signingKs != null) {
8469                // Optimization: reuse the existing cached certificates
8470                // if the package appears to be unchanged.
8471                pkg.mSignatures = ps.signatures.mSignatures;
8472                pkg.mSigningKeys = signingKs;
8473                return;
8474            }
8475
8476            Slog.w(TAG, "PackageSetting for " + ps.name
8477                    + " is missing signatures.  Collecting certs again to recover them.");
8478        } else {
8479            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8480        }
8481
8482        try {
8483            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8484            PackageParser.collectCertificates(pkg, policyFlags);
8485        } catch (PackageParserException e) {
8486            throw PackageManagerException.from(e);
8487        } finally {
8488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8489        }
8490    }
8491
8492    /**
8493     *  Traces a package scan.
8494     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8495     */
8496    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8497            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8498        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8499        try {
8500            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8501        } finally {
8502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8503        }
8504    }
8505
8506    /**
8507     *  Scans a package and returns the newly parsed package.
8508     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8509     */
8510    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8511            long currentTime, UserHandle user) throws PackageManagerException {
8512        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8513        PackageParser pp = new PackageParser();
8514        pp.setSeparateProcesses(mSeparateProcesses);
8515        pp.setOnlyCoreApps(mOnlyCore);
8516        pp.setDisplayMetrics(mMetrics);
8517        pp.setCallback(mPackageParserCallback);
8518
8519        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8520            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8521        }
8522
8523        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8524        final PackageParser.Package pkg;
8525        try {
8526            pkg = pp.parsePackage(scanFile, parseFlags);
8527        } catch (PackageParserException e) {
8528            throw PackageManagerException.from(e);
8529        } finally {
8530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8531        }
8532
8533        // Static shared libraries have synthetic package names
8534        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8535            renameStaticSharedLibraryPackage(pkg);
8536        }
8537
8538        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8539    }
8540
8541    /**
8542     *  Scans a package and returns the newly parsed package.
8543     *  @throws PackageManagerException on a parse error.
8544     */
8545    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8546            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8547            throws PackageManagerException {
8548        // If the package has children and this is the first dive in the function
8549        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8550        // packages (parent and children) would be successfully scanned before the
8551        // actual scan since scanning mutates internal state and we want to atomically
8552        // install the package and its children.
8553        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8554            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8555                scanFlags |= SCAN_CHECK_ONLY;
8556            }
8557        } else {
8558            scanFlags &= ~SCAN_CHECK_ONLY;
8559        }
8560
8561        // Scan the parent
8562        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8563                scanFlags, currentTime, user);
8564
8565        // Scan the children
8566        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8567        for (int i = 0; i < childCount; i++) {
8568            PackageParser.Package childPackage = pkg.childPackages.get(i);
8569            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8570                    currentTime, user);
8571        }
8572
8573
8574        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8575            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8576        }
8577
8578        return scannedPkg;
8579    }
8580
8581    /**
8582     *  Scans a package and returns the newly parsed package.
8583     *  @throws PackageManagerException on a parse error.
8584     */
8585    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8586            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8587            throws PackageManagerException {
8588        PackageSetting ps = null;
8589        PackageSetting updatedPkg;
8590        // reader
8591        synchronized (mPackages) {
8592            // Look to see if we already know about this package.
8593            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8594            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8595                // This package has been renamed to its original name.  Let's
8596                // use that.
8597                ps = mSettings.getPackageLPr(oldName);
8598            }
8599            // If there was no original package, see one for the real package name.
8600            if (ps == null) {
8601                ps = mSettings.getPackageLPr(pkg.packageName);
8602            }
8603            // Check to see if this package could be hiding/updating a system
8604            // package.  Must look for it either under the original or real
8605            // package name depending on our state.
8606            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8607            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8608
8609            // If this is a package we don't know about on the system partition, we
8610            // may need to remove disabled child packages on the system partition
8611            // or may need to not add child packages if the parent apk is updated
8612            // on the data partition and no longer defines this child package.
8613            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8614                // If this is a parent package for an updated system app and this system
8615                // app got an OTA update which no longer defines some of the child packages
8616                // we have to prune them from the disabled system packages.
8617                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8618                if (disabledPs != null) {
8619                    final int scannedChildCount = (pkg.childPackages != null)
8620                            ? pkg.childPackages.size() : 0;
8621                    final int disabledChildCount = disabledPs.childPackageNames != null
8622                            ? disabledPs.childPackageNames.size() : 0;
8623                    for (int i = 0; i < disabledChildCount; i++) {
8624                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8625                        boolean disabledPackageAvailable = false;
8626                        for (int j = 0; j < scannedChildCount; j++) {
8627                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8628                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8629                                disabledPackageAvailable = true;
8630                                break;
8631                            }
8632                         }
8633                         if (!disabledPackageAvailable) {
8634                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8635                         }
8636                    }
8637                }
8638            }
8639        }
8640
8641        final boolean isUpdatedPkg = updatedPkg != null;
8642        final boolean isUpdatedSystemPkg = isUpdatedPkg
8643                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8644        boolean isUpdatedPkgBetter = false;
8645        // First check if this is a system package that may involve an update
8646        if (isUpdatedSystemPkg) {
8647            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8648            // it needs to drop FLAG_PRIVILEGED.
8649            if (locationIsPrivileged(scanFile)) {
8650                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8651            } else {
8652                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8653            }
8654            // If new package is not located in "/oem" (e.g. due to an OTA),
8655            // it needs to drop FLAG_OEM.
8656            if (locationIsOem(scanFile)) {
8657                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8658            } else {
8659                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8660            }
8661
8662            if (ps != null && !ps.codePath.equals(scanFile)) {
8663                // The path has changed from what was last scanned...  check the
8664                // version of the new path against what we have stored to determine
8665                // what to do.
8666                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8667                if (pkg.mVersionCode <= ps.versionCode) {
8668                    // The system package has been updated and the code path does not match
8669                    // Ignore entry. Skip it.
8670                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8671                            + " ignored: updated version " + ps.versionCode
8672                            + " better than this " + pkg.mVersionCode);
8673                    if (!updatedPkg.codePath.equals(scanFile)) {
8674                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8675                                + ps.name + " changing from " + updatedPkg.codePathString
8676                                + " to " + scanFile);
8677                        updatedPkg.codePath = scanFile;
8678                        updatedPkg.codePathString = scanFile.toString();
8679                        updatedPkg.resourcePath = scanFile;
8680                        updatedPkg.resourcePathString = scanFile.toString();
8681                    }
8682                    updatedPkg.pkg = pkg;
8683                    updatedPkg.versionCode = pkg.mVersionCode;
8684
8685                    // Update the disabled system child packages to point to the package too.
8686                    final int childCount = updatedPkg.childPackageNames != null
8687                            ? updatedPkg.childPackageNames.size() : 0;
8688                    for (int i = 0; i < childCount; i++) {
8689                        String childPackageName = updatedPkg.childPackageNames.get(i);
8690                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8691                                childPackageName);
8692                        if (updatedChildPkg != null) {
8693                            updatedChildPkg.pkg = pkg;
8694                            updatedChildPkg.versionCode = pkg.mVersionCode;
8695                        }
8696                    }
8697                } else {
8698                    // The current app on the system partition is better than
8699                    // what we have updated to on the data partition; switch
8700                    // back to the system partition version.
8701                    // At this point, its safely assumed that package installation for
8702                    // apps in system partition will go through. If not there won't be a working
8703                    // version of the app
8704                    // writer
8705                    synchronized (mPackages) {
8706                        // Just remove the loaded entries from package lists.
8707                        mPackages.remove(ps.name);
8708                    }
8709
8710                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8711                            + " reverting from " + ps.codePathString
8712                            + ": new version " + pkg.mVersionCode
8713                            + " better than installed " + ps.versionCode);
8714
8715                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8716                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8717                    synchronized (mInstallLock) {
8718                        args.cleanUpResourcesLI();
8719                    }
8720                    synchronized (mPackages) {
8721                        mSettings.enableSystemPackageLPw(ps.name);
8722                    }
8723                    isUpdatedPkgBetter = true;
8724                }
8725            }
8726        }
8727
8728        String resourcePath = null;
8729        String baseResourcePath = null;
8730        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8731            if (ps != null && ps.resourcePathString != null) {
8732                resourcePath = ps.resourcePathString;
8733                baseResourcePath = ps.resourcePathString;
8734            } else {
8735                // Should not happen at all. Just log an error.
8736                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8737            }
8738        } else {
8739            resourcePath = pkg.codePath;
8740            baseResourcePath = pkg.baseCodePath;
8741        }
8742
8743        // Set application objects path explicitly.
8744        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8745        pkg.setApplicationInfoCodePath(pkg.codePath);
8746        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8747        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8748        pkg.setApplicationInfoResourcePath(resourcePath);
8749        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8750        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8751
8752        // throw an exception if we have an update to a system application, but, it's not more
8753        // recent than the package we've already scanned
8754        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8755            // Set CPU Abis to application info.
8756            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8757                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8758                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8759            } else {
8760                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8761                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8762            }
8763
8764            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8765                    + scanFile + " ignored: updated version " + ps.versionCode
8766                    + " better than this " + pkg.mVersionCode);
8767        }
8768
8769        if (isUpdatedPkg) {
8770            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8771            // initially
8772            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8773
8774            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8775            // flag set initially
8776            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8777                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8778            }
8779
8780            // An updated OEM app will not have the PARSE_IS_OEM
8781            // flag set initially
8782            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8783                policyFlags |= PackageParser.PARSE_IS_OEM;
8784            }
8785        }
8786
8787        // Verify certificates against what was last scanned
8788        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8789
8790        /*
8791         * A new system app appeared, but we already had a non-system one of the
8792         * same name installed earlier.
8793         */
8794        boolean shouldHideSystemApp = false;
8795        if (!isUpdatedPkg && ps != null
8796                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8797            /*
8798             * Check to make sure the signatures match first. If they don't,
8799             * wipe the installed application and its data.
8800             */
8801            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8802                    != PackageManager.SIGNATURE_MATCH) {
8803                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8804                        + " signatures don't match existing userdata copy; removing");
8805                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8806                        "scanPackageInternalLI")) {
8807                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8808                }
8809                ps = null;
8810            } else {
8811                /*
8812                 * If the newly-added system app is an older version than the
8813                 * already installed version, hide it. It will be scanned later
8814                 * and re-added like an update.
8815                 */
8816                if (pkg.mVersionCode <= ps.versionCode) {
8817                    shouldHideSystemApp = true;
8818                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8819                            + " but new version " + pkg.mVersionCode + " better than installed "
8820                            + ps.versionCode + "; hiding system");
8821                } else {
8822                    /*
8823                     * The newly found system app is a newer version that the
8824                     * one previously installed. Simply remove the
8825                     * already-installed application and replace it with our own
8826                     * while keeping the application data.
8827                     */
8828                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8829                            + " reverting from " + ps.codePathString + ": new version "
8830                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8831                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8832                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8833                    synchronized (mInstallLock) {
8834                        args.cleanUpResourcesLI();
8835                    }
8836                }
8837            }
8838        }
8839
8840        // The apk is forward locked (not public) if its code and resources
8841        // are kept in different files. (except for app in either system or
8842        // vendor path).
8843        // TODO grab this value from PackageSettings
8844        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8845            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8846                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8847            }
8848        }
8849
8850        final int userId = ((user == null) ? 0 : user.getIdentifier());
8851        if (ps != null && ps.getInstantApp(userId)) {
8852            scanFlags |= SCAN_AS_INSTANT_APP;
8853        }
8854        if (ps != null && ps.getVirtulalPreload(userId)) {
8855            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8856        }
8857
8858        // Note that we invoke the following method only if we are about to unpack an application
8859        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8860                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8861
8862        /*
8863         * If the system app should be overridden by a previously installed
8864         * data, hide the system app now and let the /data/app scan pick it up
8865         * again.
8866         */
8867        if (shouldHideSystemApp) {
8868            synchronized (mPackages) {
8869                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8870            }
8871        }
8872
8873        return scannedPkg;
8874    }
8875
8876    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8877        // Derive the new package synthetic package name
8878        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8879                + pkg.staticSharedLibVersion);
8880    }
8881
8882    private static String fixProcessName(String defProcessName,
8883            String processName) {
8884        if (processName == null) {
8885            return defProcessName;
8886        }
8887        return processName;
8888    }
8889
8890    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8891            throws PackageManagerException {
8892        if (pkgSetting.signatures.mSignatures != null) {
8893            // Already existing package. Make sure signatures match
8894            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8895                    == PackageManager.SIGNATURE_MATCH;
8896            if (!match) {
8897                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8898                        == PackageManager.SIGNATURE_MATCH;
8899            }
8900            if (!match) {
8901                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8902                        == PackageManager.SIGNATURE_MATCH;
8903            }
8904            if (!match) {
8905                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8906                        + pkg.packageName + " signatures do not match the "
8907                        + "previously installed version; ignoring!");
8908            }
8909        }
8910
8911        // Check for shared user signatures
8912        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8913            // Already existing package. Make sure signatures match
8914            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8915                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8916            if (!match) {
8917                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8918                        == PackageManager.SIGNATURE_MATCH;
8919            }
8920            if (!match) {
8921                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8922                        == PackageManager.SIGNATURE_MATCH;
8923            }
8924            if (!match) {
8925                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8926                        "Package " + pkg.packageName
8927                        + " has no signatures that match those in shared user "
8928                        + pkgSetting.sharedUser.name + "; ignoring!");
8929            }
8930        }
8931    }
8932
8933    /**
8934     * Enforces that only the system UID or root's UID can call a method exposed
8935     * via Binder.
8936     *
8937     * @param message used as message if SecurityException is thrown
8938     * @throws SecurityException if the caller is not system or root
8939     */
8940    private static final void enforceSystemOrRoot(String message) {
8941        final int uid = Binder.getCallingUid();
8942        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8943            throw new SecurityException(message);
8944        }
8945    }
8946
8947    @Override
8948    public void performFstrimIfNeeded() {
8949        enforceSystemOrRoot("Only the system can request fstrim");
8950
8951        // Before everything else, see whether we need to fstrim.
8952        try {
8953            IStorageManager sm = PackageHelper.getStorageManager();
8954            if (sm != null) {
8955                boolean doTrim = false;
8956                final long interval = android.provider.Settings.Global.getLong(
8957                        mContext.getContentResolver(),
8958                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8959                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8960                if (interval > 0) {
8961                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8962                    if (timeSinceLast > interval) {
8963                        doTrim = true;
8964                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8965                                + "; running immediately");
8966                    }
8967                }
8968                if (doTrim) {
8969                    final boolean dexOptDialogShown;
8970                    synchronized (mPackages) {
8971                        dexOptDialogShown = mDexOptDialogShown;
8972                    }
8973                    if (!isFirstBoot() && dexOptDialogShown) {
8974                        try {
8975                            ActivityManager.getService().showBootMessage(
8976                                    mContext.getResources().getString(
8977                                            R.string.android_upgrading_fstrim), true);
8978                        } catch (RemoteException e) {
8979                        }
8980                    }
8981                    sm.runMaintenance();
8982                }
8983            } else {
8984                Slog.e(TAG, "storageManager service unavailable!");
8985            }
8986        } catch (RemoteException e) {
8987            // Can't happen; StorageManagerService is local
8988        }
8989    }
8990
8991    @Override
8992    public void updatePackagesIfNeeded() {
8993        enforceSystemOrRoot("Only the system can request package update");
8994
8995        // We need to re-extract after an OTA.
8996        boolean causeUpgrade = isUpgrade();
8997
8998        // First boot or factory reset.
8999        // Note: we also handle devices that are upgrading to N right now as if it is their
9000        //       first boot, as they do not have profile data.
9001        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9002
9003        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9004        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9005
9006        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9007            return;
9008        }
9009
9010        List<PackageParser.Package> pkgs;
9011        synchronized (mPackages) {
9012            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9013        }
9014
9015        final long startTime = System.nanoTime();
9016        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9017                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9018                    false /* bootComplete */);
9019
9020        final int elapsedTimeSeconds =
9021                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9022
9023        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9024        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9025        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9026        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9027        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9028    }
9029
9030    /*
9031     * Return the prebuilt profile path given a package base code path.
9032     */
9033    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9034        return pkg.baseCodePath + ".prof";
9035    }
9036
9037    /**
9038     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9039     * containing statistics about the invocation. The array consists of three elements,
9040     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9041     * and {@code numberOfPackagesFailed}.
9042     */
9043    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9044            final String compilerFilter, boolean bootComplete) {
9045
9046        int numberOfPackagesVisited = 0;
9047        int numberOfPackagesOptimized = 0;
9048        int numberOfPackagesSkipped = 0;
9049        int numberOfPackagesFailed = 0;
9050        final int numberOfPackagesToDexopt = pkgs.size();
9051
9052        for (PackageParser.Package pkg : pkgs) {
9053            numberOfPackagesVisited++;
9054
9055            boolean useProfileForDexopt = false;
9056
9057            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9058                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9059                // that are already compiled.
9060                File profileFile = new File(getPrebuildProfilePath(pkg));
9061                // Copy profile if it exists.
9062                if (profileFile.exists()) {
9063                    try {
9064                        // We could also do this lazily before calling dexopt in
9065                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9066                        // is that we don't have a good way to say "do this only once".
9067                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9068                                pkg.applicationInfo.uid, pkg.packageName)) {
9069                            Log.e(TAG, "Installer failed to copy system profile!");
9070                        } else {
9071                            // Disabled as this causes speed-profile compilation during first boot
9072                            // even if things are already compiled.
9073                            // useProfileForDexopt = true;
9074                        }
9075                    } catch (Exception e) {
9076                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9077                                e);
9078                    }
9079                } else {
9080                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9081                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9082                    // minimize the number off apps being speed-profile compiled during first boot.
9083                    // The other paths will not change the filter.
9084                    if (disabledPs != null && disabledPs.pkg.isStub) {
9085                        // The package is the stub one, remove the stub suffix to get the normal
9086                        // package and APK names.
9087                        String systemProfilePath =
9088                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9089                        profileFile = new File(systemProfilePath);
9090                        // If we have a profile for a compressed APK, copy it to the reference
9091                        // location.
9092                        // Note that copying the profile here will cause it to override the
9093                        // reference profile every OTA even though the existing reference profile
9094                        // may have more data. We can't copy during decompression since the
9095                        // directories are not set up at that point.
9096                        if (profileFile.exists()) {
9097                            try {
9098                                // We could also do this lazily before calling dexopt in
9099                                // PackageDexOptimizer to prevent this happening on first boot. The
9100                                // issue is that we don't have a good way to say "do this only
9101                                // once".
9102                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9103                                        pkg.applicationInfo.uid, pkg.packageName)) {
9104                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9105                                } else {
9106                                    useProfileForDexopt = true;
9107                                }
9108                            } catch (Exception e) {
9109                                Log.e(TAG, "Failed to copy profile " +
9110                                        profileFile.getAbsolutePath() + " ", e);
9111                            }
9112                        }
9113                    }
9114                }
9115            }
9116
9117            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9118                if (DEBUG_DEXOPT) {
9119                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9120                }
9121                numberOfPackagesSkipped++;
9122                continue;
9123            }
9124
9125            if (DEBUG_DEXOPT) {
9126                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9127                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9128            }
9129
9130            if (showDialog) {
9131                try {
9132                    ActivityManager.getService().showBootMessage(
9133                            mContext.getResources().getString(R.string.android_upgrading_apk,
9134                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9135                } catch (RemoteException e) {
9136                }
9137                synchronized (mPackages) {
9138                    mDexOptDialogShown = true;
9139                }
9140            }
9141
9142            String pkgCompilerFilter = compilerFilter;
9143            if (useProfileForDexopt) {
9144                // Use background dexopt mode to try and use the profile. Note that this does not
9145                // guarantee usage of the profile.
9146                pkgCompilerFilter =
9147                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9148                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9149            }
9150
9151            // checkProfiles is false to avoid merging profiles during boot which
9152            // might interfere with background compilation (b/28612421).
9153            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9154            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9155            // trade-off worth doing to save boot time work.
9156            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9157            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9158                    pkg.packageName,
9159                    pkgCompilerFilter,
9160                    dexoptFlags));
9161
9162            switch (primaryDexOptStaus) {
9163                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9164                    numberOfPackagesOptimized++;
9165                    break;
9166                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9167                    numberOfPackagesSkipped++;
9168                    break;
9169                case PackageDexOptimizer.DEX_OPT_FAILED:
9170                    numberOfPackagesFailed++;
9171                    break;
9172                default:
9173                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9174                    break;
9175            }
9176        }
9177
9178        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9179                numberOfPackagesFailed };
9180    }
9181
9182    @Override
9183    public void notifyPackageUse(String packageName, int reason) {
9184        synchronized (mPackages) {
9185            final int callingUid = Binder.getCallingUid();
9186            final int callingUserId = UserHandle.getUserId(callingUid);
9187            if (getInstantAppPackageName(callingUid) != null) {
9188                if (!isCallerSameApp(packageName, callingUid)) {
9189                    return;
9190                }
9191            } else {
9192                if (isInstantApp(packageName, callingUserId)) {
9193                    return;
9194                }
9195            }
9196            notifyPackageUseLocked(packageName, reason);
9197        }
9198    }
9199
9200    private void notifyPackageUseLocked(String packageName, int reason) {
9201        final PackageParser.Package p = mPackages.get(packageName);
9202        if (p == null) {
9203            return;
9204        }
9205        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9206    }
9207
9208    @Override
9209    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9210            List<String> classPaths, String loaderIsa) {
9211        int userId = UserHandle.getCallingUserId();
9212        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9213        if (ai == null) {
9214            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9215                + loadingPackageName + ", user=" + userId);
9216            return;
9217        }
9218        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9219    }
9220
9221    @Override
9222    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9223            IDexModuleRegisterCallback callback) {
9224        int userId = UserHandle.getCallingUserId();
9225        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9226        DexManager.RegisterDexModuleResult result;
9227        if (ai == null) {
9228            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9229                     " calling user. package=" + packageName + ", user=" + userId);
9230            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9231        } else {
9232            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9233        }
9234
9235        if (callback != null) {
9236            mHandler.post(() -> {
9237                try {
9238                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9239                } catch (RemoteException e) {
9240                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9241                }
9242            });
9243        }
9244    }
9245
9246    /**
9247     * Ask the package manager to perform a dex-opt with the given compiler filter.
9248     *
9249     * Note: exposed only for the shell command to allow moving packages explicitly to a
9250     *       definite state.
9251     */
9252    @Override
9253    public boolean performDexOptMode(String packageName,
9254            boolean checkProfiles, String targetCompilerFilter, boolean force,
9255            boolean bootComplete, String splitName) {
9256        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9257                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9258                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9259        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9260                splitName, flags));
9261    }
9262
9263    /**
9264     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9265     * secondary dex files belonging to the given package.
9266     *
9267     * Note: exposed only for the shell command to allow moving packages explicitly to a
9268     *       definite state.
9269     */
9270    @Override
9271    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9272            boolean force) {
9273        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9274                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9275                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9276                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9277        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9278    }
9279
9280    /*package*/ boolean performDexOpt(DexoptOptions options) {
9281        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9282            return false;
9283        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9284            return false;
9285        }
9286
9287        if (options.isDexoptOnlySecondaryDex()) {
9288            return mDexManager.dexoptSecondaryDex(options);
9289        } else {
9290            int dexoptStatus = performDexOptWithStatus(options);
9291            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9292        }
9293    }
9294
9295    /**
9296     * Perform dexopt on the given package and return one of following result:
9297     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9298     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9299     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9300     */
9301    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9302        return performDexOptTraced(options);
9303    }
9304
9305    private int performDexOptTraced(DexoptOptions options) {
9306        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9307        try {
9308            return performDexOptInternal(options);
9309        } finally {
9310            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9311        }
9312    }
9313
9314    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9315    // if the package can now be considered up to date for the given filter.
9316    private int performDexOptInternal(DexoptOptions options) {
9317        PackageParser.Package p;
9318        synchronized (mPackages) {
9319            p = mPackages.get(options.getPackageName());
9320            if (p == null) {
9321                // Package could not be found. Report failure.
9322                return PackageDexOptimizer.DEX_OPT_FAILED;
9323            }
9324            mPackageUsage.maybeWriteAsync(mPackages);
9325            mCompilerStats.maybeWriteAsync();
9326        }
9327        long callingId = Binder.clearCallingIdentity();
9328        try {
9329            synchronized (mInstallLock) {
9330                return performDexOptInternalWithDependenciesLI(p, options);
9331            }
9332        } finally {
9333            Binder.restoreCallingIdentity(callingId);
9334        }
9335    }
9336
9337    public ArraySet<String> getOptimizablePackages() {
9338        ArraySet<String> pkgs = new ArraySet<String>();
9339        synchronized (mPackages) {
9340            for (PackageParser.Package p : mPackages.values()) {
9341                if (PackageDexOptimizer.canOptimizePackage(p)) {
9342                    pkgs.add(p.packageName);
9343                }
9344            }
9345        }
9346        return pkgs;
9347    }
9348
9349    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9350            DexoptOptions options) {
9351        // Select the dex optimizer based on the force parameter.
9352        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9353        //       allocate an object here.
9354        PackageDexOptimizer pdo = options.isForce()
9355                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9356                : mPackageDexOptimizer;
9357
9358        // Dexopt all dependencies first. Note: we ignore the return value and march on
9359        // on errors.
9360        // Note that we are going to call performDexOpt on those libraries as many times as
9361        // they are referenced in packages. When we do a batch of performDexOpt (for example
9362        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9363        // and the first package that uses the library will dexopt it. The
9364        // others will see that the compiled code for the library is up to date.
9365        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9366        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9367        if (!deps.isEmpty()) {
9368            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9369                    options.getCompilerFilter(), options.getSplitName(),
9370                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9371            for (PackageParser.Package depPackage : deps) {
9372                // TODO: Analyze and investigate if we (should) profile libraries.
9373                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9374                        getOrCreateCompilerPackageStats(depPackage),
9375                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9376            }
9377        }
9378        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9379                getOrCreateCompilerPackageStats(p),
9380                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9381    }
9382
9383    /**
9384     * Reconcile the information we have about the secondary dex files belonging to
9385     * {@code packagName} and the actual dex files. For all dex files that were
9386     * deleted, update the internal records and delete the generated oat files.
9387     */
9388    @Override
9389    public void reconcileSecondaryDexFiles(String packageName) {
9390        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9391            return;
9392        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9393            return;
9394        }
9395        mDexManager.reconcileSecondaryDexFiles(packageName);
9396    }
9397
9398    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9399    // a reference there.
9400    /*package*/ DexManager getDexManager() {
9401        return mDexManager;
9402    }
9403
9404    /**
9405     * Execute the background dexopt job immediately.
9406     */
9407    @Override
9408    public boolean runBackgroundDexoptJob() {
9409        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9410            return false;
9411        }
9412        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9413    }
9414
9415    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9416        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9417                || p.usesStaticLibraries != null) {
9418            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9419            Set<String> collectedNames = new HashSet<>();
9420            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9421
9422            retValue.remove(p);
9423
9424            return retValue;
9425        } else {
9426            return Collections.emptyList();
9427        }
9428    }
9429
9430    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9431            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9432        if (!collectedNames.contains(p.packageName)) {
9433            collectedNames.add(p.packageName);
9434            collected.add(p);
9435
9436            if (p.usesLibraries != null) {
9437                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9438                        null, collected, collectedNames);
9439            }
9440            if (p.usesOptionalLibraries != null) {
9441                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9442                        null, collected, collectedNames);
9443            }
9444            if (p.usesStaticLibraries != null) {
9445                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9446                        p.usesStaticLibrariesVersions, collected, collectedNames);
9447            }
9448        }
9449    }
9450
9451    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9452            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9453        final int libNameCount = libs.size();
9454        for (int i = 0; i < libNameCount; i++) {
9455            String libName = libs.get(i);
9456            int version = (versions != null && versions.length == libNameCount)
9457                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9458            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9459            if (libPkg != null) {
9460                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9461            }
9462        }
9463    }
9464
9465    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9466        synchronized (mPackages) {
9467            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9468            if (libEntry != null) {
9469                return mPackages.get(libEntry.apk);
9470            }
9471            return null;
9472        }
9473    }
9474
9475    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9476        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9477        if (versionedLib == null) {
9478            return null;
9479        }
9480        return versionedLib.get(version);
9481    }
9482
9483    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9484        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9485                pkg.staticSharedLibName);
9486        if (versionedLib == null) {
9487            return null;
9488        }
9489        int previousLibVersion = -1;
9490        final int versionCount = versionedLib.size();
9491        for (int i = 0; i < versionCount; i++) {
9492            final int libVersion = versionedLib.keyAt(i);
9493            if (libVersion < pkg.staticSharedLibVersion) {
9494                previousLibVersion = Math.max(previousLibVersion, libVersion);
9495            }
9496        }
9497        if (previousLibVersion >= 0) {
9498            return versionedLib.get(previousLibVersion);
9499        }
9500        return null;
9501    }
9502
9503    public void shutdown() {
9504        mPackageUsage.writeNow(mPackages);
9505        mCompilerStats.writeNow();
9506        mDexManager.writePackageDexUsageNow();
9507    }
9508
9509    @Override
9510    public void dumpProfiles(String packageName) {
9511        PackageParser.Package pkg;
9512        synchronized (mPackages) {
9513            pkg = mPackages.get(packageName);
9514            if (pkg == null) {
9515                throw new IllegalArgumentException("Unknown package: " + packageName);
9516            }
9517        }
9518        /* Only the shell, root, or the app user should be able to dump profiles. */
9519        int callingUid = Binder.getCallingUid();
9520        if (callingUid != Process.SHELL_UID &&
9521            callingUid != Process.ROOT_UID &&
9522            callingUid != pkg.applicationInfo.uid) {
9523            throw new SecurityException("dumpProfiles");
9524        }
9525
9526        synchronized (mInstallLock) {
9527            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9528            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9529            try {
9530                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9531                String codePaths = TextUtils.join(";", allCodePaths);
9532                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9533            } catch (InstallerException e) {
9534                Slog.w(TAG, "Failed to dump profiles", e);
9535            }
9536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9537        }
9538    }
9539
9540    @Override
9541    public void forceDexOpt(String packageName) {
9542        enforceSystemOrRoot("forceDexOpt");
9543
9544        PackageParser.Package pkg;
9545        synchronized (mPackages) {
9546            pkg = mPackages.get(packageName);
9547            if (pkg == null) {
9548                throw new IllegalArgumentException("Unknown package: " + packageName);
9549            }
9550        }
9551
9552        synchronized (mInstallLock) {
9553            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9554
9555            // Whoever is calling forceDexOpt wants a compiled package.
9556            // Don't use profiles since that may cause compilation to be skipped.
9557            final int res = performDexOptInternalWithDependenciesLI(
9558                    pkg,
9559                    new DexoptOptions(packageName,
9560                            getDefaultCompilerFilter(),
9561                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9562
9563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9564            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9565                throw new IllegalStateException("Failed to dexopt: " + res);
9566            }
9567        }
9568    }
9569
9570    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9571        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9572            Slog.w(TAG, "Unable to update from " + oldPkg.name
9573                    + " to " + newPkg.packageName
9574                    + ": old package not in system partition");
9575            return false;
9576        } else if (mPackages.get(oldPkg.name) != null) {
9577            Slog.w(TAG, "Unable to update from " + oldPkg.name
9578                    + " to " + newPkg.packageName
9579                    + ": old package still exists");
9580            return false;
9581        }
9582        return true;
9583    }
9584
9585    void removeCodePathLI(File codePath) {
9586        if (codePath.isDirectory()) {
9587            try {
9588                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9589            } catch (InstallerException e) {
9590                Slog.w(TAG, "Failed to remove code path", e);
9591            }
9592        } else {
9593            codePath.delete();
9594        }
9595    }
9596
9597    private int[] resolveUserIds(int userId) {
9598        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9599    }
9600
9601    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9602        if (pkg == null) {
9603            Slog.wtf(TAG, "Package was null!", new Throwable());
9604            return;
9605        }
9606        clearAppDataLeafLIF(pkg, userId, flags);
9607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9608        for (int i = 0; i < childCount; i++) {
9609            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9610        }
9611    }
9612
9613    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9614        final PackageSetting ps;
9615        synchronized (mPackages) {
9616            ps = mSettings.mPackages.get(pkg.packageName);
9617        }
9618        for (int realUserId : resolveUserIds(userId)) {
9619            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9620            try {
9621                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9622                        ceDataInode);
9623            } catch (InstallerException e) {
9624                Slog.w(TAG, String.valueOf(e));
9625            }
9626        }
9627    }
9628
9629    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9630        if (pkg == null) {
9631            Slog.wtf(TAG, "Package was null!", new Throwable());
9632            return;
9633        }
9634        destroyAppDataLeafLIF(pkg, userId, flags);
9635        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9636        for (int i = 0; i < childCount; i++) {
9637            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9638        }
9639    }
9640
9641    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9642        final PackageSetting ps;
9643        synchronized (mPackages) {
9644            ps = mSettings.mPackages.get(pkg.packageName);
9645        }
9646        for (int realUserId : resolveUserIds(userId)) {
9647            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9648            try {
9649                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9650                        ceDataInode);
9651            } catch (InstallerException e) {
9652                Slog.w(TAG, String.valueOf(e));
9653            }
9654            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9655        }
9656    }
9657
9658    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9659        if (pkg == null) {
9660            Slog.wtf(TAG, "Package was null!", new Throwable());
9661            return;
9662        }
9663        destroyAppProfilesLeafLIF(pkg);
9664        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9665        for (int i = 0; i < childCount; i++) {
9666            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9667        }
9668    }
9669
9670    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9671        try {
9672            mInstaller.destroyAppProfiles(pkg.packageName);
9673        } catch (InstallerException e) {
9674            Slog.w(TAG, String.valueOf(e));
9675        }
9676    }
9677
9678    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9679        if (pkg == null) {
9680            Slog.wtf(TAG, "Package was null!", new Throwable());
9681            return;
9682        }
9683        clearAppProfilesLeafLIF(pkg);
9684        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9685        for (int i = 0; i < childCount; i++) {
9686            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9687        }
9688    }
9689
9690    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9691        try {
9692            mInstaller.clearAppProfiles(pkg.packageName);
9693        } catch (InstallerException e) {
9694            Slog.w(TAG, String.valueOf(e));
9695        }
9696    }
9697
9698    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9699            long lastUpdateTime) {
9700        // Set parent install/update time
9701        PackageSetting ps = (PackageSetting) pkg.mExtras;
9702        if (ps != null) {
9703            ps.firstInstallTime = firstInstallTime;
9704            ps.lastUpdateTime = lastUpdateTime;
9705        }
9706        // Set children install/update time
9707        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9708        for (int i = 0; i < childCount; i++) {
9709            PackageParser.Package childPkg = pkg.childPackages.get(i);
9710            ps = (PackageSetting) childPkg.mExtras;
9711            if (ps != null) {
9712                ps.firstInstallTime = firstInstallTime;
9713                ps.lastUpdateTime = lastUpdateTime;
9714            }
9715        }
9716    }
9717
9718    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9719            SharedLibraryEntry file,
9720            PackageParser.Package changingLib) {
9721        if (file.path != null) {
9722            usesLibraryFiles.add(file.path);
9723            return;
9724        }
9725        PackageParser.Package p = mPackages.get(file.apk);
9726        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9727            // If we are doing this while in the middle of updating a library apk,
9728            // then we need to make sure to use that new apk for determining the
9729            // dependencies here.  (We haven't yet finished committing the new apk
9730            // to the package manager state.)
9731            if (p == null || p.packageName.equals(changingLib.packageName)) {
9732                p = changingLib;
9733            }
9734        }
9735        if (p != null) {
9736            usesLibraryFiles.addAll(p.getAllCodePaths());
9737            if (p.usesLibraryFiles != null) {
9738                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9739            }
9740        }
9741    }
9742
9743    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9744            PackageParser.Package changingLib) throws PackageManagerException {
9745        if (pkg == null) {
9746            return;
9747        }
9748        // The collection used here must maintain the order of addition (so
9749        // that libraries are searched in the correct order) and must have no
9750        // duplicates.
9751        Set<String> usesLibraryFiles = null;
9752        if (pkg.usesLibraries != null) {
9753            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9754                    null, null, pkg.packageName, changingLib, true,
9755                    pkg.applicationInfo.targetSdkVersion, null);
9756        }
9757        if (pkg.usesStaticLibraries != null) {
9758            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9759                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9760                    pkg.packageName, changingLib, true,
9761                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9762        }
9763        if (pkg.usesOptionalLibraries != null) {
9764            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9765                    null, null, pkg.packageName, changingLib, false,
9766                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9767        }
9768        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9769            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9770        } else {
9771            pkg.usesLibraryFiles = null;
9772        }
9773    }
9774
9775    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9776            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9777            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9778            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9779            throws PackageManagerException {
9780        final int libCount = requestedLibraries.size();
9781        for (int i = 0; i < libCount; i++) {
9782            final String libName = requestedLibraries.get(i);
9783            final int libVersion = requiredVersions != null ? requiredVersions[i]
9784                    : SharedLibraryInfo.VERSION_UNDEFINED;
9785            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9786            if (libEntry == null) {
9787                if (required) {
9788                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9789                            "Package " + packageName + " requires unavailable shared library "
9790                                    + libName + "; failing!");
9791                } else if (DEBUG_SHARED_LIBRARIES) {
9792                    Slog.i(TAG, "Package " + packageName
9793                            + " desires unavailable shared library "
9794                            + libName + "; ignoring!");
9795                }
9796            } else {
9797                if (requiredVersions != null && requiredCertDigests != null) {
9798                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9799                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9800                            "Package " + packageName + " requires unavailable static shared"
9801                                    + " library " + libName + " version "
9802                                    + libEntry.info.getVersion() + "; failing!");
9803                    }
9804
9805                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9806                    if (libPkg == null) {
9807                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9808                                "Package " + packageName + " requires unavailable static shared"
9809                                        + " library; failing!");
9810                    }
9811
9812                    final String[] expectedCertDigests = requiredCertDigests[i];
9813                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9814                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9815                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9816                            : PackageUtils.computeSignaturesSha256Digests(
9817                                    new Signature[]{libPkg.mSignatures[0]});
9818
9819                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9820                    // target O we don't parse the "additional-certificate" tags similarly
9821                    // how we only consider all certs only for apps targeting O (see above).
9822                    // Therefore, the size check is safe to make.
9823                    if (expectedCertDigests.length != libCertDigests.length) {
9824                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9825                                "Package " + packageName + " requires differently signed" +
9826                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9827                    }
9828
9829                    // Use a predictable order as signature order may vary
9830                    Arrays.sort(libCertDigests);
9831                    Arrays.sort(expectedCertDigests);
9832
9833                    final int certCount = libCertDigests.length;
9834                    for (int j = 0; j < certCount; j++) {
9835                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9836                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9837                                    "Package " + packageName + " requires differently signed" +
9838                                            " static shared library; failing!");
9839                        }
9840                    }
9841                }
9842
9843                if (outUsedLibraries == null) {
9844                    // Use LinkedHashSet to preserve the order of files added to
9845                    // usesLibraryFiles while eliminating duplicates.
9846                    outUsedLibraries = new LinkedHashSet<>();
9847                }
9848                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9849            }
9850        }
9851        return outUsedLibraries;
9852    }
9853
9854    private static boolean hasString(List<String> list, List<String> which) {
9855        if (list == null) {
9856            return false;
9857        }
9858        for (int i=list.size()-1; i>=0; i--) {
9859            for (int j=which.size()-1; j>=0; j--) {
9860                if (which.get(j).equals(list.get(i))) {
9861                    return true;
9862                }
9863            }
9864        }
9865        return false;
9866    }
9867
9868    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9869            PackageParser.Package changingPkg) {
9870        ArrayList<PackageParser.Package> res = null;
9871        for (PackageParser.Package pkg : mPackages.values()) {
9872            if (changingPkg != null
9873                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9874                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9875                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9876                            changingPkg.staticSharedLibName)) {
9877                return null;
9878            }
9879            if (res == null) {
9880                res = new ArrayList<>();
9881            }
9882            res.add(pkg);
9883            try {
9884                updateSharedLibrariesLPr(pkg, changingPkg);
9885            } catch (PackageManagerException e) {
9886                // If a system app update or an app and a required lib missing we
9887                // delete the package and for updated system apps keep the data as
9888                // it is better for the user to reinstall than to be in an limbo
9889                // state. Also libs disappearing under an app should never happen
9890                // - just in case.
9891                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9892                    final int flags = pkg.isUpdatedSystemApp()
9893                            ? PackageManager.DELETE_KEEP_DATA : 0;
9894                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9895                            flags , null, true, null);
9896                }
9897                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9898            }
9899        }
9900        return res;
9901    }
9902
9903    /**
9904     * Derive the value of the {@code cpuAbiOverride} based on the provided
9905     * value and an optional stored value from the package settings.
9906     */
9907    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9908        String cpuAbiOverride = null;
9909
9910        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9911            cpuAbiOverride = null;
9912        } else if (abiOverride != null) {
9913            cpuAbiOverride = abiOverride;
9914        } else if (settings != null) {
9915            cpuAbiOverride = settings.cpuAbiOverrideString;
9916        }
9917
9918        return cpuAbiOverride;
9919    }
9920
9921    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9922            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9923                    throws PackageManagerException {
9924        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9925        // If the package has children and this is the first dive in the function
9926        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9927        // whether all packages (parent and children) would be successfully scanned
9928        // before the actual scan since scanning mutates internal state and we want
9929        // to atomically install the package and its children.
9930        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9931            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9932                scanFlags |= SCAN_CHECK_ONLY;
9933            }
9934        } else {
9935            scanFlags &= ~SCAN_CHECK_ONLY;
9936        }
9937
9938        final PackageParser.Package scannedPkg;
9939        try {
9940            // Scan the parent
9941            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9942            // Scan the children
9943            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9944            for (int i = 0; i < childCount; i++) {
9945                PackageParser.Package childPkg = pkg.childPackages.get(i);
9946                scanPackageLI(childPkg, policyFlags,
9947                        scanFlags, currentTime, user);
9948            }
9949        } finally {
9950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9951        }
9952
9953        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9954            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9955        }
9956
9957        return scannedPkg;
9958    }
9959
9960    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9961            int scanFlags, long currentTime, @Nullable UserHandle user)
9962                    throws PackageManagerException {
9963        boolean success = false;
9964        try {
9965            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9966                    currentTime, user);
9967            success = true;
9968            return res;
9969        } finally {
9970            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9971                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9972                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9973                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9974                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9975            }
9976        }
9977    }
9978
9979    /**
9980     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9981     */
9982    private static boolean apkHasCode(String fileName) {
9983        StrictJarFile jarFile = null;
9984        try {
9985            jarFile = new StrictJarFile(fileName,
9986                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9987            return jarFile.findEntry("classes.dex") != null;
9988        } catch (IOException ignore) {
9989        } finally {
9990            try {
9991                if (jarFile != null) {
9992                    jarFile.close();
9993                }
9994            } catch (IOException ignore) {}
9995        }
9996        return false;
9997    }
9998
9999    /**
10000     * Enforces code policy for the package. This ensures that if an APK has
10001     * declared hasCode="true" in its manifest that the APK actually contains
10002     * code.
10003     *
10004     * @throws PackageManagerException If bytecode could not be found when it should exist
10005     */
10006    private static void assertCodePolicy(PackageParser.Package pkg)
10007            throws PackageManagerException {
10008        final boolean shouldHaveCode =
10009                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10010        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10011            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10012                    "Package " + pkg.baseCodePath + " code is missing");
10013        }
10014
10015        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10016            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10017                final boolean splitShouldHaveCode =
10018                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10019                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10020                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10021                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10022                }
10023            }
10024        }
10025    }
10026
10027    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10028            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10029                    throws PackageManagerException {
10030        if (DEBUG_PACKAGE_SCANNING) {
10031            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10032                Log.d(TAG, "Scanning package " + pkg.packageName);
10033        }
10034
10035        applyPolicy(pkg, policyFlags);
10036
10037        assertPackageIsValid(pkg, policyFlags, scanFlags);
10038
10039        if (Build.IS_DEBUGGABLE &&
10040                pkg.isPrivilegedApp() &&
10041                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10042            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10043        }
10044
10045        // Initialize package source and resource directories
10046        final File scanFile = new File(pkg.codePath);
10047        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10048        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10049
10050        SharedUserSetting suid = null;
10051        PackageSetting pkgSetting = null;
10052
10053        // Getting the package setting may have a side-effect, so if we
10054        // are only checking if scan would succeed, stash a copy of the
10055        // old setting to restore at the end.
10056        PackageSetting nonMutatedPs = null;
10057
10058        // We keep references to the derived CPU Abis from settings in oder to reuse
10059        // them in the case where we're not upgrading or booting for the first time.
10060        String primaryCpuAbiFromSettings = null;
10061        String secondaryCpuAbiFromSettings = null;
10062
10063        // writer
10064        synchronized (mPackages) {
10065            if (pkg.mSharedUserId != null) {
10066                // SIDE EFFECTS; may potentially allocate a new shared user
10067                suid = mSettings.getSharedUserLPw(
10068                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10069                if (DEBUG_PACKAGE_SCANNING) {
10070                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10071                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10072                                + "): packages=" + suid.packages);
10073                }
10074            }
10075
10076            // Check if we are renaming from an original package name.
10077            PackageSetting origPackage = null;
10078            String realName = null;
10079            if (pkg.mOriginalPackages != null) {
10080                // This package may need to be renamed to a previously
10081                // installed name.  Let's check on that...
10082                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10083                if (pkg.mOriginalPackages.contains(renamed)) {
10084                    // This package had originally been installed as the
10085                    // original name, and we have already taken care of
10086                    // transitioning to the new one.  Just update the new
10087                    // one to continue using the old name.
10088                    realName = pkg.mRealPackage;
10089                    if (!pkg.packageName.equals(renamed)) {
10090                        // Callers into this function may have already taken
10091                        // care of renaming the package; only do it here if
10092                        // it is not already done.
10093                        pkg.setPackageName(renamed);
10094                    }
10095                } else {
10096                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10097                        if ((origPackage = mSettings.getPackageLPr(
10098                                pkg.mOriginalPackages.get(i))) != null) {
10099                            // We do have the package already installed under its
10100                            // original name...  should we use it?
10101                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10102                                // New package is not compatible with original.
10103                                origPackage = null;
10104                                continue;
10105                            } else if (origPackage.sharedUser != null) {
10106                                // Make sure uid is compatible between packages.
10107                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10108                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10109                                            + " to " + pkg.packageName + ": old uid "
10110                                            + origPackage.sharedUser.name
10111                                            + " differs from " + pkg.mSharedUserId);
10112                                    origPackage = null;
10113                                    continue;
10114                                }
10115                                // TODO: Add case when shared user id is added [b/28144775]
10116                            } else {
10117                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10118                                        + pkg.packageName + " to old name " + origPackage.name);
10119                            }
10120                            break;
10121                        }
10122                    }
10123                }
10124            }
10125
10126            if (mTransferedPackages.contains(pkg.packageName)) {
10127                Slog.w(TAG, "Package " + pkg.packageName
10128                        + " was transferred to another, but its .apk remains");
10129            }
10130
10131            // See comments in nonMutatedPs declaration
10132            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10133                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10134                if (foundPs != null) {
10135                    nonMutatedPs = new PackageSetting(foundPs);
10136                }
10137            }
10138
10139            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10140                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10141                if (foundPs != null) {
10142                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10143                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10144                }
10145            }
10146
10147            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10148            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10149                PackageManagerService.reportSettingsProblem(Log.WARN,
10150                        "Package " + pkg.packageName + " shared user changed from "
10151                                + (pkgSetting.sharedUser != null
10152                                        ? pkgSetting.sharedUser.name : "<nothing>")
10153                                + " to "
10154                                + (suid != null ? suid.name : "<nothing>")
10155                                + "; replacing with new");
10156                pkgSetting = null;
10157            }
10158            final PackageSetting oldPkgSetting =
10159                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10160            final PackageSetting disabledPkgSetting =
10161                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10162
10163            String[] usesStaticLibraries = null;
10164            if (pkg.usesStaticLibraries != null) {
10165                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10166                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10167            }
10168
10169            if (pkgSetting == null) {
10170                final String parentPackageName = (pkg.parentPackage != null)
10171                        ? pkg.parentPackage.packageName : null;
10172                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10173                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10174                // REMOVE SharedUserSetting from method; update in a separate call
10175                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10176                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10177                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10178                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10179                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10180                        true /*allowInstall*/, instantApp, virtualPreload,
10181                        parentPackageName, pkg.getChildPackageNames(),
10182                        UserManagerService.getInstance(), usesStaticLibraries,
10183                        pkg.usesStaticLibrariesVersions);
10184                // SIDE EFFECTS; updates system state; move elsewhere
10185                if (origPackage != null) {
10186                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10187                }
10188                mSettings.addUserToSettingLPw(pkgSetting);
10189            } else {
10190                // REMOVE SharedUserSetting from method; update in a separate call.
10191                //
10192                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10193                // secondaryCpuAbi are not known at this point so we always update them
10194                // to null here, only to reset them at a later point.
10195                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10196                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10197                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10198                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10199                        UserManagerService.getInstance(), usesStaticLibraries,
10200                        pkg.usesStaticLibrariesVersions);
10201            }
10202            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10203            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10204
10205            // SIDE EFFECTS; modifies system state; move elsewhere
10206            if (pkgSetting.origPackage != null) {
10207                // If we are first transitioning from an original package,
10208                // fix up the new package's name now.  We need to do this after
10209                // looking up the package under its new name, so getPackageLP
10210                // can take care of fiddling things correctly.
10211                pkg.setPackageName(origPackage.name);
10212
10213                // File a report about this.
10214                String msg = "New package " + pkgSetting.realName
10215                        + " renamed to replace old package " + pkgSetting.name;
10216                reportSettingsProblem(Log.WARN, msg);
10217
10218                // Make a note of it.
10219                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10220                    mTransferedPackages.add(origPackage.name);
10221                }
10222
10223                // No longer need to retain this.
10224                pkgSetting.origPackage = null;
10225            }
10226
10227            // SIDE EFFECTS; modifies system state; move elsewhere
10228            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10229                // Make a note of it.
10230                mTransferedPackages.add(pkg.packageName);
10231            }
10232
10233            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10234                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10235            }
10236
10237            if ((scanFlags & SCAN_BOOTING) == 0
10238                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10239                // Check all shared libraries and map to their actual file path.
10240                // We only do this here for apps not on a system dir, because those
10241                // are the only ones that can fail an install due to this.  We
10242                // will take care of the system apps by updating all of their
10243                // library paths after the scan is done. Also during the initial
10244                // scan don't update any libs as we do this wholesale after all
10245                // apps are scanned to avoid dependency based scanning.
10246                updateSharedLibrariesLPr(pkg, null);
10247            }
10248
10249            if (mFoundPolicyFile) {
10250                SELinuxMMAC.assignSeInfoValue(pkg);
10251            }
10252            pkg.applicationInfo.uid = pkgSetting.appId;
10253            pkg.mExtras = pkgSetting;
10254
10255
10256            // Static shared libs have same package with different versions where
10257            // we internally use a synthetic package name to allow multiple versions
10258            // of the same package, therefore we need to compare signatures against
10259            // the package setting for the latest library version.
10260            PackageSetting signatureCheckPs = pkgSetting;
10261            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10262                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10263                if (libraryEntry != null) {
10264                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10265                }
10266            }
10267
10268            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10269                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10270                    // We just determined the app is signed correctly, so bring
10271                    // over the latest parsed certs.
10272                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10273                } else {
10274                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10275                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10276                                "Package " + pkg.packageName + " upgrade keys do not match the "
10277                                + "previously installed version");
10278                    } else {
10279                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10280                        String msg = "System package " + pkg.packageName
10281                                + " signature changed; retaining data.";
10282                        reportSettingsProblem(Log.WARN, msg);
10283                    }
10284                }
10285            } else {
10286                try {
10287                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10288                    verifySignaturesLP(signatureCheckPs, pkg);
10289                    // We just determined the app is signed correctly, so bring
10290                    // over the latest parsed certs.
10291                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10292                } catch (PackageManagerException e) {
10293                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10294                        throw e;
10295                    }
10296                    // The signature has changed, but this package is in the system
10297                    // image...  let's recover!
10298                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10299                    // However...  if this package is part of a shared user, but it
10300                    // doesn't match the signature of the shared user, let's fail.
10301                    // What this means is that you can't change the signatures
10302                    // associated with an overall shared user, which doesn't seem all
10303                    // that unreasonable.
10304                    if (signatureCheckPs.sharedUser != null) {
10305                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10306                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10307                            throw new PackageManagerException(
10308                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10309                                    "Signature mismatch for shared user: "
10310                                            + pkgSetting.sharedUser);
10311                        }
10312                    }
10313                    // File a report about this.
10314                    String msg = "System package " + pkg.packageName
10315                            + " signature changed; retaining data.";
10316                    reportSettingsProblem(Log.WARN, msg);
10317                }
10318            }
10319
10320            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10321                // This package wants to adopt ownership of permissions from
10322                // another package.
10323                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10324                    final String origName = pkg.mAdoptPermissions.get(i);
10325                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10326                    if (orig != null) {
10327                        if (verifyPackageUpdateLPr(orig, pkg)) {
10328                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10329                                    + pkg.packageName);
10330                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10331                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10332                        }
10333                    }
10334                }
10335            }
10336        }
10337
10338        pkg.applicationInfo.processName = fixProcessName(
10339                pkg.applicationInfo.packageName,
10340                pkg.applicationInfo.processName);
10341
10342        if (pkg != mPlatformPackage) {
10343            // Get all of our default paths setup
10344            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10345        }
10346
10347        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10348
10349        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10350            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10351                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10352                final boolean extractNativeLibs = !pkg.isLibrary();
10353                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10354                        mAppLib32InstallDir);
10355                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10356
10357                // Some system apps still use directory structure for native libraries
10358                // in which case we might end up not detecting abi solely based on apk
10359                // structure. Try to detect abi based on directory structure.
10360                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10361                        pkg.applicationInfo.primaryCpuAbi == null) {
10362                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10363                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10364                }
10365            } else {
10366                // This is not a first boot or an upgrade, don't bother deriving the
10367                // ABI during the scan. Instead, trust the value that was stored in the
10368                // package setting.
10369                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10370                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10371
10372                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10373
10374                if (DEBUG_ABI_SELECTION) {
10375                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10376                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10377                        pkg.applicationInfo.secondaryCpuAbi);
10378                }
10379            }
10380        } else {
10381            if ((scanFlags & SCAN_MOVE) != 0) {
10382                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10383                // but we already have this packages package info in the PackageSetting. We just
10384                // use that and derive the native library path based on the new codepath.
10385                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10386                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10387            }
10388
10389            // Set native library paths again. For moves, the path will be updated based on the
10390            // ABIs we've determined above. For non-moves, the path will be updated based on the
10391            // ABIs we determined during compilation, but the path will depend on the final
10392            // package path (after the rename away from the stage path).
10393            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10394        }
10395
10396        // This is a special case for the "system" package, where the ABI is
10397        // dictated by the zygote configuration (and init.rc). We should keep track
10398        // of this ABI so that we can deal with "normal" applications that run under
10399        // the same UID correctly.
10400        if (mPlatformPackage == pkg) {
10401            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10402                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10403        }
10404
10405        // If there's a mismatch between the abi-override in the package setting
10406        // and the abiOverride specified for the install. Warn about this because we
10407        // would've already compiled the app without taking the package setting into
10408        // account.
10409        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10410            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10411                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10412                        " for package " + pkg.packageName);
10413            }
10414        }
10415
10416        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10417        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10418        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10419
10420        // Copy the derived override back to the parsed package, so that we can
10421        // update the package settings accordingly.
10422        pkg.cpuAbiOverride = cpuAbiOverride;
10423
10424        if (DEBUG_ABI_SELECTION) {
10425            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10426                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10427                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10428        }
10429
10430        // Push the derived path down into PackageSettings so we know what to
10431        // clean up at uninstall time.
10432        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10433
10434        if (DEBUG_ABI_SELECTION) {
10435            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10436                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10437                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10438        }
10439
10440        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10441        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10442            // We don't do this here during boot because we can do it all
10443            // at once after scanning all existing packages.
10444            //
10445            // We also do this *before* we perform dexopt on this package, so that
10446            // we can avoid redundant dexopts, and also to make sure we've got the
10447            // code and package path correct.
10448            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10449        }
10450
10451        if (mFactoryTest && pkg.requestedPermissions.contains(
10452                android.Manifest.permission.FACTORY_TEST)) {
10453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10454        }
10455
10456        if (isSystemApp(pkg)) {
10457            pkgSetting.isOrphaned = true;
10458        }
10459
10460        // Take care of first install / last update times.
10461        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10462        if (currentTime != 0) {
10463            if (pkgSetting.firstInstallTime == 0) {
10464                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10465            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10466                pkgSetting.lastUpdateTime = currentTime;
10467            }
10468        } else if (pkgSetting.firstInstallTime == 0) {
10469            // We need *something*.  Take time time stamp of the file.
10470            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10471        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10472            if (scanFileTime != pkgSetting.timeStamp) {
10473                // A package on the system image has changed; consider this
10474                // to be an update.
10475                pkgSetting.lastUpdateTime = scanFileTime;
10476            }
10477        }
10478        pkgSetting.setTimeStamp(scanFileTime);
10479
10480        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10481            if (nonMutatedPs != null) {
10482                synchronized (mPackages) {
10483                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10484                }
10485            }
10486        } else {
10487            final int userId = user == null ? 0 : user.getIdentifier();
10488            // Modify state for the given package setting
10489            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10490                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10491            if (pkgSetting.getInstantApp(userId)) {
10492                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10493            }
10494        }
10495        return pkg;
10496    }
10497
10498    /**
10499     * Applies policy to the parsed package based upon the given policy flags.
10500     * Ensures the package is in a good state.
10501     * <p>
10502     * Implementation detail: This method must NOT have any side effect. It would
10503     * ideally be static, but, it requires locks to read system state.
10504     */
10505    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10506        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10507            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10508            if (pkg.applicationInfo.isDirectBootAware()) {
10509                // we're direct boot aware; set for all components
10510                for (PackageParser.Service s : pkg.services) {
10511                    s.info.encryptionAware = s.info.directBootAware = true;
10512                }
10513                for (PackageParser.Provider p : pkg.providers) {
10514                    p.info.encryptionAware = p.info.directBootAware = true;
10515                }
10516                for (PackageParser.Activity a : pkg.activities) {
10517                    a.info.encryptionAware = a.info.directBootAware = true;
10518                }
10519                for (PackageParser.Activity r : pkg.receivers) {
10520                    r.info.encryptionAware = r.info.directBootAware = true;
10521                }
10522            }
10523            if (compressedFileExists(pkg.codePath)) {
10524                pkg.isStub = true;
10525            }
10526        } else {
10527            // Only allow system apps to be flagged as core apps.
10528            pkg.coreApp = false;
10529            // clear flags not applicable to regular apps
10530            pkg.applicationInfo.privateFlags &=
10531                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10532            pkg.applicationInfo.privateFlags &=
10533                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10534        }
10535        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10536
10537        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10538            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10539        }
10540
10541        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10542            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10543        }
10544
10545        if (!isSystemApp(pkg)) {
10546            // Only system apps can use these features.
10547            pkg.mOriginalPackages = null;
10548            pkg.mRealPackage = null;
10549            pkg.mAdoptPermissions = null;
10550        }
10551    }
10552
10553    /**
10554     * Asserts the parsed package is valid according to the given policy. If the
10555     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10556     * <p>
10557     * Implementation detail: This method must NOT have any side effects. It would
10558     * ideally be static, but, it requires locks to read system state.
10559     *
10560     * @throws PackageManagerException If the package fails any of the validation checks
10561     */
10562    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10563            throws PackageManagerException {
10564        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10565            assertCodePolicy(pkg);
10566        }
10567
10568        if (pkg.applicationInfo.getCodePath() == null ||
10569                pkg.applicationInfo.getResourcePath() == null) {
10570            // Bail out. The resource and code paths haven't been set.
10571            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10572                    "Code and resource paths haven't been set correctly");
10573        }
10574
10575        // Make sure we're not adding any bogus keyset info
10576        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10577        ksms.assertScannedPackageValid(pkg);
10578
10579        synchronized (mPackages) {
10580            // The special "android" package can only be defined once
10581            if (pkg.packageName.equals("android")) {
10582                if (mAndroidApplication != null) {
10583                    Slog.w(TAG, "*************************************************");
10584                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10585                    Slog.w(TAG, " codePath=" + pkg.codePath);
10586                    Slog.w(TAG, "*************************************************");
10587                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10588                            "Core android package being redefined.  Skipping.");
10589                }
10590            }
10591
10592            // A package name must be unique; don't allow duplicates
10593            if (mPackages.containsKey(pkg.packageName)) {
10594                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10595                        "Application package " + pkg.packageName
10596                        + " already installed.  Skipping duplicate.");
10597            }
10598
10599            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10600                // Static libs have a synthetic package name containing the version
10601                // but we still want the base name to be unique.
10602                if (mPackages.containsKey(pkg.manifestPackageName)) {
10603                    throw new PackageManagerException(
10604                            "Duplicate static shared lib provider package");
10605                }
10606
10607                // Static shared libraries should have at least O target SDK
10608                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10609                    throw new PackageManagerException(
10610                            "Packages declaring static-shared libs must target O SDK or higher");
10611                }
10612
10613                // Package declaring static a shared lib cannot be instant apps
10614                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10615                    throw new PackageManagerException(
10616                            "Packages declaring static-shared libs cannot be instant apps");
10617                }
10618
10619                // Package declaring static a shared lib cannot be renamed since the package
10620                // name is synthetic and apps can't code around package manager internals.
10621                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10622                    throw new PackageManagerException(
10623                            "Packages declaring static-shared libs cannot be renamed");
10624                }
10625
10626                // Package declaring static a shared lib cannot declare child packages
10627                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10628                    throw new PackageManagerException(
10629                            "Packages declaring static-shared libs cannot have child packages");
10630                }
10631
10632                // Package declaring static a shared lib cannot declare dynamic libs
10633                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10634                    throw new PackageManagerException(
10635                            "Packages declaring static-shared libs cannot declare dynamic libs");
10636                }
10637
10638                // Package declaring static a shared lib cannot declare shared users
10639                if (pkg.mSharedUserId != null) {
10640                    throw new PackageManagerException(
10641                            "Packages declaring static-shared libs cannot declare shared users");
10642                }
10643
10644                // Static shared libs cannot declare activities
10645                if (!pkg.activities.isEmpty()) {
10646                    throw new PackageManagerException(
10647                            "Static shared libs cannot declare activities");
10648                }
10649
10650                // Static shared libs cannot declare services
10651                if (!pkg.services.isEmpty()) {
10652                    throw new PackageManagerException(
10653                            "Static shared libs cannot declare services");
10654                }
10655
10656                // Static shared libs cannot declare providers
10657                if (!pkg.providers.isEmpty()) {
10658                    throw new PackageManagerException(
10659                            "Static shared libs cannot declare content providers");
10660                }
10661
10662                // Static shared libs cannot declare receivers
10663                if (!pkg.receivers.isEmpty()) {
10664                    throw new PackageManagerException(
10665                            "Static shared libs cannot declare broadcast receivers");
10666                }
10667
10668                // Static shared libs cannot declare permission groups
10669                if (!pkg.permissionGroups.isEmpty()) {
10670                    throw new PackageManagerException(
10671                            "Static shared libs cannot declare permission groups");
10672                }
10673
10674                // Static shared libs cannot declare permissions
10675                if (!pkg.permissions.isEmpty()) {
10676                    throw new PackageManagerException(
10677                            "Static shared libs cannot declare permissions");
10678                }
10679
10680                // Static shared libs cannot declare protected broadcasts
10681                if (pkg.protectedBroadcasts != null) {
10682                    throw new PackageManagerException(
10683                            "Static shared libs cannot declare protected broadcasts");
10684                }
10685
10686                // Static shared libs cannot be overlay targets
10687                if (pkg.mOverlayTarget != null) {
10688                    throw new PackageManagerException(
10689                            "Static shared libs cannot be overlay targets");
10690                }
10691
10692                // The version codes must be ordered as lib versions
10693                int minVersionCode = Integer.MIN_VALUE;
10694                int maxVersionCode = Integer.MAX_VALUE;
10695
10696                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10697                        pkg.staticSharedLibName);
10698                if (versionedLib != null) {
10699                    final int versionCount = versionedLib.size();
10700                    for (int i = 0; i < versionCount; i++) {
10701                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10702                        final int libVersionCode = libInfo.getDeclaringPackage()
10703                                .getVersionCode();
10704                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10705                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10706                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10707                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10708                        } else {
10709                            minVersionCode = maxVersionCode = libVersionCode;
10710                            break;
10711                        }
10712                    }
10713                }
10714                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10715                    throw new PackageManagerException("Static shared"
10716                            + " lib version codes must be ordered as lib versions");
10717                }
10718            }
10719
10720            // Only privileged apps and updated privileged apps can add child packages.
10721            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10722                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10723                    throw new PackageManagerException("Only privileged apps can add child "
10724                            + "packages. Ignoring package " + pkg.packageName);
10725                }
10726                final int childCount = pkg.childPackages.size();
10727                for (int i = 0; i < childCount; i++) {
10728                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10729                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10730                            childPkg.packageName)) {
10731                        throw new PackageManagerException("Can't override child of "
10732                                + "another disabled app. Ignoring package " + pkg.packageName);
10733                    }
10734                }
10735            }
10736
10737            // If we're only installing presumed-existing packages, require that the
10738            // scanned APK is both already known and at the path previously established
10739            // for it.  Previously unknown packages we pick up normally, but if we have an
10740            // a priori expectation about this package's install presence, enforce it.
10741            // With a singular exception for new system packages. When an OTA contains
10742            // a new system package, we allow the codepath to change from a system location
10743            // to the user-installed location. If we don't allow this change, any newer,
10744            // user-installed version of the application will be ignored.
10745            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10746                if (mExpectingBetter.containsKey(pkg.packageName)) {
10747                    logCriticalInfo(Log.WARN,
10748                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10749                } else {
10750                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10751                    if (known != null) {
10752                        if (DEBUG_PACKAGE_SCANNING) {
10753                            Log.d(TAG, "Examining " + pkg.codePath
10754                                    + " and requiring known paths " + known.codePathString
10755                                    + " & " + known.resourcePathString);
10756                        }
10757                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10758                                || !pkg.applicationInfo.getResourcePath().equals(
10759                                        known.resourcePathString)) {
10760                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10761                                    "Application package " + pkg.packageName
10762                                    + " found at " + pkg.applicationInfo.getCodePath()
10763                                    + " but expected at " + known.codePathString
10764                                    + "; ignoring.");
10765                        }
10766                    } else {
10767                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10768                                "Application package " + pkg.packageName
10769                                + " not found; ignoring.");
10770                    }
10771                }
10772            }
10773
10774            // Verify that this new package doesn't have any content providers
10775            // that conflict with existing packages.  Only do this if the
10776            // package isn't already installed, since we don't want to break
10777            // things that are installed.
10778            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10779                final int N = pkg.providers.size();
10780                int i;
10781                for (i=0; i<N; i++) {
10782                    PackageParser.Provider p = pkg.providers.get(i);
10783                    if (p.info.authority != null) {
10784                        String names[] = p.info.authority.split(";");
10785                        for (int j = 0; j < names.length; j++) {
10786                            if (mProvidersByAuthority.containsKey(names[j])) {
10787                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10788                                final String otherPackageName =
10789                                        ((other != null && other.getComponentName() != null) ?
10790                                                other.getComponentName().getPackageName() : "?");
10791                                throw new PackageManagerException(
10792                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10793                                        "Can't install because provider name " + names[j]
10794                                                + " (in package " + pkg.applicationInfo.packageName
10795                                                + ") is already used by " + otherPackageName);
10796                            }
10797                        }
10798                    }
10799                }
10800            }
10801        }
10802    }
10803
10804    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10805            int type, String declaringPackageName, int declaringVersionCode) {
10806        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10807        if (versionedLib == null) {
10808            versionedLib = new SparseArray<>();
10809            mSharedLibraries.put(name, versionedLib);
10810            if (type == SharedLibraryInfo.TYPE_STATIC) {
10811                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10812            }
10813        } else if (versionedLib.indexOfKey(version) >= 0) {
10814            return false;
10815        }
10816        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10817                version, type, declaringPackageName, declaringVersionCode);
10818        versionedLib.put(version, libEntry);
10819        return true;
10820    }
10821
10822    private boolean removeSharedLibraryLPw(String name, int version) {
10823        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10824        if (versionedLib == null) {
10825            return false;
10826        }
10827        final int libIdx = versionedLib.indexOfKey(version);
10828        if (libIdx < 0) {
10829            return false;
10830        }
10831        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10832        versionedLib.remove(version);
10833        if (versionedLib.size() <= 0) {
10834            mSharedLibraries.remove(name);
10835            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10836                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10837                        .getPackageName());
10838            }
10839        }
10840        return true;
10841    }
10842
10843    /**
10844     * Adds a scanned package to the system. When this method is finished, the package will
10845     * be available for query, resolution, etc...
10846     */
10847    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10848            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10849        final String pkgName = pkg.packageName;
10850        if (mCustomResolverComponentName != null &&
10851                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10852            setUpCustomResolverActivity(pkg);
10853        }
10854
10855        if (pkg.packageName.equals("android")) {
10856            synchronized (mPackages) {
10857                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10858                    // Set up information for our fall-back user intent resolution activity.
10859                    mPlatformPackage = pkg;
10860                    pkg.mVersionCode = mSdkVersion;
10861                    mAndroidApplication = pkg.applicationInfo;
10862                    if (!mResolverReplaced) {
10863                        mResolveActivity.applicationInfo = mAndroidApplication;
10864                        mResolveActivity.name = ResolverActivity.class.getName();
10865                        mResolveActivity.packageName = mAndroidApplication.packageName;
10866                        mResolveActivity.processName = "system:ui";
10867                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10868                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10869                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10870                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10871                        mResolveActivity.exported = true;
10872                        mResolveActivity.enabled = true;
10873                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10874                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10875                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10876                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10877                                | ActivityInfo.CONFIG_ORIENTATION
10878                                | ActivityInfo.CONFIG_KEYBOARD
10879                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10880                        mResolveInfo.activityInfo = mResolveActivity;
10881                        mResolveInfo.priority = 0;
10882                        mResolveInfo.preferredOrder = 0;
10883                        mResolveInfo.match = 0;
10884                        mResolveComponentName = new ComponentName(
10885                                mAndroidApplication.packageName, mResolveActivity.name);
10886                    }
10887                }
10888            }
10889        }
10890
10891        ArrayList<PackageParser.Package> clientLibPkgs = null;
10892        // writer
10893        synchronized (mPackages) {
10894            boolean hasStaticSharedLibs = false;
10895
10896            // Any app can add new static shared libraries
10897            if (pkg.staticSharedLibName != null) {
10898                // Static shared libs don't allow renaming as they have synthetic package
10899                // names to allow install of multiple versions, so use name from manifest.
10900                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10901                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10902                        pkg.manifestPackageName, pkg.mVersionCode)) {
10903                    hasStaticSharedLibs = true;
10904                } else {
10905                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10906                                + pkg.staticSharedLibName + " already exists; skipping");
10907                }
10908                // Static shared libs cannot be updated once installed since they
10909                // use synthetic package name which includes the version code, so
10910                // not need to update other packages's shared lib dependencies.
10911            }
10912
10913            if (!hasStaticSharedLibs
10914                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10915                // Only system apps can add new dynamic shared libraries.
10916                if (pkg.libraryNames != null) {
10917                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10918                        String name = pkg.libraryNames.get(i);
10919                        boolean allowed = false;
10920                        if (pkg.isUpdatedSystemApp()) {
10921                            // New library entries can only be added through the
10922                            // system image.  This is important to get rid of a lot
10923                            // of nasty edge cases: for example if we allowed a non-
10924                            // system update of the app to add a library, then uninstalling
10925                            // the update would make the library go away, and assumptions
10926                            // we made such as through app install filtering would now
10927                            // have allowed apps on the device which aren't compatible
10928                            // with it.  Better to just have the restriction here, be
10929                            // conservative, and create many fewer cases that can negatively
10930                            // impact the user experience.
10931                            final PackageSetting sysPs = mSettings
10932                                    .getDisabledSystemPkgLPr(pkg.packageName);
10933                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10934                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10935                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10936                                        allowed = true;
10937                                        break;
10938                                    }
10939                                }
10940                            }
10941                        } else {
10942                            allowed = true;
10943                        }
10944                        if (allowed) {
10945                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10946                                    SharedLibraryInfo.VERSION_UNDEFINED,
10947                                    SharedLibraryInfo.TYPE_DYNAMIC,
10948                                    pkg.packageName, pkg.mVersionCode)) {
10949                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10950                                        + name + " already exists; skipping");
10951                            }
10952                        } else {
10953                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10954                                    + name + " that is not declared on system image; skipping");
10955                        }
10956                    }
10957
10958                    if ((scanFlags & SCAN_BOOTING) == 0) {
10959                        // If we are not booting, we need to update any applications
10960                        // that are clients of our shared library.  If we are booting,
10961                        // this will all be done once the scan is complete.
10962                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10963                    }
10964                }
10965            }
10966        }
10967
10968        if ((scanFlags & SCAN_BOOTING) != 0) {
10969            // No apps can run during boot scan, so they don't need to be frozen
10970        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10971            // Caller asked to not kill app, so it's probably not frozen
10972        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10973            // Caller asked us to ignore frozen check for some reason; they
10974            // probably didn't know the package name
10975        } else {
10976            // We're doing major surgery on this package, so it better be frozen
10977            // right now to keep it from launching
10978            checkPackageFrozen(pkgName);
10979        }
10980
10981        // Also need to kill any apps that are dependent on the library.
10982        if (clientLibPkgs != null) {
10983            for (int i=0; i<clientLibPkgs.size(); i++) {
10984                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10985                killApplication(clientPkg.applicationInfo.packageName,
10986                        clientPkg.applicationInfo.uid, "update lib");
10987            }
10988        }
10989
10990        // writer
10991        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10992
10993        synchronized (mPackages) {
10994            // We don't expect installation to fail beyond this point
10995
10996            // Add the new setting to mSettings
10997            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10998            // Add the new setting to mPackages
10999            mPackages.put(pkg.applicationInfo.packageName, pkg);
11000            // Make sure we don't accidentally delete its data.
11001            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11002            while (iter.hasNext()) {
11003                PackageCleanItem item = iter.next();
11004                if (pkgName.equals(item.packageName)) {
11005                    iter.remove();
11006                }
11007            }
11008
11009            // Add the package's KeySets to the global KeySetManagerService
11010            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11011            ksms.addScannedPackageLPw(pkg);
11012
11013            int N = pkg.providers.size();
11014            StringBuilder r = null;
11015            int i;
11016            for (i=0; i<N; i++) {
11017                PackageParser.Provider p = pkg.providers.get(i);
11018                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11019                        p.info.processName);
11020                mProviders.addProvider(p);
11021                p.syncable = p.info.isSyncable;
11022                if (p.info.authority != null) {
11023                    String names[] = p.info.authority.split(";");
11024                    p.info.authority = null;
11025                    for (int j = 0; j < names.length; j++) {
11026                        if (j == 1 && p.syncable) {
11027                            // We only want the first authority for a provider to possibly be
11028                            // syncable, so if we already added this provider using a different
11029                            // authority clear the syncable flag. We copy the provider before
11030                            // changing it because the mProviders object contains a reference
11031                            // to a provider that we don't want to change.
11032                            // Only do this for the second authority since the resulting provider
11033                            // object can be the same for all future authorities for this provider.
11034                            p = new PackageParser.Provider(p);
11035                            p.syncable = false;
11036                        }
11037                        if (!mProvidersByAuthority.containsKey(names[j])) {
11038                            mProvidersByAuthority.put(names[j], p);
11039                            if (p.info.authority == null) {
11040                                p.info.authority = names[j];
11041                            } else {
11042                                p.info.authority = p.info.authority + ";" + names[j];
11043                            }
11044                            if (DEBUG_PACKAGE_SCANNING) {
11045                                if (chatty)
11046                                    Log.d(TAG, "Registered content provider: " + names[j]
11047                                            + ", className = " + p.info.name + ", isSyncable = "
11048                                            + p.info.isSyncable);
11049                            }
11050                        } else {
11051                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11052                            Slog.w(TAG, "Skipping provider name " + names[j] +
11053                                    " (in package " + pkg.applicationInfo.packageName +
11054                                    "): name already used by "
11055                                    + ((other != null && other.getComponentName() != null)
11056                                            ? other.getComponentName().getPackageName() : "?"));
11057                        }
11058                    }
11059                }
11060                if (chatty) {
11061                    if (r == null) {
11062                        r = new StringBuilder(256);
11063                    } else {
11064                        r.append(' ');
11065                    }
11066                    r.append(p.info.name);
11067                }
11068            }
11069            if (r != null) {
11070                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11071            }
11072
11073            N = pkg.services.size();
11074            r = null;
11075            for (i=0; i<N; i++) {
11076                PackageParser.Service s = pkg.services.get(i);
11077                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11078                        s.info.processName);
11079                mServices.addService(s);
11080                if (chatty) {
11081                    if (r == null) {
11082                        r = new StringBuilder(256);
11083                    } else {
11084                        r.append(' ');
11085                    }
11086                    r.append(s.info.name);
11087                }
11088            }
11089            if (r != null) {
11090                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11091            }
11092
11093            N = pkg.receivers.size();
11094            r = null;
11095            for (i=0; i<N; i++) {
11096                PackageParser.Activity a = pkg.receivers.get(i);
11097                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11098                        a.info.processName);
11099                mReceivers.addActivity(a, "receiver");
11100                if (chatty) {
11101                    if (r == null) {
11102                        r = new StringBuilder(256);
11103                    } else {
11104                        r.append(' ');
11105                    }
11106                    r.append(a.info.name);
11107                }
11108            }
11109            if (r != null) {
11110                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11111            }
11112
11113            N = pkg.activities.size();
11114            r = null;
11115            for (i=0; i<N; i++) {
11116                PackageParser.Activity a = pkg.activities.get(i);
11117                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11118                        a.info.processName);
11119                mActivities.addActivity(a, "activity");
11120                if (chatty) {
11121                    if (r == null) {
11122                        r = new StringBuilder(256);
11123                    } else {
11124                        r.append(' ');
11125                    }
11126                    r.append(a.info.name);
11127                }
11128            }
11129            if (r != null) {
11130                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11131            }
11132
11133            // Don't allow ephemeral applications to define new permissions groups.
11134            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11135                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11136                        + " ignored: instant apps cannot define new permission groups.");
11137            } else {
11138                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11139            }
11140
11141            // Don't allow ephemeral applications to define new permissions.
11142            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11143                Slog.w(TAG, "Permissions from package " + pkg.packageName
11144                        + " ignored: instant apps cannot define new permissions.");
11145            } else {
11146                mPermissionManager.addAllPermissions(pkg, chatty);
11147            }
11148
11149            N = pkg.instrumentation.size();
11150            r = null;
11151            for (i=0; i<N; i++) {
11152                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11153                a.info.packageName = pkg.applicationInfo.packageName;
11154                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11155                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11156                a.info.splitNames = pkg.splitNames;
11157                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11158                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11159                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11160                a.info.dataDir = pkg.applicationInfo.dataDir;
11161                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11162                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11163                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11164                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11165                mInstrumentation.put(a.getComponentName(), a);
11166                if (chatty) {
11167                    if (r == null) {
11168                        r = new StringBuilder(256);
11169                    } else {
11170                        r.append(' ');
11171                    }
11172                    r.append(a.info.name);
11173                }
11174            }
11175            if (r != null) {
11176                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11177            }
11178
11179            if (pkg.protectedBroadcasts != null) {
11180                N = pkg.protectedBroadcasts.size();
11181                synchronized (mProtectedBroadcasts) {
11182                    for (i = 0; i < N; i++) {
11183                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11184                    }
11185                }
11186            }
11187        }
11188
11189        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11190    }
11191
11192    /**
11193     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11194     * is derived purely on the basis of the contents of {@code scanFile} and
11195     * {@code cpuAbiOverride}.
11196     *
11197     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11198     */
11199    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11200                                 String cpuAbiOverride, boolean extractLibs,
11201                                 File appLib32InstallDir)
11202            throws PackageManagerException {
11203        // Give ourselves some initial paths; we'll come back for another
11204        // pass once we've determined ABI below.
11205        setNativeLibraryPaths(pkg, appLib32InstallDir);
11206
11207        // We would never need to extract libs for forward-locked and external packages,
11208        // since the container service will do it for us. We shouldn't attempt to
11209        // extract libs from system app when it was not updated.
11210        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11211                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11212            extractLibs = false;
11213        }
11214
11215        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11216        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11217
11218        NativeLibraryHelper.Handle handle = null;
11219        try {
11220            handle = NativeLibraryHelper.Handle.create(pkg);
11221            // TODO(multiArch): This can be null for apps that didn't go through the
11222            // usual installation process. We can calculate it again, like we
11223            // do during install time.
11224            //
11225            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11226            // unnecessary.
11227            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11228
11229            // Null out the abis so that they can be recalculated.
11230            pkg.applicationInfo.primaryCpuAbi = null;
11231            pkg.applicationInfo.secondaryCpuAbi = null;
11232            if (isMultiArch(pkg.applicationInfo)) {
11233                // Warn if we've set an abiOverride for multi-lib packages..
11234                // By definition, we need to copy both 32 and 64 bit libraries for
11235                // such packages.
11236                if (pkg.cpuAbiOverride != null
11237                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11238                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11239                }
11240
11241                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11242                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11243                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11244                    if (extractLibs) {
11245                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11246                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11247                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11248                                useIsaSpecificSubdirs);
11249                    } else {
11250                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11251                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11252                    }
11253                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11254                }
11255
11256                // Shared library native code should be in the APK zip aligned
11257                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11258                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11259                            "Shared library native lib extraction not supported");
11260                }
11261
11262                maybeThrowExceptionForMultiArchCopy(
11263                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11264
11265                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11266                    if (extractLibs) {
11267                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11268                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11269                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11270                                useIsaSpecificSubdirs);
11271                    } else {
11272                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11273                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11274                    }
11275                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11276                }
11277
11278                maybeThrowExceptionForMultiArchCopy(
11279                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11280
11281                if (abi64 >= 0) {
11282                    // Shared library native libs should be in the APK zip aligned
11283                    if (extractLibs && pkg.isLibrary()) {
11284                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11285                                "Shared library native lib extraction not supported");
11286                    }
11287                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11288                }
11289
11290                if (abi32 >= 0) {
11291                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11292                    if (abi64 >= 0) {
11293                        if (pkg.use32bitAbi) {
11294                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11295                            pkg.applicationInfo.primaryCpuAbi = abi;
11296                        } else {
11297                            pkg.applicationInfo.secondaryCpuAbi = abi;
11298                        }
11299                    } else {
11300                        pkg.applicationInfo.primaryCpuAbi = abi;
11301                    }
11302                }
11303            } else {
11304                String[] abiList = (cpuAbiOverride != null) ?
11305                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11306
11307                // Enable gross and lame hacks for apps that are built with old
11308                // SDK tools. We must scan their APKs for renderscript bitcode and
11309                // not launch them if it's present. Don't bother checking on devices
11310                // that don't have 64 bit support.
11311                boolean needsRenderScriptOverride = false;
11312                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11313                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11314                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11315                    needsRenderScriptOverride = true;
11316                }
11317
11318                final int copyRet;
11319                if (extractLibs) {
11320                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11321                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11322                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11323                } else {
11324                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11325                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11326                }
11327                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11328
11329                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11330                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11331                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11332                }
11333
11334                if (copyRet >= 0) {
11335                    // Shared libraries that have native libs must be multi-architecture
11336                    if (pkg.isLibrary()) {
11337                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11338                                "Shared library with native libs must be multiarch");
11339                    }
11340                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11341                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11342                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11343                } else if (needsRenderScriptOverride) {
11344                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11345                }
11346            }
11347        } catch (IOException ioe) {
11348            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11349        } finally {
11350            IoUtils.closeQuietly(handle);
11351        }
11352
11353        // Now that we've calculated the ABIs and determined if it's an internal app,
11354        // we will go ahead and populate the nativeLibraryPath.
11355        setNativeLibraryPaths(pkg, appLib32InstallDir);
11356    }
11357
11358    /**
11359     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11360     * i.e, so that all packages can be run inside a single process if required.
11361     *
11362     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11363     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11364     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11365     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11366     * updating a package that belongs to a shared user.
11367     *
11368     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11369     * adds unnecessary complexity.
11370     */
11371    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11372            PackageParser.Package scannedPackage) {
11373        String requiredInstructionSet = null;
11374        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11375            requiredInstructionSet = VMRuntime.getInstructionSet(
11376                     scannedPackage.applicationInfo.primaryCpuAbi);
11377        }
11378
11379        PackageSetting requirer = null;
11380        for (PackageSetting ps : packagesForUser) {
11381            // If packagesForUser contains scannedPackage, we skip it. This will happen
11382            // when scannedPackage is an update of an existing package. Without this check,
11383            // we will never be able to change the ABI of any package belonging to a shared
11384            // user, even if it's compatible with other packages.
11385            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11386                if (ps.primaryCpuAbiString == null) {
11387                    continue;
11388                }
11389
11390                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11391                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11392                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11393                    // this but there's not much we can do.
11394                    String errorMessage = "Instruction set mismatch, "
11395                            + ((requirer == null) ? "[caller]" : requirer)
11396                            + " requires " + requiredInstructionSet + " whereas " + ps
11397                            + " requires " + instructionSet;
11398                    Slog.w(TAG, errorMessage);
11399                }
11400
11401                if (requiredInstructionSet == null) {
11402                    requiredInstructionSet = instructionSet;
11403                    requirer = ps;
11404                }
11405            }
11406        }
11407
11408        if (requiredInstructionSet != null) {
11409            String adjustedAbi;
11410            if (requirer != null) {
11411                // requirer != null implies that either scannedPackage was null or that scannedPackage
11412                // did not require an ABI, in which case we have to adjust scannedPackage to match
11413                // the ABI of the set (which is the same as requirer's ABI)
11414                adjustedAbi = requirer.primaryCpuAbiString;
11415                if (scannedPackage != null) {
11416                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11417                }
11418            } else {
11419                // requirer == null implies that we're updating all ABIs in the set to
11420                // match scannedPackage.
11421                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11422            }
11423
11424            for (PackageSetting ps : packagesForUser) {
11425                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11426                    if (ps.primaryCpuAbiString != null) {
11427                        continue;
11428                    }
11429
11430                    ps.primaryCpuAbiString = adjustedAbi;
11431                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11432                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11433                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11434                        if (DEBUG_ABI_SELECTION) {
11435                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11436                                    + " (requirer="
11437                                    + (requirer != null ? requirer.pkg : "null")
11438                                    + ", scannedPackage="
11439                                    + (scannedPackage != null ? scannedPackage : "null")
11440                                    + ")");
11441                        }
11442                        try {
11443                            mInstaller.rmdex(ps.codePathString,
11444                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11445                        } catch (InstallerException ignored) {
11446                        }
11447                    }
11448                }
11449            }
11450        }
11451    }
11452
11453    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11454        synchronized (mPackages) {
11455            mResolverReplaced = true;
11456            // Set up information for custom user intent resolution activity.
11457            mResolveActivity.applicationInfo = pkg.applicationInfo;
11458            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11459            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11460            mResolveActivity.processName = pkg.applicationInfo.packageName;
11461            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11462            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11463                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11464            mResolveActivity.theme = 0;
11465            mResolveActivity.exported = true;
11466            mResolveActivity.enabled = true;
11467            mResolveInfo.activityInfo = mResolveActivity;
11468            mResolveInfo.priority = 0;
11469            mResolveInfo.preferredOrder = 0;
11470            mResolveInfo.match = 0;
11471            mResolveComponentName = mCustomResolverComponentName;
11472            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11473                    mResolveComponentName);
11474        }
11475    }
11476
11477    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11478        if (installerActivity == null) {
11479            if (DEBUG_EPHEMERAL) {
11480                Slog.d(TAG, "Clear ephemeral installer activity");
11481            }
11482            mInstantAppInstallerActivity = null;
11483            return;
11484        }
11485
11486        if (DEBUG_EPHEMERAL) {
11487            Slog.d(TAG, "Set ephemeral installer activity: "
11488                    + installerActivity.getComponentName());
11489        }
11490        // Set up information for ephemeral installer activity
11491        mInstantAppInstallerActivity = installerActivity;
11492        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11493                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11494        mInstantAppInstallerActivity.exported = true;
11495        mInstantAppInstallerActivity.enabled = true;
11496        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11497        mInstantAppInstallerInfo.priority = 0;
11498        mInstantAppInstallerInfo.preferredOrder = 1;
11499        mInstantAppInstallerInfo.isDefault = true;
11500        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11501                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11502    }
11503
11504    private static String calculateBundledApkRoot(final String codePathString) {
11505        final File codePath = new File(codePathString);
11506        final File codeRoot;
11507        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11508            codeRoot = Environment.getRootDirectory();
11509        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11510            codeRoot = Environment.getOemDirectory();
11511        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11512            codeRoot = Environment.getVendorDirectory();
11513        } else {
11514            // Unrecognized code path; take its top real segment as the apk root:
11515            // e.g. /something/app/blah.apk => /something
11516            try {
11517                File f = codePath.getCanonicalFile();
11518                File parent = f.getParentFile();    // non-null because codePath is a file
11519                File tmp;
11520                while ((tmp = parent.getParentFile()) != null) {
11521                    f = parent;
11522                    parent = tmp;
11523                }
11524                codeRoot = f;
11525                Slog.w(TAG, "Unrecognized code path "
11526                        + codePath + " - using " + codeRoot);
11527            } catch (IOException e) {
11528                // Can't canonicalize the code path -- shenanigans?
11529                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11530                return Environment.getRootDirectory().getPath();
11531            }
11532        }
11533        return codeRoot.getPath();
11534    }
11535
11536    /**
11537     * Derive and set the location of native libraries for the given package,
11538     * which varies depending on where and how the package was installed.
11539     */
11540    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11541        final ApplicationInfo info = pkg.applicationInfo;
11542        final String codePath = pkg.codePath;
11543        final File codeFile = new File(codePath);
11544        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11545        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11546
11547        info.nativeLibraryRootDir = null;
11548        info.nativeLibraryRootRequiresIsa = false;
11549        info.nativeLibraryDir = null;
11550        info.secondaryNativeLibraryDir = null;
11551
11552        if (isApkFile(codeFile)) {
11553            // Monolithic install
11554            if (bundledApp) {
11555                // If "/system/lib64/apkname" exists, assume that is the per-package
11556                // native library directory to use; otherwise use "/system/lib/apkname".
11557                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11558                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11559                        getPrimaryInstructionSet(info));
11560
11561                // This is a bundled system app so choose the path based on the ABI.
11562                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11563                // is just the default path.
11564                final String apkName = deriveCodePathName(codePath);
11565                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11566                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11567                        apkName).getAbsolutePath();
11568
11569                if (info.secondaryCpuAbi != null) {
11570                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11571                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11572                            secondaryLibDir, apkName).getAbsolutePath();
11573                }
11574            } else if (asecApp) {
11575                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11576                        .getAbsolutePath();
11577            } else {
11578                final String apkName = deriveCodePathName(codePath);
11579                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11580                        .getAbsolutePath();
11581            }
11582
11583            info.nativeLibraryRootRequiresIsa = false;
11584            info.nativeLibraryDir = info.nativeLibraryRootDir;
11585        } else {
11586            // Cluster install
11587            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11588            info.nativeLibraryRootRequiresIsa = true;
11589
11590            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11591                    getPrimaryInstructionSet(info)).getAbsolutePath();
11592
11593            if (info.secondaryCpuAbi != null) {
11594                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11595                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11596            }
11597        }
11598    }
11599
11600    /**
11601     * Calculate the abis and roots for a bundled app. These can uniquely
11602     * be determined from the contents of the system partition, i.e whether
11603     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11604     * of this information, and instead assume that the system was built
11605     * sensibly.
11606     */
11607    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11608                                           PackageSetting pkgSetting) {
11609        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11610
11611        // If "/system/lib64/apkname" exists, assume that is the per-package
11612        // native library directory to use; otherwise use "/system/lib/apkname".
11613        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11614        setBundledAppAbi(pkg, apkRoot, apkName);
11615        // pkgSetting might be null during rescan following uninstall of updates
11616        // to a bundled app, so accommodate that possibility.  The settings in
11617        // that case will be established later from the parsed package.
11618        //
11619        // If the settings aren't null, sync them up with what we've just derived.
11620        // note that apkRoot isn't stored in the package settings.
11621        if (pkgSetting != null) {
11622            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11623            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11624        }
11625    }
11626
11627    /**
11628     * Deduces the ABI of a bundled app and sets the relevant fields on the
11629     * parsed pkg object.
11630     *
11631     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11632     *        under which system libraries are installed.
11633     * @param apkName the name of the installed package.
11634     */
11635    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11636        final File codeFile = new File(pkg.codePath);
11637
11638        final boolean has64BitLibs;
11639        final boolean has32BitLibs;
11640        if (isApkFile(codeFile)) {
11641            // Monolithic install
11642            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11643            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11644        } else {
11645            // Cluster install
11646            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11647            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11648                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11649                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11650                has64BitLibs = (new File(rootDir, isa)).exists();
11651            } else {
11652                has64BitLibs = false;
11653            }
11654            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11655                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11656                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11657                has32BitLibs = (new File(rootDir, isa)).exists();
11658            } else {
11659                has32BitLibs = false;
11660            }
11661        }
11662
11663        if (has64BitLibs && !has32BitLibs) {
11664            // The package has 64 bit libs, but not 32 bit libs. Its primary
11665            // ABI should be 64 bit. We can safely assume here that the bundled
11666            // native libraries correspond to the most preferred ABI in the list.
11667
11668            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11669            pkg.applicationInfo.secondaryCpuAbi = null;
11670        } else if (has32BitLibs && !has64BitLibs) {
11671            // The package has 32 bit libs but not 64 bit libs. Its primary
11672            // ABI should be 32 bit.
11673
11674            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11675            pkg.applicationInfo.secondaryCpuAbi = null;
11676        } else if (has32BitLibs && has64BitLibs) {
11677            // The application has both 64 and 32 bit bundled libraries. We check
11678            // here that the app declares multiArch support, and warn if it doesn't.
11679            //
11680            // We will be lenient here and record both ABIs. The primary will be the
11681            // ABI that's higher on the list, i.e, a device that's configured to prefer
11682            // 64 bit apps will see a 64 bit primary ABI,
11683
11684            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11685                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11686            }
11687
11688            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11689                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11690                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11691            } else {
11692                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11693                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11694            }
11695        } else {
11696            pkg.applicationInfo.primaryCpuAbi = null;
11697            pkg.applicationInfo.secondaryCpuAbi = null;
11698        }
11699    }
11700
11701    private void killApplication(String pkgName, int appId, String reason) {
11702        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11703    }
11704
11705    private void killApplication(String pkgName, int appId, int userId, String reason) {
11706        // Request the ActivityManager to kill the process(only for existing packages)
11707        // so that we do not end up in a confused state while the user is still using the older
11708        // version of the application while the new one gets installed.
11709        final long token = Binder.clearCallingIdentity();
11710        try {
11711            IActivityManager am = ActivityManager.getService();
11712            if (am != null) {
11713                try {
11714                    am.killApplication(pkgName, appId, userId, reason);
11715                } catch (RemoteException e) {
11716                }
11717            }
11718        } finally {
11719            Binder.restoreCallingIdentity(token);
11720        }
11721    }
11722
11723    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11724        // Remove the parent package setting
11725        PackageSetting ps = (PackageSetting) pkg.mExtras;
11726        if (ps != null) {
11727            removePackageLI(ps, chatty);
11728        }
11729        // Remove the child package setting
11730        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11731        for (int i = 0; i < childCount; i++) {
11732            PackageParser.Package childPkg = pkg.childPackages.get(i);
11733            ps = (PackageSetting) childPkg.mExtras;
11734            if (ps != null) {
11735                removePackageLI(ps, chatty);
11736            }
11737        }
11738    }
11739
11740    void removePackageLI(PackageSetting ps, boolean chatty) {
11741        if (DEBUG_INSTALL) {
11742            if (chatty)
11743                Log.d(TAG, "Removing package " + ps.name);
11744        }
11745
11746        // writer
11747        synchronized (mPackages) {
11748            mPackages.remove(ps.name);
11749            final PackageParser.Package pkg = ps.pkg;
11750            if (pkg != null) {
11751                cleanPackageDataStructuresLILPw(pkg, chatty);
11752            }
11753        }
11754    }
11755
11756    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11757        if (DEBUG_INSTALL) {
11758            if (chatty)
11759                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11760        }
11761
11762        // writer
11763        synchronized (mPackages) {
11764            // Remove the parent package
11765            mPackages.remove(pkg.applicationInfo.packageName);
11766            cleanPackageDataStructuresLILPw(pkg, chatty);
11767
11768            // Remove the child packages
11769            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11770            for (int i = 0; i < childCount; i++) {
11771                PackageParser.Package childPkg = pkg.childPackages.get(i);
11772                mPackages.remove(childPkg.applicationInfo.packageName);
11773                cleanPackageDataStructuresLILPw(childPkg, chatty);
11774            }
11775        }
11776    }
11777
11778    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11779        int N = pkg.providers.size();
11780        StringBuilder r = null;
11781        int i;
11782        for (i=0; i<N; i++) {
11783            PackageParser.Provider p = pkg.providers.get(i);
11784            mProviders.removeProvider(p);
11785            if (p.info.authority == null) {
11786
11787                /* There was another ContentProvider with this authority when
11788                 * this app was installed so this authority is null,
11789                 * Ignore it as we don't have to unregister the provider.
11790                 */
11791                continue;
11792            }
11793            String names[] = p.info.authority.split(";");
11794            for (int j = 0; j < names.length; j++) {
11795                if (mProvidersByAuthority.get(names[j]) == p) {
11796                    mProvidersByAuthority.remove(names[j]);
11797                    if (DEBUG_REMOVE) {
11798                        if (chatty)
11799                            Log.d(TAG, "Unregistered content provider: " + names[j]
11800                                    + ", className = " + p.info.name + ", isSyncable = "
11801                                    + p.info.isSyncable);
11802                    }
11803                }
11804            }
11805            if (DEBUG_REMOVE && chatty) {
11806                if (r == null) {
11807                    r = new StringBuilder(256);
11808                } else {
11809                    r.append(' ');
11810                }
11811                r.append(p.info.name);
11812            }
11813        }
11814        if (r != null) {
11815            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11816        }
11817
11818        N = pkg.services.size();
11819        r = null;
11820        for (i=0; i<N; i++) {
11821            PackageParser.Service s = pkg.services.get(i);
11822            mServices.removeService(s);
11823            if (chatty) {
11824                if (r == null) {
11825                    r = new StringBuilder(256);
11826                } else {
11827                    r.append(' ');
11828                }
11829                r.append(s.info.name);
11830            }
11831        }
11832        if (r != null) {
11833            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11834        }
11835
11836        N = pkg.receivers.size();
11837        r = null;
11838        for (i=0; i<N; i++) {
11839            PackageParser.Activity a = pkg.receivers.get(i);
11840            mReceivers.removeActivity(a, "receiver");
11841            if (DEBUG_REMOVE && chatty) {
11842                if (r == null) {
11843                    r = new StringBuilder(256);
11844                } else {
11845                    r.append(' ');
11846                }
11847                r.append(a.info.name);
11848            }
11849        }
11850        if (r != null) {
11851            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11852        }
11853
11854        N = pkg.activities.size();
11855        r = null;
11856        for (i=0; i<N; i++) {
11857            PackageParser.Activity a = pkg.activities.get(i);
11858            mActivities.removeActivity(a, "activity");
11859            if (DEBUG_REMOVE && chatty) {
11860                if (r == null) {
11861                    r = new StringBuilder(256);
11862                } else {
11863                    r.append(' ');
11864                }
11865                r.append(a.info.name);
11866            }
11867        }
11868        if (r != null) {
11869            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11870        }
11871
11872        mPermissionManager.removeAllPermissions(pkg, chatty);
11873
11874        N = pkg.instrumentation.size();
11875        r = null;
11876        for (i=0; i<N; i++) {
11877            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11878            mInstrumentation.remove(a.getComponentName());
11879            if (DEBUG_REMOVE && chatty) {
11880                if (r == null) {
11881                    r = new StringBuilder(256);
11882                } else {
11883                    r.append(' ');
11884                }
11885                r.append(a.info.name);
11886            }
11887        }
11888        if (r != null) {
11889            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11890        }
11891
11892        r = null;
11893        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11894            // Only system apps can hold shared libraries.
11895            if (pkg.libraryNames != null) {
11896                for (i = 0; i < pkg.libraryNames.size(); i++) {
11897                    String name = pkg.libraryNames.get(i);
11898                    if (removeSharedLibraryLPw(name, 0)) {
11899                        if (DEBUG_REMOVE && chatty) {
11900                            if (r == null) {
11901                                r = new StringBuilder(256);
11902                            } else {
11903                                r.append(' ');
11904                            }
11905                            r.append(name);
11906                        }
11907                    }
11908                }
11909            }
11910        }
11911
11912        r = null;
11913
11914        // Any package can hold static shared libraries.
11915        if (pkg.staticSharedLibName != null) {
11916            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11917                if (DEBUG_REMOVE && chatty) {
11918                    if (r == null) {
11919                        r = new StringBuilder(256);
11920                    } else {
11921                        r.append(' ');
11922                    }
11923                    r.append(pkg.staticSharedLibName);
11924                }
11925            }
11926        }
11927
11928        if (r != null) {
11929            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11930        }
11931    }
11932
11933    public static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11934    public static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11935    public static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11936
11937    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11938        // Update the parent permissions
11939        updatePermissionsLPw(pkg.packageName, pkg, flags);
11940        // Update the child permissions
11941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11942        for (int i = 0; i < childCount; i++) {
11943            PackageParser.Package childPkg = pkg.childPackages.get(i);
11944            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11945        }
11946    }
11947
11948    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11949            int flags) {
11950        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11951        updatePermissionsLocked(changingPkg, pkgInfo, volumeUuid, flags);
11952    }
11953
11954    private void updatePermissionsLocked(String changingPkg,
11955            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11956        // TODO: Most of the methods exposing BasePermission internals [source package name,
11957        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
11958        // have package settings, we should make note of it elsewhere [map between
11959        // source package name and BasePermission] and cycle through that here. Then we
11960        // define a single method on BasePermission that takes a PackageSetting, changing
11961        // package name and a package.
11962        // NOTE: With this approach, we also don't need to tree trees differently than
11963        // normal permissions. Today, we need two separate loops because these BasePermission
11964        // objects are stored separately.
11965        // Make sure there are no dangling permission trees.
11966        flags = mPermissionManager.updatePermissionTrees(changingPkg, pkgInfo, flags);
11967
11968        // Make sure all dynamic permissions have been assigned to a package,
11969        // and make sure there are no dangling permissions.
11970        flags = mPermissionManager.updatePermissions(changingPkg, pkgInfo, flags);
11971
11972        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11973        // Now update the permissions for all packages, in particular
11974        // replace the granted permissions of the system packages.
11975        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11976            for (PackageParser.Package pkg : mPackages.values()) {
11977                if (pkg != pkgInfo) {
11978                    // Only replace for packages on requested volume
11979                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11980                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11981                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11982                    grantPermissionsLPw(pkg, replace, changingPkg);
11983                }
11984            }
11985        }
11986
11987        if (pkgInfo != null) {
11988            // Only replace for packages on requested volume
11989            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11990            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11991                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11992            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11993        }
11994        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11995    }
11996
11997    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11998            String packageOfInterest) {
11999        // IMPORTANT: There are two types of permissions: install and runtime.
12000        // Install time permissions are granted when the app is installed to
12001        // all device users and users added in the future. Runtime permissions
12002        // are granted at runtime explicitly to specific users. Normal and signature
12003        // protected permissions are install time permissions. Dangerous permissions
12004        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12005        // otherwise they are runtime permissions. This function does not manage
12006        // runtime permissions except for the case an app targeting Lollipop MR1
12007        // being upgraded to target a newer SDK, in which case dangerous permissions
12008        // are transformed from install time to runtime ones.
12009
12010        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12011        if (ps == null) {
12012            return;
12013        }
12014
12015        PermissionsState permissionsState = ps.getPermissionsState();
12016        PermissionsState origPermissions = permissionsState;
12017
12018        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12019
12020        boolean runtimePermissionsRevoked = false;
12021        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12022
12023        boolean changedInstallPermission = false;
12024
12025        if (replace) {
12026            ps.installPermissionsFixed = false;
12027            if (!ps.isSharedUser()) {
12028                origPermissions = new PermissionsState(permissionsState);
12029                permissionsState.reset();
12030            } else {
12031                // We need to know only about runtime permission changes since the
12032                // calling code always writes the install permissions state but
12033                // the runtime ones are written only if changed. The only cases of
12034                // changed runtime permissions here are promotion of an install to
12035                // runtime and revocation of a runtime from a shared user.
12036                changedRuntimePermissionUserIds =
12037                        mPermissionManager.revokeUnusedSharedUserPermissions(
12038                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12039                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12040                    runtimePermissionsRevoked = true;
12041                }
12042            }
12043        }
12044
12045        permissionsState.setGlobalGids(mGlobalGids);
12046
12047        final int N = pkg.requestedPermissions.size();
12048        for (int i=0; i<N; i++) {
12049            final String name = pkg.requestedPermissions.get(i);
12050            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12051            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12052                    >= Build.VERSION_CODES.M;
12053
12054            if (DEBUG_INSTALL) {
12055                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12056            }
12057
12058            if (bp == null || bp.getSourcePackageSetting() == null) {
12059                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12060                    if (DEBUG_PERMISSIONS) {
12061                        Slog.i(TAG, "Unknown permission " + name
12062                                + " in package " + pkg.packageName);
12063                    }
12064                }
12065                continue;
12066            }
12067
12068
12069            // Limit ephemeral apps to ephemeral allowed permissions.
12070            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12071                if (DEBUG_PERMISSIONS) {
12072                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12073                            + pkg.packageName);
12074                }
12075                continue;
12076            }
12077
12078            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12079                if (DEBUG_PERMISSIONS) {
12080                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12081                            + pkg.packageName);
12082                }
12083                continue;
12084            }
12085
12086            final String perm = bp.getName();
12087            boolean allowedSig = false;
12088            int grant = GRANT_DENIED;
12089
12090            // Keep track of app op permissions.
12091            if (bp.isAppOp()) {
12092                mSettings.addAppOpPackage(perm, pkg.packageName);
12093            }
12094
12095            if (bp.isNormal()) {
12096                // For all apps normal permissions are install time ones.
12097                grant = GRANT_INSTALL;
12098            } else if (bp.isRuntime()) {
12099                // If a permission review is required for legacy apps we represent
12100                // their permissions as always granted runtime ones since we need
12101                // to keep the review required permission flag per user while an
12102                // install permission's state is shared across all users.
12103                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12104                    // For legacy apps dangerous permissions are install time ones.
12105                    grant = GRANT_INSTALL;
12106                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12107                    // For legacy apps that became modern, install becomes runtime.
12108                    grant = GRANT_UPGRADE;
12109                } else if (mPromoteSystemApps
12110                        && isSystemApp(ps)
12111                        && mExistingSystemPackages.contains(ps.name)) {
12112                    // For legacy system apps, install becomes runtime.
12113                    // We cannot check hasInstallPermission() for system apps since those
12114                    // permissions were granted implicitly and not persisted pre-M.
12115                    grant = GRANT_UPGRADE;
12116                } else {
12117                    // For modern apps keep runtime permissions unchanged.
12118                    grant = GRANT_RUNTIME;
12119                }
12120            } else if (bp.isSignature()) {
12121                // For all apps signature permissions are install time ones.
12122                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12123                if (allowedSig) {
12124                    grant = GRANT_INSTALL;
12125                }
12126            }
12127
12128            if (DEBUG_PERMISSIONS) {
12129                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12130            }
12131
12132            if (grant != GRANT_DENIED) {
12133                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12134                    // If this is an existing, non-system package, then
12135                    // we can't add any new permissions to it.
12136                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12137                        // Except...  if this is a permission that was added
12138                        // to the platform (note: need to only do this when
12139                        // updating the platform).
12140                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12141                            grant = GRANT_DENIED;
12142                        }
12143                    }
12144                }
12145
12146                switch (grant) {
12147                    case GRANT_INSTALL: {
12148                        // Revoke this as runtime permission to handle the case of
12149                        // a runtime permission being downgraded to an install one.
12150                        // Also in permission review mode we keep dangerous permissions
12151                        // for legacy apps
12152                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12153                            if (origPermissions.getRuntimePermissionState(
12154                                    perm, userId) != null) {
12155                                // Revoke the runtime permission and clear the flags.
12156                                origPermissions.revokeRuntimePermission(bp, userId);
12157                                origPermissions.updatePermissionFlags(bp, userId,
12158                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12159                                // If we revoked a permission permission, we have to write.
12160                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12161                                        changedRuntimePermissionUserIds, userId);
12162                            }
12163                        }
12164                        // Grant an install permission.
12165                        if (permissionsState.grantInstallPermission(bp) !=
12166                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12167                            changedInstallPermission = true;
12168                        }
12169                    } break;
12170
12171                    case GRANT_RUNTIME: {
12172                        // Grant previously granted runtime permissions.
12173                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12174                            PermissionState permissionState = origPermissions
12175                                    .getRuntimePermissionState(perm, userId);
12176                            int flags = permissionState != null
12177                                    ? permissionState.getFlags() : 0;
12178                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12179                                // Don't propagate the permission in a permission review mode if
12180                                // the former was revoked, i.e. marked to not propagate on upgrade.
12181                                // Note that in a permission review mode install permissions are
12182                                // represented as constantly granted runtime ones since we need to
12183                                // keep a per user state associated with the permission. Also the
12184                                // revoke on upgrade flag is no longer applicable and is reset.
12185                                final boolean revokeOnUpgrade = (flags & PackageManager
12186                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12187                                if (revokeOnUpgrade) {
12188                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12189                                    // Since we changed the flags, we have to write.
12190                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12191                                            changedRuntimePermissionUserIds, userId);
12192                                }
12193                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12194                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12195                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12196                                        // If we cannot put the permission as it was,
12197                                        // we have to write.
12198                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12199                                                changedRuntimePermissionUserIds, userId);
12200                                    }
12201                                }
12202
12203                                // If the app supports runtime permissions no need for a review.
12204                                if (mPermissionReviewRequired
12205                                        && appSupportsRuntimePermissions
12206                                        && (flags & PackageManager
12207                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12208                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12209                                    // Since we changed the flags, we have to write.
12210                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12211                                            changedRuntimePermissionUserIds, userId);
12212                                }
12213                            } else if (mPermissionReviewRequired
12214                                    && !appSupportsRuntimePermissions) {
12215                                // For legacy apps that need a permission review, every new
12216                                // runtime permission is granted but it is pending a review.
12217                                // We also need to review only platform defined runtime
12218                                // permissions as these are the only ones the platform knows
12219                                // how to disable the API to simulate revocation as legacy
12220                                // apps don't expect to run with revoked permissions.
12221                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12222                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12223                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12224                                        // We changed the flags, hence have to write.
12225                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12226                                                changedRuntimePermissionUserIds, userId);
12227                                    }
12228                                }
12229                                if (permissionsState.grantRuntimePermission(bp, userId)
12230                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12231                                    // We changed the permission, hence have to write.
12232                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12233                                            changedRuntimePermissionUserIds, userId);
12234                                }
12235                            }
12236                            // Propagate the permission flags.
12237                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12238                        }
12239                    } break;
12240
12241                    case GRANT_UPGRADE: {
12242                        // Grant runtime permissions for a previously held install permission.
12243                        PermissionState permissionState = origPermissions
12244                                .getInstallPermissionState(perm);
12245                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12246
12247                        if (origPermissions.revokeInstallPermission(bp)
12248                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12249                            // We will be transferring the permission flags, so clear them.
12250                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12251                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12252                            changedInstallPermission = true;
12253                        }
12254
12255                        // If the permission is not to be promoted to runtime we ignore it and
12256                        // also its other flags as they are not applicable to install permissions.
12257                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12258                            for (int userId : currentUserIds) {
12259                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12260                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12261                                    // Transfer the permission flags.
12262                                    permissionsState.updatePermissionFlags(bp, userId,
12263                                            flags, flags);
12264                                    // If we granted the permission, we have to write.
12265                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12266                                            changedRuntimePermissionUserIds, userId);
12267                                }
12268                            }
12269                        }
12270                    } break;
12271
12272                    default: {
12273                        if (packageOfInterest == null
12274                                || packageOfInterest.equals(pkg.packageName)) {
12275                            if (DEBUG_PERMISSIONS) {
12276                                Slog.i(TAG, "Not granting permission " + perm
12277                                        + " to package " + pkg.packageName
12278                                        + " because it was previously installed without");
12279                            }
12280                        }
12281                    } break;
12282                }
12283            } else {
12284                if (permissionsState.revokeInstallPermission(bp) !=
12285                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12286                    // Also drop the permission flags.
12287                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12288                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12289                    changedInstallPermission = true;
12290                    Slog.i(TAG, "Un-granting permission " + perm
12291                            + " from package " + pkg.packageName
12292                            + " (protectionLevel=" + bp.getProtectionLevel()
12293                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12294                            + ")");
12295                } else if (bp.isAppOp()) {
12296                    // Don't print warning for app op permissions, since it is fine for them
12297                    // not to be granted, there is a UI for the user to decide.
12298                    if (DEBUG_PERMISSIONS
12299                            && (packageOfInterest == null
12300                                    || packageOfInterest.equals(pkg.packageName))) {
12301                        Slog.i(TAG, "Not granting permission " + perm
12302                                + " to package " + pkg.packageName
12303                                + " (protectionLevel=" + bp.getProtectionLevel()
12304                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12305                                + ")");
12306                    }
12307                }
12308            }
12309        }
12310
12311        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12312                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12313            // This is the first that we have heard about this package, so the
12314            // permissions we have now selected are fixed until explicitly
12315            // changed.
12316            ps.installPermissionsFixed = true;
12317        }
12318
12319        // Persist the runtime permissions state for users with changes. If permissions
12320        // were revoked because no app in the shared user declares them we have to
12321        // write synchronously to avoid losing runtime permissions state.
12322        for (int userId : changedRuntimePermissionUserIds) {
12323            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12324        }
12325    }
12326
12327    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12328        boolean allowed = false;
12329        final int NP = PackageParser.NEW_PERMISSIONS.length;
12330        for (int ip=0; ip<NP; ip++) {
12331            final PackageParser.NewPermissionInfo npi
12332                    = PackageParser.NEW_PERMISSIONS[ip];
12333            if (npi.name.equals(perm)
12334                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12335                allowed = true;
12336                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12337                        + pkg.packageName);
12338                break;
12339            }
12340        }
12341        return allowed;
12342    }
12343
12344    /**
12345     * Determines whether a package is whitelisted for a particular privapp permission.
12346     *
12347     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12348     *
12349     * <p>This handles parent/child apps.
12350     */
12351    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12352        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12353                .getPrivAppPermissions(pkg.packageName);
12354        // Let's check if this package is whitelisted...
12355        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12356        // If it's not, we'll also tail-recurse to the parent.
12357        return whitelisted ||
12358                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12359    }
12360
12361    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12362            BasePermission bp, PermissionsState origPermissions) {
12363        boolean oemPermission = bp.isOEM();
12364        boolean privilegedPermission = bp.isPrivileged();
12365        boolean privappPermissionsDisable =
12366                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12367        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12368        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12369        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12370                && !platformPackage && platformPermission) {
12371            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12372                Slog.w(TAG, "Privileged permission " + perm + " for package "
12373                        + pkg.packageName + " - not in privapp-permissions whitelist");
12374                // Only report violations for apps on system image
12375                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12376                    // it's only a reportable violation if the permission isn't explicitly denied
12377                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12378                            .getPrivAppDenyPermissions(pkg.packageName);
12379                    final boolean permissionViolation =
12380                            deniedPermissions == null || !deniedPermissions.contains(perm);
12381                    if (permissionViolation
12382                            && RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12383                        if (mPrivappPermissionsViolations == null) {
12384                            mPrivappPermissionsViolations = new ArraySet<>();
12385                        }
12386                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12387                    } else {
12388                        return false;
12389                    }
12390                }
12391                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12392                    return false;
12393                }
12394            }
12395        }
12396        boolean allowed = (compareSignatures(
12397                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12398                        == PackageManager.SIGNATURE_MATCH)
12399                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12400                        == PackageManager.SIGNATURE_MATCH);
12401        if (!allowed && (privilegedPermission || oemPermission)) {
12402            if (isSystemApp(pkg)) {
12403                // For updated system applications, a privileged/oem permission
12404                // is granted only if it had been defined by the original application.
12405                if (pkg.isUpdatedSystemApp()) {
12406                    final PackageSetting sysPs = mSettings
12407                            .getDisabledSystemPkgLPr(pkg.packageName);
12408                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12409                        // If the original was granted this permission, we take
12410                        // that grant decision as read and propagate it to the
12411                        // update.
12412                        if ((privilegedPermission && sysPs.isPrivileged())
12413                                || (oemPermission && sysPs.isOem()
12414                                        && canGrantOemPermission(sysPs, perm))) {
12415                            allowed = true;
12416                        }
12417                    } else {
12418                        // The system apk may have been updated with an older
12419                        // version of the one on the data partition, but which
12420                        // granted a new system permission that it didn't have
12421                        // before.  In this case we do want to allow the app to
12422                        // now get the new permission if the ancestral apk is
12423                        // privileged to get it.
12424                        if (sysPs != null && sysPs.pkg != null
12425                                && isPackageRequestingPermission(sysPs.pkg, perm)
12426                                && ((privilegedPermission && sysPs.isPrivileged())
12427                                        || (oemPermission && sysPs.isOem()
12428                                                && canGrantOemPermission(sysPs, perm)))) {
12429                            allowed = true;
12430                        }
12431                        // Also if a privileged parent package on the system image or any of
12432                        // its children requested a privileged/oem permission, the updated child
12433                        // packages can also get the permission.
12434                        if (pkg.parentPackage != null) {
12435                            final PackageSetting disabledSysParentPs = mSettings
12436                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12437                            final PackageParser.Package disabledSysParentPkg =
12438                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12439                                    ? null : disabledSysParentPs.pkg;
12440                            if (disabledSysParentPkg != null
12441                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12442                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12443                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12444                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12445                                    allowed = true;
12446                                } else if (disabledSysParentPkg.childPackages != null) {
12447                                    final int count = disabledSysParentPkg.childPackages.size();
12448                                    for (int i = 0; i < count; i++) {
12449                                        final PackageParser.Package disabledSysChildPkg =
12450                                                disabledSysParentPkg.childPackages.get(i);
12451                                        final PackageSetting disabledSysChildPs =
12452                                                mSettings.getDisabledSystemPkgLPr(
12453                                                        disabledSysChildPkg.packageName);
12454                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12455                                                && canGrantOemPermission(
12456                                                        disabledSysChildPs, perm)) {
12457                                            allowed = true;
12458                                            break;
12459                                        }
12460                                    }
12461                                }
12462                            }
12463                        }
12464                    }
12465                } else {
12466                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12467                            || (oemPermission && isOemApp(pkg)
12468                                    && canGrantOemPermission(
12469                                            mSettings.getPackageLPr(pkg.packageName), perm));
12470                }
12471            }
12472        }
12473        if (!allowed) {
12474            if (!allowed
12475                    && bp.isPre23()
12476                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12477                // If this was a previously normal/dangerous permission that got moved
12478                // to a system permission as part of the runtime permission redesign, then
12479                // we still want to blindly grant it to old apps.
12480                allowed = true;
12481            }
12482            if (!allowed && bp.isInstaller()
12483                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12484                // If this permission is to be granted to the system installer and
12485                // this app is an installer, then it gets the permission.
12486                allowed = true;
12487            }
12488            if (!allowed && bp.isVerifier()
12489                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12490                // If this permission is to be granted to the system verifier and
12491                // this app is a verifier, then it gets the permission.
12492                allowed = true;
12493            }
12494            if (!allowed && bp.isPreInstalled()
12495                    && isSystemApp(pkg)) {
12496                // Any pre-installed system app is allowed to get this permission.
12497                allowed = true;
12498            }
12499            if (!allowed && bp.isDevelopment()) {
12500                // For development permissions, a development permission
12501                // is granted only if it was already granted.
12502                allowed = origPermissions.hasInstallPermission(perm);
12503            }
12504            if (!allowed && bp.isSetup()
12505                    && pkg.packageName.equals(mSetupWizardPackage)) {
12506                // If this permission is to be granted to the system setup wizard and
12507                // this app is a setup wizard, then it gets the permission.
12508                allowed = true;
12509            }
12510        }
12511        return allowed;
12512    }
12513
12514    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12515        if (!ps.isOem()) {
12516            return false;
12517        }
12518        // all oem permissions must explicitly be granted or denied
12519        final Boolean granted =
12520                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12521        if (granted == null) {
12522            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12523                    + ps.name + " must be explicitly declared granted or not");
12524        }
12525        return Boolean.TRUE == granted;
12526    }
12527
12528    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12529        final int permCount = pkg.requestedPermissions.size();
12530        for (int j = 0; j < permCount; j++) {
12531            String requestedPermission = pkg.requestedPermissions.get(j);
12532            if (permission.equals(requestedPermission)) {
12533                return true;
12534            }
12535        }
12536        return false;
12537    }
12538
12539    final class ActivityIntentResolver
12540            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12541        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12542                boolean defaultOnly, int userId) {
12543            if (!sUserManager.exists(userId)) return null;
12544            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12545            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12546        }
12547
12548        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12549                int userId) {
12550            if (!sUserManager.exists(userId)) return null;
12551            mFlags = flags;
12552            return super.queryIntent(intent, resolvedType,
12553                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12554                    userId);
12555        }
12556
12557        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12558                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12559            if (!sUserManager.exists(userId)) return null;
12560            if (packageActivities == null) {
12561                return null;
12562            }
12563            mFlags = flags;
12564            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12565            final int N = packageActivities.size();
12566            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12567                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12568
12569            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12570            for (int i = 0; i < N; ++i) {
12571                intentFilters = packageActivities.get(i).intents;
12572                if (intentFilters != null && intentFilters.size() > 0) {
12573                    PackageParser.ActivityIntentInfo[] array =
12574                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12575                    intentFilters.toArray(array);
12576                    listCut.add(array);
12577                }
12578            }
12579            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12580        }
12581
12582        /**
12583         * Finds a privileged activity that matches the specified activity names.
12584         */
12585        private PackageParser.Activity findMatchingActivity(
12586                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12587            for (PackageParser.Activity sysActivity : activityList) {
12588                if (sysActivity.info.name.equals(activityInfo.name)) {
12589                    return sysActivity;
12590                }
12591                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12592                    return sysActivity;
12593                }
12594                if (sysActivity.info.targetActivity != null) {
12595                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12596                        return sysActivity;
12597                    }
12598                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12599                        return sysActivity;
12600                    }
12601                }
12602            }
12603            return null;
12604        }
12605
12606        public class IterGenerator<E> {
12607            public Iterator<E> generate(ActivityIntentInfo info) {
12608                return null;
12609            }
12610        }
12611
12612        public class ActionIterGenerator extends IterGenerator<String> {
12613            @Override
12614            public Iterator<String> generate(ActivityIntentInfo info) {
12615                return info.actionsIterator();
12616            }
12617        }
12618
12619        public class CategoriesIterGenerator extends IterGenerator<String> {
12620            @Override
12621            public Iterator<String> generate(ActivityIntentInfo info) {
12622                return info.categoriesIterator();
12623            }
12624        }
12625
12626        public class SchemesIterGenerator extends IterGenerator<String> {
12627            @Override
12628            public Iterator<String> generate(ActivityIntentInfo info) {
12629                return info.schemesIterator();
12630            }
12631        }
12632
12633        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12634            @Override
12635            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12636                return info.authoritiesIterator();
12637            }
12638        }
12639
12640        /**
12641         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12642         * MODIFIED. Do not pass in a list that should not be changed.
12643         */
12644        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12645                IterGenerator<T> generator, Iterator<T> searchIterator) {
12646            // loop through the set of actions; every one must be found in the intent filter
12647            while (searchIterator.hasNext()) {
12648                // we must have at least one filter in the list to consider a match
12649                if (intentList.size() == 0) {
12650                    break;
12651                }
12652
12653                final T searchAction = searchIterator.next();
12654
12655                // loop through the set of intent filters
12656                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12657                while (intentIter.hasNext()) {
12658                    final ActivityIntentInfo intentInfo = intentIter.next();
12659                    boolean selectionFound = false;
12660
12661                    // loop through the intent filter's selection criteria; at least one
12662                    // of them must match the searched criteria
12663                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12664                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12665                        final T intentSelection = intentSelectionIter.next();
12666                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12667                            selectionFound = true;
12668                            break;
12669                        }
12670                    }
12671
12672                    // the selection criteria wasn't found in this filter's set; this filter
12673                    // is not a potential match
12674                    if (!selectionFound) {
12675                        intentIter.remove();
12676                    }
12677                }
12678            }
12679        }
12680
12681        private boolean isProtectedAction(ActivityIntentInfo filter) {
12682            final Iterator<String> actionsIter = filter.actionsIterator();
12683            while (actionsIter != null && actionsIter.hasNext()) {
12684                final String filterAction = actionsIter.next();
12685                if (PROTECTED_ACTIONS.contains(filterAction)) {
12686                    return true;
12687                }
12688            }
12689            return false;
12690        }
12691
12692        /**
12693         * Adjusts the priority of the given intent filter according to policy.
12694         * <p>
12695         * <ul>
12696         * <li>The priority for non privileged applications is capped to '0'</li>
12697         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12698         * <li>The priority for unbundled updates to privileged applications is capped to the
12699         *      priority defined on the system partition</li>
12700         * </ul>
12701         * <p>
12702         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12703         * allowed to obtain any priority on any action.
12704         */
12705        private void adjustPriority(
12706                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12707            // nothing to do; priority is fine as-is
12708            if (intent.getPriority() <= 0) {
12709                return;
12710            }
12711
12712            final ActivityInfo activityInfo = intent.activity.info;
12713            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12714
12715            final boolean privilegedApp =
12716                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12717            if (!privilegedApp) {
12718                // non-privileged applications can never define a priority >0
12719                if (DEBUG_FILTERS) {
12720                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12721                            + " package: " + applicationInfo.packageName
12722                            + " activity: " + intent.activity.className
12723                            + " origPrio: " + intent.getPriority());
12724                }
12725                intent.setPriority(0);
12726                return;
12727            }
12728
12729            if (systemActivities == null) {
12730                // the system package is not disabled; we're parsing the system partition
12731                if (isProtectedAction(intent)) {
12732                    if (mDeferProtectedFilters) {
12733                        // We can't deal with these just yet. No component should ever obtain a
12734                        // >0 priority for a protected actions, with ONE exception -- the setup
12735                        // wizard. The setup wizard, however, cannot be known until we're able to
12736                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12737                        // until all intent filters have been processed. Chicken, meet egg.
12738                        // Let the filter temporarily have a high priority and rectify the
12739                        // priorities after all system packages have been scanned.
12740                        mProtectedFilters.add(intent);
12741                        if (DEBUG_FILTERS) {
12742                            Slog.i(TAG, "Protected action; save for later;"
12743                                    + " package: " + applicationInfo.packageName
12744                                    + " activity: " + intent.activity.className
12745                                    + " origPrio: " + intent.getPriority());
12746                        }
12747                        return;
12748                    } else {
12749                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12750                            Slog.i(TAG, "No setup wizard;"
12751                                + " All protected intents capped to priority 0");
12752                        }
12753                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12754                            if (DEBUG_FILTERS) {
12755                                Slog.i(TAG, "Found setup wizard;"
12756                                    + " allow priority " + intent.getPriority() + ";"
12757                                    + " package: " + intent.activity.info.packageName
12758                                    + " activity: " + intent.activity.className
12759                                    + " priority: " + intent.getPriority());
12760                            }
12761                            // setup wizard gets whatever it wants
12762                            return;
12763                        }
12764                        if (DEBUG_FILTERS) {
12765                            Slog.i(TAG, "Protected action; cap priority to 0;"
12766                                    + " package: " + intent.activity.info.packageName
12767                                    + " activity: " + intent.activity.className
12768                                    + " origPrio: " + intent.getPriority());
12769                        }
12770                        intent.setPriority(0);
12771                        return;
12772                    }
12773                }
12774                // privileged apps on the system image get whatever priority they request
12775                return;
12776            }
12777
12778            // privileged app unbundled update ... try to find the same activity
12779            final PackageParser.Activity foundActivity =
12780                    findMatchingActivity(systemActivities, activityInfo);
12781            if (foundActivity == null) {
12782                // this is a new activity; it cannot obtain >0 priority
12783                if (DEBUG_FILTERS) {
12784                    Slog.i(TAG, "New activity; cap priority to 0;"
12785                            + " package: " + applicationInfo.packageName
12786                            + " activity: " + intent.activity.className
12787                            + " origPrio: " + intent.getPriority());
12788                }
12789                intent.setPriority(0);
12790                return;
12791            }
12792
12793            // found activity, now check for filter equivalence
12794
12795            // a shallow copy is enough; we modify the list, not its contents
12796            final List<ActivityIntentInfo> intentListCopy =
12797                    new ArrayList<>(foundActivity.intents);
12798            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12799
12800            // find matching action subsets
12801            final Iterator<String> actionsIterator = intent.actionsIterator();
12802            if (actionsIterator != null) {
12803                getIntentListSubset(
12804                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12805                if (intentListCopy.size() == 0) {
12806                    // no more intents to match; we're not equivalent
12807                    if (DEBUG_FILTERS) {
12808                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12809                                + " package: " + applicationInfo.packageName
12810                                + " activity: " + intent.activity.className
12811                                + " origPrio: " + intent.getPriority());
12812                    }
12813                    intent.setPriority(0);
12814                    return;
12815                }
12816            }
12817
12818            // find matching category subsets
12819            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12820            if (categoriesIterator != null) {
12821                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12822                        categoriesIterator);
12823                if (intentListCopy.size() == 0) {
12824                    // no more intents to match; we're not equivalent
12825                    if (DEBUG_FILTERS) {
12826                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12827                                + " package: " + applicationInfo.packageName
12828                                + " activity: " + intent.activity.className
12829                                + " origPrio: " + intent.getPriority());
12830                    }
12831                    intent.setPriority(0);
12832                    return;
12833                }
12834            }
12835
12836            // find matching schemes subsets
12837            final Iterator<String> schemesIterator = intent.schemesIterator();
12838            if (schemesIterator != null) {
12839                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12840                        schemesIterator);
12841                if (intentListCopy.size() == 0) {
12842                    // no more intents to match; we're not equivalent
12843                    if (DEBUG_FILTERS) {
12844                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12845                                + " package: " + applicationInfo.packageName
12846                                + " activity: " + intent.activity.className
12847                                + " origPrio: " + intent.getPriority());
12848                    }
12849                    intent.setPriority(0);
12850                    return;
12851                }
12852            }
12853
12854            // find matching authorities subsets
12855            final Iterator<IntentFilter.AuthorityEntry>
12856                    authoritiesIterator = intent.authoritiesIterator();
12857            if (authoritiesIterator != null) {
12858                getIntentListSubset(intentListCopy,
12859                        new AuthoritiesIterGenerator(),
12860                        authoritiesIterator);
12861                if (intentListCopy.size() == 0) {
12862                    // no more intents to match; we're not equivalent
12863                    if (DEBUG_FILTERS) {
12864                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12865                                + " package: " + applicationInfo.packageName
12866                                + " activity: " + intent.activity.className
12867                                + " origPrio: " + intent.getPriority());
12868                    }
12869                    intent.setPriority(0);
12870                    return;
12871                }
12872            }
12873
12874            // we found matching filter(s); app gets the max priority of all intents
12875            int cappedPriority = 0;
12876            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12877                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12878            }
12879            if (intent.getPriority() > cappedPriority) {
12880                if (DEBUG_FILTERS) {
12881                    Slog.i(TAG, "Found matching filter(s);"
12882                            + " cap priority to " + cappedPriority + ";"
12883                            + " package: " + applicationInfo.packageName
12884                            + " activity: " + intent.activity.className
12885                            + " origPrio: " + intent.getPriority());
12886                }
12887                intent.setPriority(cappedPriority);
12888                return;
12889            }
12890            // all this for nothing; the requested priority was <= what was on the system
12891        }
12892
12893        public final void addActivity(PackageParser.Activity a, String type) {
12894            mActivities.put(a.getComponentName(), a);
12895            if (DEBUG_SHOW_INFO)
12896                Log.v(
12897                TAG, "  " + type + " " +
12898                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12899            if (DEBUG_SHOW_INFO)
12900                Log.v(TAG, "    Class=" + a.info.name);
12901            final int NI = a.intents.size();
12902            for (int j=0; j<NI; j++) {
12903                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12904                if ("activity".equals(type)) {
12905                    final PackageSetting ps =
12906                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12907                    final List<PackageParser.Activity> systemActivities =
12908                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12909                    adjustPriority(systemActivities, intent);
12910                }
12911                if (DEBUG_SHOW_INFO) {
12912                    Log.v(TAG, "    IntentFilter:");
12913                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12914                }
12915                if (!intent.debugCheck()) {
12916                    Log.w(TAG, "==> For Activity " + a.info.name);
12917                }
12918                addFilter(intent);
12919            }
12920        }
12921
12922        public final void removeActivity(PackageParser.Activity a, String type) {
12923            mActivities.remove(a.getComponentName());
12924            if (DEBUG_SHOW_INFO) {
12925                Log.v(TAG, "  " + type + " "
12926                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12927                                : a.info.name) + ":");
12928                Log.v(TAG, "    Class=" + a.info.name);
12929            }
12930            final int NI = a.intents.size();
12931            for (int j=0; j<NI; j++) {
12932                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12933                if (DEBUG_SHOW_INFO) {
12934                    Log.v(TAG, "    IntentFilter:");
12935                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12936                }
12937                removeFilter(intent);
12938            }
12939        }
12940
12941        @Override
12942        protected boolean allowFilterResult(
12943                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12944            ActivityInfo filterAi = filter.activity.info;
12945            for (int i=dest.size()-1; i>=0; i--) {
12946                ActivityInfo destAi = dest.get(i).activityInfo;
12947                if (destAi.name == filterAi.name
12948                        && destAi.packageName == filterAi.packageName) {
12949                    return false;
12950                }
12951            }
12952            return true;
12953        }
12954
12955        @Override
12956        protected ActivityIntentInfo[] newArray(int size) {
12957            return new ActivityIntentInfo[size];
12958        }
12959
12960        @Override
12961        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12962            if (!sUserManager.exists(userId)) return true;
12963            PackageParser.Package p = filter.activity.owner;
12964            if (p != null) {
12965                PackageSetting ps = (PackageSetting)p.mExtras;
12966                if (ps != null) {
12967                    // System apps are never considered stopped for purposes of
12968                    // filtering, because there may be no way for the user to
12969                    // actually re-launch them.
12970                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12971                            && ps.getStopped(userId);
12972                }
12973            }
12974            return false;
12975        }
12976
12977        @Override
12978        protected boolean isPackageForFilter(String packageName,
12979                PackageParser.ActivityIntentInfo info) {
12980            return packageName.equals(info.activity.owner.packageName);
12981        }
12982
12983        @Override
12984        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12985                int match, int userId) {
12986            if (!sUserManager.exists(userId)) return null;
12987            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12988                return null;
12989            }
12990            final PackageParser.Activity activity = info.activity;
12991            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12992            if (ps == null) {
12993                return null;
12994            }
12995            final PackageUserState userState = ps.readUserState(userId);
12996            ActivityInfo ai =
12997                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12998            if (ai == null) {
12999                return null;
13000            }
13001            final boolean matchExplicitlyVisibleOnly =
13002                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13003            final boolean matchVisibleToInstantApp =
13004                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13005            final boolean componentVisible =
13006                    matchVisibleToInstantApp
13007                    && info.isVisibleToInstantApp()
13008                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13009            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13010            // throw out filters that aren't visible to ephemeral apps
13011            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13012                return null;
13013            }
13014            // throw out instant app filters if we're not explicitly requesting them
13015            if (!matchInstantApp && userState.instantApp) {
13016                return null;
13017            }
13018            // throw out instant app filters if updates are available; will trigger
13019            // instant app resolution
13020            if (userState.instantApp && ps.isUpdateAvailable()) {
13021                return null;
13022            }
13023            final ResolveInfo res = new ResolveInfo();
13024            res.activityInfo = ai;
13025            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13026                res.filter = info;
13027            }
13028            if (info != null) {
13029                res.handleAllWebDataURI = info.handleAllWebDataURI();
13030            }
13031            res.priority = info.getPriority();
13032            res.preferredOrder = activity.owner.mPreferredOrder;
13033            //System.out.println("Result: " + res.activityInfo.className +
13034            //                   " = " + res.priority);
13035            res.match = match;
13036            res.isDefault = info.hasDefault;
13037            res.labelRes = info.labelRes;
13038            res.nonLocalizedLabel = info.nonLocalizedLabel;
13039            if (userNeedsBadging(userId)) {
13040                res.noResourceId = true;
13041            } else {
13042                res.icon = info.icon;
13043            }
13044            res.iconResourceId = info.icon;
13045            res.system = res.activityInfo.applicationInfo.isSystemApp();
13046            res.isInstantAppAvailable = userState.instantApp;
13047            return res;
13048        }
13049
13050        @Override
13051        protected void sortResults(List<ResolveInfo> results) {
13052            Collections.sort(results, mResolvePrioritySorter);
13053        }
13054
13055        @Override
13056        protected void dumpFilter(PrintWriter out, String prefix,
13057                PackageParser.ActivityIntentInfo filter) {
13058            out.print(prefix); out.print(
13059                    Integer.toHexString(System.identityHashCode(filter.activity)));
13060                    out.print(' ');
13061                    filter.activity.printComponentShortName(out);
13062                    out.print(" filter ");
13063                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13064        }
13065
13066        @Override
13067        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13068            return filter.activity;
13069        }
13070
13071        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13072            PackageParser.Activity activity = (PackageParser.Activity)label;
13073            out.print(prefix); out.print(
13074                    Integer.toHexString(System.identityHashCode(activity)));
13075                    out.print(' ');
13076                    activity.printComponentShortName(out);
13077            if (count > 1) {
13078                out.print(" ("); out.print(count); out.print(" filters)");
13079            }
13080            out.println();
13081        }
13082
13083        // Keys are String (activity class name), values are Activity.
13084        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13085                = new ArrayMap<ComponentName, PackageParser.Activity>();
13086        private int mFlags;
13087    }
13088
13089    private final class ServiceIntentResolver
13090            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13091        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13092                boolean defaultOnly, int userId) {
13093            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13094            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13095        }
13096
13097        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13098                int userId) {
13099            if (!sUserManager.exists(userId)) return null;
13100            mFlags = flags;
13101            return super.queryIntent(intent, resolvedType,
13102                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13103                    userId);
13104        }
13105
13106        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13107                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13108            if (!sUserManager.exists(userId)) return null;
13109            if (packageServices == null) {
13110                return null;
13111            }
13112            mFlags = flags;
13113            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13114            final int N = packageServices.size();
13115            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13116                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13117
13118            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13119            for (int i = 0; i < N; ++i) {
13120                intentFilters = packageServices.get(i).intents;
13121                if (intentFilters != null && intentFilters.size() > 0) {
13122                    PackageParser.ServiceIntentInfo[] array =
13123                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13124                    intentFilters.toArray(array);
13125                    listCut.add(array);
13126                }
13127            }
13128            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13129        }
13130
13131        public final void addService(PackageParser.Service s) {
13132            mServices.put(s.getComponentName(), s);
13133            if (DEBUG_SHOW_INFO) {
13134                Log.v(TAG, "  "
13135                        + (s.info.nonLocalizedLabel != null
13136                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13137                Log.v(TAG, "    Class=" + s.info.name);
13138            }
13139            final int NI = s.intents.size();
13140            int j;
13141            for (j=0; j<NI; j++) {
13142                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13143                if (DEBUG_SHOW_INFO) {
13144                    Log.v(TAG, "    IntentFilter:");
13145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13146                }
13147                if (!intent.debugCheck()) {
13148                    Log.w(TAG, "==> For Service " + s.info.name);
13149                }
13150                addFilter(intent);
13151            }
13152        }
13153
13154        public final void removeService(PackageParser.Service s) {
13155            mServices.remove(s.getComponentName());
13156            if (DEBUG_SHOW_INFO) {
13157                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13158                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13159                Log.v(TAG, "    Class=" + s.info.name);
13160            }
13161            final int NI = s.intents.size();
13162            int j;
13163            for (j=0; j<NI; j++) {
13164                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13165                if (DEBUG_SHOW_INFO) {
13166                    Log.v(TAG, "    IntentFilter:");
13167                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13168                }
13169                removeFilter(intent);
13170            }
13171        }
13172
13173        @Override
13174        protected boolean allowFilterResult(
13175                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13176            ServiceInfo filterSi = filter.service.info;
13177            for (int i=dest.size()-1; i>=0; i--) {
13178                ServiceInfo destAi = dest.get(i).serviceInfo;
13179                if (destAi.name == filterSi.name
13180                        && destAi.packageName == filterSi.packageName) {
13181                    return false;
13182                }
13183            }
13184            return true;
13185        }
13186
13187        @Override
13188        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13189            return new PackageParser.ServiceIntentInfo[size];
13190        }
13191
13192        @Override
13193        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13194            if (!sUserManager.exists(userId)) return true;
13195            PackageParser.Package p = filter.service.owner;
13196            if (p != null) {
13197                PackageSetting ps = (PackageSetting)p.mExtras;
13198                if (ps != null) {
13199                    // System apps are never considered stopped for purposes of
13200                    // filtering, because there may be no way for the user to
13201                    // actually re-launch them.
13202                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13203                            && ps.getStopped(userId);
13204                }
13205            }
13206            return false;
13207        }
13208
13209        @Override
13210        protected boolean isPackageForFilter(String packageName,
13211                PackageParser.ServiceIntentInfo info) {
13212            return packageName.equals(info.service.owner.packageName);
13213        }
13214
13215        @Override
13216        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13217                int match, int userId) {
13218            if (!sUserManager.exists(userId)) return null;
13219            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13220            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13221                return null;
13222            }
13223            final PackageParser.Service service = info.service;
13224            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13225            if (ps == null) {
13226                return null;
13227            }
13228            final PackageUserState userState = ps.readUserState(userId);
13229            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13230                    userState, userId);
13231            if (si == null) {
13232                return null;
13233            }
13234            final boolean matchVisibleToInstantApp =
13235                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13236            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13237            // throw out filters that aren't visible to ephemeral apps
13238            if (matchVisibleToInstantApp
13239                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13240                return null;
13241            }
13242            // throw out ephemeral filters if we're not explicitly requesting them
13243            if (!isInstantApp && userState.instantApp) {
13244                return null;
13245            }
13246            // throw out instant app filters if updates are available; will trigger
13247            // instant app resolution
13248            if (userState.instantApp && ps.isUpdateAvailable()) {
13249                return null;
13250            }
13251            final ResolveInfo res = new ResolveInfo();
13252            res.serviceInfo = si;
13253            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13254                res.filter = filter;
13255            }
13256            res.priority = info.getPriority();
13257            res.preferredOrder = service.owner.mPreferredOrder;
13258            res.match = match;
13259            res.isDefault = info.hasDefault;
13260            res.labelRes = info.labelRes;
13261            res.nonLocalizedLabel = info.nonLocalizedLabel;
13262            res.icon = info.icon;
13263            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13264            return res;
13265        }
13266
13267        @Override
13268        protected void sortResults(List<ResolveInfo> results) {
13269            Collections.sort(results, mResolvePrioritySorter);
13270        }
13271
13272        @Override
13273        protected void dumpFilter(PrintWriter out, String prefix,
13274                PackageParser.ServiceIntentInfo filter) {
13275            out.print(prefix); out.print(
13276                    Integer.toHexString(System.identityHashCode(filter.service)));
13277                    out.print(' ');
13278                    filter.service.printComponentShortName(out);
13279                    out.print(" filter ");
13280                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13281        }
13282
13283        @Override
13284        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13285            return filter.service;
13286        }
13287
13288        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13289            PackageParser.Service service = (PackageParser.Service)label;
13290            out.print(prefix); out.print(
13291                    Integer.toHexString(System.identityHashCode(service)));
13292                    out.print(' ');
13293                    service.printComponentShortName(out);
13294            if (count > 1) {
13295                out.print(" ("); out.print(count); out.print(" filters)");
13296            }
13297            out.println();
13298        }
13299
13300//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13301//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13302//            final List<ResolveInfo> retList = Lists.newArrayList();
13303//            while (i.hasNext()) {
13304//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13305//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13306//                    retList.add(resolveInfo);
13307//                }
13308//            }
13309//            return retList;
13310//        }
13311
13312        // Keys are String (activity class name), values are Activity.
13313        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13314                = new ArrayMap<ComponentName, PackageParser.Service>();
13315        private int mFlags;
13316    }
13317
13318    private final class ProviderIntentResolver
13319            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13320        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13321                boolean defaultOnly, int userId) {
13322            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13323            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13324        }
13325
13326        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13327                int userId) {
13328            if (!sUserManager.exists(userId))
13329                return null;
13330            mFlags = flags;
13331            return super.queryIntent(intent, resolvedType,
13332                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13333                    userId);
13334        }
13335
13336        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13337                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13338            if (!sUserManager.exists(userId))
13339                return null;
13340            if (packageProviders == null) {
13341                return null;
13342            }
13343            mFlags = flags;
13344            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13345            final int N = packageProviders.size();
13346            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13347                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13348
13349            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13350            for (int i = 0; i < N; ++i) {
13351                intentFilters = packageProviders.get(i).intents;
13352                if (intentFilters != null && intentFilters.size() > 0) {
13353                    PackageParser.ProviderIntentInfo[] array =
13354                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13355                    intentFilters.toArray(array);
13356                    listCut.add(array);
13357                }
13358            }
13359            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13360        }
13361
13362        public final void addProvider(PackageParser.Provider p) {
13363            if (mProviders.containsKey(p.getComponentName())) {
13364                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13365                return;
13366            }
13367
13368            mProviders.put(p.getComponentName(), p);
13369            if (DEBUG_SHOW_INFO) {
13370                Log.v(TAG, "  "
13371                        + (p.info.nonLocalizedLabel != null
13372                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13373                Log.v(TAG, "    Class=" + p.info.name);
13374            }
13375            final int NI = p.intents.size();
13376            int j;
13377            for (j = 0; j < NI; j++) {
13378                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13379                if (DEBUG_SHOW_INFO) {
13380                    Log.v(TAG, "    IntentFilter:");
13381                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13382                }
13383                if (!intent.debugCheck()) {
13384                    Log.w(TAG, "==> For Provider " + p.info.name);
13385                }
13386                addFilter(intent);
13387            }
13388        }
13389
13390        public final void removeProvider(PackageParser.Provider p) {
13391            mProviders.remove(p.getComponentName());
13392            if (DEBUG_SHOW_INFO) {
13393                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13394                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13395                Log.v(TAG, "    Class=" + p.info.name);
13396            }
13397            final int NI = p.intents.size();
13398            int j;
13399            for (j = 0; j < NI; j++) {
13400                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13401                if (DEBUG_SHOW_INFO) {
13402                    Log.v(TAG, "    IntentFilter:");
13403                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13404                }
13405                removeFilter(intent);
13406            }
13407        }
13408
13409        @Override
13410        protected boolean allowFilterResult(
13411                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13412            ProviderInfo filterPi = filter.provider.info;
13413            for (int i = dest.size() - 1; i >= 0; i--) {
13414                ProviderInfo destPi = dest.get(i).providerInfo;
13415                if (destPi.name == filterPi.name
13416                        && destPi.packageName == filterPi.packageName) {
13417                    return false;
13418                }
13419            }
13420            return true;
13421        }
13422
13423        @Override
13424        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13425            return new PackageParser.ProviderIntentInfo[size];
13426        }
13427
13428        @Override
13429        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13430            if (!sUserManager.exists(userId))
13431                return true;
13432            PackageParser.Package p = filter.provider.owner;
13433            if (p != null) {
13434                PackageSetting ps = (PackageSetting) p.mExtras;
13435                if (ps != null) {
13436                    // System apps are never considered stopped for purposes of
13437                    // filtering, because there may be no way for the user to
13438                    // actually re-launch them.
13439                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13440                            && ps.getStopped(userId);
13441                }
13442            }
13443            return false;
13444        }
13445
13446        @Override
13447        protected boolean isPackageForFilter(String packageName,
13448                PackageParser.ProviderIntentInfo info) {
13449            return packageName.equals(info.provider.owner.packageName);
13450        }
13451
13452        @Override
13453        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13454                int match, int userId) {
13455            if (!sUserManager.exists(userId))
13456                return null;
13457            final PackageParser.ProviderIntentInfo info = filter;
13458            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13459                return null;
13460            }
13461            final PackageParser.Provider provider = info.provider;
13462            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13463            if (ps == null) {
13464                return null;
13465            }
13466            final PackageUserState userState = ps.readUserState(userId);
13467            final boolean matchVisibleToInstantApp =
13468                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13469            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13470            // throw out filters that aren't visible to instant applications
13471            if (matchVisibleToInstantApp
13472                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13473                return null;
13474            }
13475            // throw out instant application filters if we're not explicitly requesting them
13476            if (!isInstantApp && userState.instantApp) {
13477                return null;
13478            }
13479            // throw out instant application filters if updates are available; will trigger
13480            // instant application resolution
13481            if (userState.instantApp && ps.isUpdateAvailable()) {
13482                return null;
13483            }
13484            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13485                    userState, userId);
13486            if (pi == null) {
13487                return null;
13488            }
13489            final ResolveInfo res = new ResolveInfo();
13490            res.providerInfo = pi;
13491            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13492                res.filter = filter;
13493            }
13494            res.priority = info.getPriority();
13495            res.preferredOrder = provider.owner.mPreferredOrder;
13496            res.match = match;
13497            res.isDefault = info.hasDefault;
13498            res.labelRes = info.labelRes;
13499            res.nonLocalizedLabel = info.nonLocalizedLabel;
13500            res.icon = info.icon;
13501            res.system = res.providerInfo.applicationInfo.isSystemApp();
13502            return res;
13503        }
13504
13505        @Override
13506        protected void sortResults(List<ResolveInfo> results) {
13507            Collections.sort(results, mResolvePrioritySorter);
13508        }
13509
13510        @Override
13511        protected void dumpFilter(PrintWriter out, String prefix,
13512                PackageParser.ProviderIntentInfo filter) {
13513            out.print(prefix);
13514            out.print(
13515                    Integer.toHexString(System.identityHashCode(filter.provider)));
13516            out.print(' ');
13517            filter.provider.printComponentShortName(out);
13518            out.print(" filter ");
13519            out.println(Integer.toHexString(System.identityHashCode(filter)));
13520        }
13521
13522        @Override
13523        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13524            return filter.provider;
13525        }
13526
13527        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13528            PackageParser.Provider provider = (PackageParser.Provider)label;
13529            out.print(prefix); out.print(
13530                    Integer.toHexString(System.identityHashCode(provider)));
13531                    out.print(' ');
13532                    provider.printComponentShortName(out);
13533            if (count > 1) {
13534                out.print(" ("); out.print(count); out.print(" filters)");
13535            }
13536            out.println();
13537        }
13538
13539        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13540                = new ArrayMap<ComponentName, PackageParser.Provider>();
13541        private int mFlags;
13542    }
13543
13544    static final class EphemeralIntentResolver
13545            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13546        /**
13547         * The result that has the highest defined order. Ordering applies on a
13548         * per-package basis. Mapping is from package name to Pair of order and
13549         * EphemeralResolveInfo.
13550         * <p>
13551         * NOTE: This is implemented as a field variable for convenience and efficiency.
13552         * By having a field variable, we're able to track filter ordering as soon as
13553         * a non-zero order is defined. Otherwise, multiple loops across the result set
13554         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13555         * this needs to be contained entirely within {@link #filterResults}.
13556         */
13557        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13558
13559        @Override
13560        protected AuxiliaryResolveInfo[] newArray(int size) {
13561            return new AuxiliaryResolveInfo[size];
13562        }
13563
13564        @Override
13565        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13566            return true;
13567        }
13568
13569        @Override
13570        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13571                int userId) {
13572            if (!sUserManager.exists(userId)) {
13573                return null;
13574            }
13575            final String packageName = responseObj.resolveInfo.getPackageName();
13576            final Integer order = responseObj.getOrder();
13577            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13578                    mOrderResult.get(packageName);
13579            // ordering is enabled and this item's order isn't high enough
13580            if (lastOrderResult != null && lastOrderResult.first >= order) {
13581                return null;
13582            }
13583            final InstantAppResolveInfo res = responseObj.resolveInfo;
13584            if (order > 0) {
13585                // non-zero order, enable ordering
13586                mOrderResult.put(packageName, new Pair<>(order, res));
13587            }
13588            return responseObj;
13589        }
13590
13591        @Override
13592        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13593            // only do work if ordering is enabled [most of the time it won't be]
13594            if (mOrderResult.size() == 0) {
13595                return;
13596            }
13597            int resultSize = results.size();
13598            for (int i = 0; i < resultSize; i++) {
13599                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13600                final String packageName = info.getPackageName();
13601                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13602                if (savedInfo == null) {
13603                    // package doesn't having ordering
13604                    continue;
13605                }
13606                if (savedInfo.second == info) {
13607                    // circled back to the highest ordered item; remove from order list
13608                    mOrderResult.remove(packageName);
13609                    if (mOrderResult.size() == 0) {
13610                        // no more ordered items
13611                        break;
13612                    }
13613                    continue;
13614                }
13615                // item has a worse order, remove it from the result list
13616                results.remove(i);
13617                resultSize--;
13618                i--;
13619            }
13620        }
13621    }
13622
13623    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13624            new Comparator<ResolveInfo>() {
13625        public int compare(ResolveInfo r1, ResolveInfo r2) {
13626            int v1 = r1.priority;
13627            int v2 = r2.priority;
13628            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13629            if (v1 != v2) {
13630                return (v1 > v2) ? -1 : 1;
13631            }
13632            v1 = r1.preferredOrder;
13633            v2 = r2.preferredOrder;
13634            if (v1 != v2) {
13635                return (v1 > v2) ? -1 : 1;
13636            }
13637            if (r1.isDefault != r2.isDefault) {
13638                return r1.isDefault ? -1 : 1;
13639            }
13640            v1 = r1.match;
13641            v2 = r2.match;
13642            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13643            if (v1 != v2) {
13644                return (v1 > v2) ? -1 : 1;
13645            }
13646            if (r1.system != r2.system) {
13647                return r1.system ? -1 : 1;
13648            }
13649            if (r1.activityInfo != null) {
13650                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13651            }
13652            if (r1.serviceInfo != null) {
13653                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13654            }
13655            if (r1.providerInfo != null) {
13656                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13657            }
13658            return 0;
13659        }
13660    };
13661
13662    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13663            new Comparator<ProviderInfo>() {
13664        public int compare(ProviderInfo p1, ProviderInfo p2) {
13665            final int v1 = p1.initOrder;
13666            final int v2 = p2.initOrder;
13667            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13668        }
13669    };
13670
13671    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13672            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13673            final int[] userIds) {
13674        mHandler.post(new Runnable() {
13675            @Override
13676            public void run() {
13677                try {
13678                    final IActivityManager am = ActivityManager.getService();
13679                    if (am == null) return;
13680                    final int[] resolvedUserIds;
13681                    if (userIds == null) {
13682                        resolvedUserIds = am.getRunningUserIds();
13683                    } else {
13684                        resolvedUserIds = userIds;
13685                    }
13686                    for (int id : resolvedUserIds) {
13687                        final Intent intent = new Intent(action,
13688                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13689                        if (extras != null) {
13690                            intent.putExtras(extras);
13691                        }
13692                        if (targetPkg != null) {
13693                            intent.setPackage(targetPkg);
13694                        }
13695                        // Modify the UID when posting to other users
13696                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13697                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13698                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13699                            intent.putExtra(Intent.EXTRA_UID, uid);
13700                        }
13701                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13702                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13703                        if (DEBUG_BROADCASTS) {
13704                            RuntimeException here = new RuntimeException("here");
13705                            here.fillInStackTrace();
13706                            Slog.d(TAG, "Sending to user " + id + ": "
13707                                    + intent.toShortString(false, true, false, false)
13708                                    + " " + intent.getExtras(), here);
13709                        }
13710                        am.broadcastIntent(null, intent, null, finishedReceiver,
13711                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13712                                null, finishedReceiver != null, false, id);
13713                    }
13714                } catch (RemoteException ex) {
13715                }
13716            }
13717        });
13718    }
13719
13720    /**
13721     * Check if the external storage media is available. This is true if there
13722     * is a mounted external storage medium or if the external storage is
13723     * emulated.
13724     */
13725    private boolean isExternalMediaAvailable() {
13726        return mMediaMounted || Environment.isExternalStorageEmulated();
13727    }
13728
13729    @Override
13730    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13732            return null;
13733        }
13734        // writer
13735        synchronized (mPackages) {
13736            if (!isExternalMediaAvailable()) {
13737                // If the external storage is no longer mounted at this point,
13738                // the caller may not have been able to delete all of this
13739                // packages files and can not delete any more.  Bail.
13740                return null;
13741            }
13742            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13743            if (lastPackage != null) {
13744                pkgs.remove(lastPackage);
13745            }
13746            if (pkgs.size() > 0) {
13747                return pkgs.get(0);
13748            }
13749        }
13750        return null;
13751    }
13752
13753    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13754        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13755                userId, andCode ? 1 : 0, packageName);
13756        if (mSystemReady) {
13757            msg.sendToTarget();
13758        } else {
13759            if (mPostSystemReadyMessages == null) {
13760                mPostSystemReadyMessages = new ArrayList<>();
13761            }
13762            mPostSystemReadyMessages.add(msg);
13763        }
13764    }
13765
13766    void startCleaningPackages() {
13767        // reader
13768        if (!isExternalMediaAvailable()) {
13769            return;
13770        }
13771        synchronized (mPackages) {
13772            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13773                return;
13774            }
13775        }
13776        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13777        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13778        IActivityManager am = ActivityManager.getService();
13779        if (am != null) {
13780            int dcsUid = -1;
13781            synchronized (mPackages) {
13782                if (!mDefaultContainerWhitelisted) {
13783                    mDefaultContainerWhitelisted = true;
13784                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13785                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13786                }
13787            }
13788            try {
13789                if (dcsUid > 0) {
13790                    am.backgroundWhitelistUid(dcsUid);
13791                }
13792                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13793                        UserHandle.USER_SYSTEM);
13794            } catch (RemoteException e) {
13795            }
13796        }
13797    }
13798
13799    @Override
13800    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13801            int installFlags, String installerPackageName, int userId) {
13802        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13803
13804        final int callingUid = Binder.getCallingUid();
13805        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13806                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13807
13808        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13809            try {
13810                if (observer != null) {
13811                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13812                }
13813            } catch (RemoteException re) {
13814            }
13815            return;
13816        }
13817
13818        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13819            installFlags |= PackageManager.INSTALL_FROM_ADB;
13820
13821        } else {
13822            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13823            // about installerPackageName.
13824
13825            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13826            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13827        }
13828
13829        UserHandle user;
13830        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13831            user = UserHandle.ALL;
13832        } else {
13833            user = new UserHandle(userId);
13834        }
13835
13836        // Only system components can circumvent runtime permissions when installing.
13837        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13838                && mContext.checkCallingOrSelfPermission(Manifest.permission
13839                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13840            throw new SecurityException("You need the "
13841                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13842                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13843        }
13844
13845        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13846                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13847            throw new IllegalArgumentException(
13848                    "New installs into ASEC containers no longer supported");
13849        }
13850
13851        final File originFile = new File(originPath);
13852        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13853
13854        final Message msg = mHandler.obtainMessage(INIT_COPY);
13855        final VerificationInfo verificationInfo = new VerificationInfo(
13856                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13857        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13858                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13859                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13860                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13861        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13862        msg.obj = params;
13863
13864        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13865                System.identityHashCode(msg.obj));
13866        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13867                System.identityHashCode(msg.obj));
13868
13869        mHandler.sendMessage(msg);
13870    }
13871
13872
13873    /**
13874     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13875     * it is acting on behalf on an enterprise or the user).
13876     *
13877     * Note that the ordering of the conditionals in this method is important. The checks we perform
13878     * are as follows, in this order:
13879     *
13880     * 1) If the install is being performed by a system app, we can trust the app to have set the
13881     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13882     *    what it is.
13883     * 2) If the install is being performed by a device or profile owner app, the install reason
13884     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13885     *    set the install reason correctly. If the app targets an older SDK version where install
13886     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13887     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13888     * 3) In all other cases, the install is being performed by a regular app that is neither part
13889     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13890     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13891     *    set to enterprise policy and if so, change it to unknown instead.
13892     */
13893    private int fixUpInstallReason(String installerPackageName, int installerUid,
13894            int installReason) {
13895        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13896                == PERMISSION_GRANTED) {
13897            // If the install is being performed by a system app, we trust that app to have set the
13898            // install reason correctly.
13899            return installReason;
13900        }
13901
13902        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13903            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13904        if (dpm != null) {
13905            ComponentName owner = null;
13906            try {
13907                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13908                if (owner == null) {
13909                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13910                }
13911            } catch (RemoteException e) {
13912            }
13913            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13914                // If the install is being performed by a device or profile owner, the install
13915                // reason should be enterprise policy.
13916                return PackageManager.INSTALL_REASON_POLICY;
13917            }
13918        }
13919
13920        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13921            // If the install is being performed by a regular app (i.e. neither system app nor
13922            // device or profile owner), we have no reason to believe that the app is acting on
13923            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13924            // change it to unknown instead.
13925            return PackageManager.INSTALL_REASON_UNKNOWN;
13926        }
13927
13928        // If the install is being performed by a regular app and the install reason was set to any
13929        // value but enterprise policy, leave the install reason unchanged.
13930        return installReason;
13931    }
13932
13933    void installStage(String packageName, File stagedDir,
13934            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13935            String installerPackageName, int installerUid, UserHandle user,
13936            Certificate[][] certificates) {
13937        if (DEBUG_EPHEMERAL) {
13938            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13939                Slog.d(TAG, "Ephemeral install of " + packageName);
13940            }
13941        }
13942        final VerificationInfo verificationInfo = new VerificationInfo(
13943                sessionParams.originatingUri, sessionParams.referrerUri,
13944                sessionParams.originatingUid, installerUid);
13945
13946        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13947
13948        final Message msg = mHandler.obtainMessage(INIT_COPY);
13949        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13950                sessionParams.installReason);
13951        final InstallParams params = new InstallParams(origin, null, observer,
13952                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13953                verificationInfo, user, sessionParams.abiOverride,
13954                sessionParams.grantedRuntimePermissions, certificates, installReason);
13955        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13956        msg.obj = params;
13957
13958        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13959                System.identityHashCode(msg.obj));
13960        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13961                System.identityHashCode(msg.obj));
13962
13963        mHandler.sendMessage(msg);
13964    }
13965
13966    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13967            int userId) {
13968        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13969        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13970                false /*startReceiver*/, pkgSetting.appId, userId);
13971
13972        // Send a session commit broadcast
13973        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13974        info.installReason = pkgSetting.getInstallReason(userId);
13975        info.appPackageName = packageName;
13976        sendSessionCommitBroadcast(info, userId);
13977    }
13978
13979    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13980            boolean includeStopped, int appId, int... userIds) {
13981        if (ArrayUtils.isEmpty(userIds)) {
13982            return;
13983        }
13984        Bundle extras = new Bundle(1);
13985        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13986        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13987
13988        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13989                packageName, extras, 0, null, null, userIds);
13990        if (sendBootCompleted) {
13991            mHandler.post(() -> {
13992                        for (int userId : userIds) {
13993                            sendBootCompletedBroadcastToSystemApp(
13994                                    packageName, includeStopped, userId);
13995                        }
13996                    }
13997            );
13998        }
13999    }
14000
14001    /**
14002     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14003     * automatically without needing an explicit launch.
14004     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14005     */
14006    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14007            int userId) {
14008        // If user is not running, the app didn't miss any broadcast
14009        if (!mUserManagerInternal.isUserRunning(userId)) {
14010            return;
14011        }
14012        final IActivityManager am = ActivityManager.getService();
14013        try {
14014            // Deliver LOCKED_BOOT_COMPLETED first
14015            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14016                    .setPackage(packageName);
14017            if (includeStopped) {
14018                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14019            }
14020            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14021            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14022                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14023
14024            // Deliver BOOT_COMPLETED only if user is unlocked
14025            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14026                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14027                if (includeStopped) {
14028                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14029                }
14030                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14031                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14032            }
14033        } catch (RemoteException e) {
14034            throw e.rethrowFromSystemServer();
14035        }
14036    }
14037
14038    @Override
14039    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14040            int userId) {
14041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14042        PackageSetting pkgSetting;
14043        final int callingUid = Binder.getCallingUid();
14044        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14045                true /* requireFullPermission */, true /* checkShell */,
14046                "setApplicationHiddenSetting for user " + userId);
14047
14048        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14049            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14050            return false;
14051        }
14052
14053        long callingId = Binder.clearCallingIdentity();
14054        try {
14055            boolean sendAdded = false;
14056            boolean sendRemoved = false;
14057            // writer
14058            synchronized (mPackages) {
14059                pkgSetting = mSettings.mPackages.get(packageName);
14060                if (pkgSetting == null) {
14061                    return false;
14062                }
14063                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14064                    return false;
14065                }
14066                // Do not allow "android" is being disabled
14067                if ("android".equals(packageName)) {
14068                    Slog.w(TAG, "Cannot hide package: android");
14069                    return false;
14070                }
14071                // Cannot hide static shared libs as they are considered
14072                // a part of the using app (emulating static linking). Also
14073                // static libs are installed always on internal storage.
14074                PackageParser.Package pkg = mPackages.get(packageName);
14075                if (pkg != null && pkg.staticSharedLibName != null) {
14076                    Slog.w(TAG, "Cannot hide package: " + packageName
14077                            + " providing static shared library: "
14078                            + pkg.staticSharedLibName);
14079                    return false;
14080                }
14081                // Only allow protected packages to hide themselves.
14082                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14083                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14084                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14085                    return false;
14086                }
14087
14088                if (pkgSetting.getHidden(userId) != hidden) {
14089                    pkgSetting.setHidden(hidden, userId);
14090                    mSettings.writePackageRestrictionsLPr(userId);
14091                    if (hidden) {
14092                        sendRemoved = true;
14093                    } else {
14094                        sendAdded = true;
14095                    }
14096                }
14097            }
14098            if (sendAdded) {
14099                sendPackageAddedForUser(packageName, pkgSetting, userId);
14100                return true;
14101            }
14102            if (sendRemoved) {
14103                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14104                        "hiding pkg");
14105                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14106                return true;
14107            }
14108        } finally {
14109            Binder.restoreCallingIdentity(callingId);
14110        }
14111        return false;
14112    }
14113
14114    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14115            int userId) {
14116        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14117        info.removedPackage = packageName;
14118        info.installerPackageName = pkgSetting.installerPackageName;
14119        info.removedUsers = new int[] {userId};
14120        info.broadcastUsers = new int[] {userId};
14121        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14122        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14123    }
14124
14125    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14126        if (pkgList.length > 0) {
14127            Bundle extras = new Bundle(1);
14128            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14129
14130            sendPackageBroadcast(
14131                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14132                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14133                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14134                    new int[] {userId});
14135        }
14136    }
14137
14138    /**
14139     * Returns true if application is not found or there was an error. Otherwise it returns
14140     * the hidden state of the package for the given user.
14141     */
14142    @Override
14143    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14144        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14145        final int callingUid = Binder.getCallingUid();
14146        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14147                true /* requireFullPermission */, false /* checkShell */,
14148                "getApplicationHidden for user " + userId);
14149        PackageSetting ps;
14150        long callingId = Binder.clearCallingIdentity();
14151        try {
14152            // writer
14153            synchronized (mPackages) {
14154                ps = mSettings.mPackages.get(packageName);
14155                if (ps == null) {
14156                    return true;
14157                }
14158                if (filterAppAccessLPr(ps, callingUid, userId)) {
14159                    return true;
14160                }
14161                return ps.getHidden(userId);
14162            }
14163        } finally {
14164            Binder.restoreCallingIdentity(callingId);
14165        }
14166    }
14167
14168    /**
14169     * @hide
14170     */
14171    @Override
14172    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14173            int installReason) {
14174        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14175                null);
14176        PackageSetting pkgSetting;
14177        final int callingUid = Binder.getCallingUid();
14178        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14179                true /* requireFullPermission */, true /* checkShell */,
14180                "installExistingPackage for user " + userId);
14181        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14182            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14183        }
14184
14185        long callingId = Binder.clearCallingIdentity();
14186        try {
14187            boolean installed = false;
14188            final boolean instantApp =
14189                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14190            final boolean fullApp =
14191                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14192
14193            // writer
14194            synchronized (mPackages) {
14195                pkgSetting = mSettings.mPackages.get(packageName);
14196                if (pkgSetting == null) {
14197                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14198                }
14199                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14200                    // only allow the existing package to be used if it's installed as a full
14201                    // application for at least one user
14202                    boolean installAllowed = false;
14203                    for (int checkUserId : sUserManager.getUserIds()) {
14204                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14205                        if (installAllowed) {
14206                            break;
14207                        }
14208                    }
14209                    if (!installAllowed) {
14210                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14211                    }
14212                }
14213                if (!pkgSetting.getInstalled(userId)) {
14214                    pkgSetting.setInstalled(true, userId);
14215                    pkgSetting.setHidden(false, userId);
14216                    pkgSetting.setInstallReason(installReason, userId);
14217                    mSettings.writePackageRestrictionsLPr(userId);
14218                    mSettings.writeKernelMappingLPr(pkgSetting);
14219                    installed = true;
14220                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14221                    // upgrade app from instant to full; we don't allow app downgrade
14222                    installed = true;
14223                }
14224                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14225            }
14226
14227            if (installed) {
14228                if (pkgSetting.pkg != null) {
14229                    synchronized (mInstallLock) {
14230                        // We don't need to freeze for a brand new install
14231                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14232                    }
14233                }
14234                sendPackageAddedForUser(packageName, pkgSetting, userId);
14235                synchronized (mPackages) {
14236                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14237                }
14238            }
14239        } finally {
14240            Binder.restoreCallingIdentity(callingId);
14241        }
14242
14243        return PackageManager.INSTALL_SUCCEEDED;
14244    }
14245
14246    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14247            boolean instantApp, boolean fullApp) {
14248        // no state specified; do nothing
14249        if (!instantApp && !fullApp) {
14250            return;
14251        }
14252        if (userId != UserHandle.USER_ALL) {
14253            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14254                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14255            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14256                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14257            }
14258        } else {
14259            for (int currentUserId : sUserManager.getUserIds()) {
14260                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14261                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14262                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14263                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14264                }
14265            }
14266        }
14267    }
14268
14269    boolean isUserRestricted(int userId, String restrictionKey) {
14270        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14271        if (restrictions.getBoolean(restrictionKey, false)) {
14272            Log.w(TAG, "User is restricted: " + restrictionKey);
14273            return true;
14274        }
14275        return false;
14276    }
14277
14278    @Override
14279    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14280            int userId) {
14281        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14282        final int callingUid = Binder.getCallingUid();
14283        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14284                true /* requireFullPermission */, true /* checkShell */,
14285                "setPackagesSuspended for user " + userId);
14286
14287        if (ArrayUtils.isEmpty(packageNames)) {
14288            return packageNames;
14289        }
14290
14291        // List of package names for whom the suspended state has changed.
14292        List<String> changedPackages = new ArrayList<>(packageNames.length);
14293        // List of package names for whom the suspended state is not set as requested in this
14294        // method.
14295        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14296        long callingId = Binder.clearCallingIdentity();
14297        try {
14298            for (int i = 0; i < packageNames.length; i++) {
14299                String packageName = packageNames[i];
14300                boolean changed = false;
14301                final int appId;
14302                synchronized (mPackages) {
14303                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14304                    if (pkgSetting == null
14305                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14306                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14307                                + "\". Skipping suspending/un-suspending.");
14308                        unactionedPackages.add(packageName);
14309                        continue;
14310                    }
14311                    appId = pkgSetting.appId;
14312                    if (pkgSetting.getSuspended(userId) != suspended) {
14313                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14314                            unactionedPackages.add(packageName);
14315                            continue;
14316                        }
14317                        pkgSetting.setSuspended(suspended, userId);
14318                        mSettings.writePackageRestrictionsLPr(userId);
14319                        changed = true;
14320                        changedPackages.add(packageName);
14321                    }
14322                }
14323
14324                if (changed && suspended) {
14325                    killApplication(packageName, UserHandle.getUid(userId, appId),
14326                            "suspending package");
14327                }
14328            }
14329        } finally {
14330            Binder.restoreCallingIdentity(callingId);
14331        }
14332
14333        if (!changedPackages.isEmpty()) {
14334            sendPackagesSuspendedForUser(changedPackages.toArray(
14335                    new String[changedPackages.size()]), userId, suspended);
14336        }
14337
14338        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14339    }
14340
14341    @Override
14342    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14343        final int callingUid = Binder.getCallingUid();
14344        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14345                true /* requireFullPermission */, false /* checkShell */,
14346                "isPackageSuspendedForUser for user " + userId);
14347        synchronized (mPackages) {
14348            final PackageSetting ps = mSettings.mPackages.get(packageName);
14349            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14350                throw new IllegalArgumentException("Unknown target package: " + packageName);
14351            }
14352            return ps.getSuspended(userId);
14353        }
14354    }
14355
14356    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14357        if (isPackageDeviceAdmin(packageName, userId)) {
14358            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14359                    + "\": has an active device admin");
14360            return false;
14361        }
14362
14363        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14364        if (packageName.equals(activeLauncherPackageName)) {
14365            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14366                    + "\": contains the active launcher");
14367            return false;
14368        }
14369
14370        if (packageName.equals(mRequiredInstallerPackage)) {
14371            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14372                    + "\": required for package installation");
14373            return false;
14374        }
14375
14376        if (packageName.equals(mRequiredUninstallerPackage)) {
14377            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14378                    + "\": required for package uninstallation");
14379            return false;
14380        }
14381
14382        if (packageName.equals(mRequiredVerifierPackage)) {
14383            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14384                    + "\": required for package verification");
14385            return false;
14386        }
14387
14388        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14389            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14390                    + "\": is the default dialer");
14391            return false;
14392        }
14393
14394        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14395            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14396                    + "\": protected package");
14397            return false;
14398        }
14399
14400        // Cannot suspend static shared libs as they are considered
14401        // a part of the using app (emulating static linking). Also
14402        // static libs are installed always on internal storage.
14403        PackageParser.Package pkg = mPackages.get(packageName);
14404        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14405            Slog.w(TAG, "Cannot suspend package: " + packageName
14406                    + " providing static shared library: "
14407                    + pkg.staticSharedLibName);
14408            return false;
14409        }
14410
14411        return true;
14412    }
14413
14414    private String getActiveLauncherPackageName(int userId) {
14415        Intent intent = new Intent(Intent.ACTION_MAIN);
14416        intent.addCategory(Intent.CATEGORY_HOME);
14417        ResolveInfo resolveInfo = resolveIntent(
14418                intent,
14419                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14420                PackageManager.MATCH_DEFAULT_ONLY,
14421                userId);
14422
14423        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14424    }
14425
14426    private String getDefaultDialerPackageName(int userId) {
14427        synchronized (mPackages) {
14428            return mSettings.getDefaultDialerPackageNameLPw(userId);
14429        }
14430    }
14431
14432    @Override
14433    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14434        mContext.enforceCallingOrSelfPermission(
14435                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14436                "Only package verification agents can verify applications");
14437
14438        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14439        final PackageVerificationResponse response = new PackageVerificationResponse(
14440                verificationCode, Binder.getCallingUid());
14441        msg.arg1 = id;
14442        msg.obj = response;
14443        mHandler.sendMessage(msg);
14444    }
14445
14446    @Override
14447    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14448            long millisecondsToDelay) {
14449        mContext.enforceCallingOrSelfPermission(
14450                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14451                "Only package verification agents can extend verification timeouts");
14452
14453        final PackageVerificationState state = mPendingVerification.get(id);
14454        final PackageVerificationResponse response = new PackageVerificationResponse(
14455                verificationCodeAtTimeout, Binder.getCallingUid());
14456
14457        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14458            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14459        }
14460        if (millisecondsToDelay < 0) {
14461            millisecondsToDelay = 0;
14462        }
14463        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14464                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14465            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14466        }
14467
14468        if ((state != null) && !state.timeoutExtended()) {
14469            state.extendTimeout();
14470
14471            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14472            msg.arg1 = id;
14473            msg.obj = response;
14474            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14475        }
14476    }
14477
14478    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14479            int verificationCode, UserHandle user) {
14480        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14481        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14482        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14483        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14484        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14485
14486        mContext.sendBroadcastAsUser(intent, user,
14487                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14488    }
14489
14490    private ComponentName matchComponentForVerifier(String packageName,
14491            List<ResolveInfo> receivers) {
14492        ActivityInfo targetReceiver = null;
14493
14494        final int NR = receivers.size();
14495        for (int i = 0; i < NR; i++) {
14496            final ResolveInfo info = receivers.get(i);
14497            if (info.activityInfo == null) {
14498                continue;
14499            }
14500
14501            if (packageName.equals(info.activityInfo.packageName)) {
14502                targetReceiver = info.activityInfo;
14503                break;
14504            }
14505        }
14506
14507        if (targetReceiver == null) {
14508            return null;
14509        }
14510
14511        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14512    }
14513
14514    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14515            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14516        if (pkgInfo.verifiers.length == 0) {
14517            return null;
14518        }
14519
14520        final int N = pkgInfo.verifiers.length;
14521        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14522        for (int i = 0; i < N; i++) {
14523            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14524
14525            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14526                    receivers);
14527            if (comp == null) {
14528                continue;
14529            }
14530
14531            final int verifierUid = getUidForVerifier(verifierInfo);
14532            if (verifierUid == -1) {
14533                continue;
14534            }
14535
14536            if (DEBUG_VERIFY) {
14537                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14538                        + " with the correct signature");
14539            }
14540            sufficientVerifiers.add(comp);
14541            verificationState.addSufficientVerifier(verifierUid);
14542        }
14543
14544        return sufficientVerifiers;
14545    }
14546
14547    private int getUidForVerifier(VerifierInfo verifierInfo) {
14548        synchronized (mPackages) {
14549            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14550            if (pkg == null) {
14551                return -1;
14552            } else if (pkg.mSignatures.length != 1) {
14553                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14554                        + " has more than one signature; ignoring");
14555                return -1;
14556            }
14557
14558            /*
14559             * If the public key of the package's signature does not match
14560             * our expected public key, then this is a different package and
14561             * we should skip.
14562             */
14563
14564            final byte[] expectedPublicKey;
14565            try {
14566                final Signature verifierSig = pkg.mSignatures[0];
14567                final PublicKey publicKey = verifierSig.getPublicKey();
14568                expectedPublicKey = publicKey.getEncoded();
14569            } catch (CertificateException e) {
14570                return -1;
14571            }
14572
14573            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14574
14575            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14576                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14577                        + " does not have the expected public key; ignoring");
14578                return -1;
14579            }
14580
14581            return pkg.applicationInfo.uid;
14582        }
14583    }
14584
14585    @Override
14586    public void finishPackageInstall(int token, boolean didLaunch) {
14587        enforceSystemOrRoot("Only the system is allowed to finish installs");
14588
14589        if (DEBUG_INSTALL) {
14590            Slog.v(TAG, "BM finishing package install for " + token);
14591        }
14592        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14593
14594        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14595        mHandler.sendMessage(msg);
14596    }
14597
14598    /**
14599     * Get the verification agent timeout.  Used for both the APK verifier and the
14600     * intent filter verifier.
14601     *
14602     * @return verification timeout in milliseconds
14603     */
14604    private long getVerificationTimeout() {
14605        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14606                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14607                DEFAULT_VERIFICATION_TIMEOUT);
14608    }
14609
14610    /**
14611     * Get the default verification agent response code.
14612     *
14613     * @return default verification response code
14614     */
14615    private int getDefaultVerificationResponse(UserHandle user) {
14616        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14617            return PackageManager.VERIFICATION_REJECT;
14618        }
14619        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14620                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14621                DEFAULT_VERIFICATION_RESPONSE);
14622    }
14623
14624    /**
14625     * Check whether or not package verification has been enabled.
14626     *
14627     * @return true if verification should be performed
14628     */
14629    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14630        if (!DEFAULT_VERIFY_ENABLE) {
14631            return false;
14632        }
14633
14634        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14635
14636        // Check if installing from ADB
14637        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14638            // Do not run verification in a test harness environment
14639            if (ActivityManager.isRunningInTestHarness()) {
14640                return false;
14641            }
14642            if (ensureVerifyAppsEnabled) {
14643                return true;
14644            }
14645            // Check if the developer does not want package verification for ADB installs
14646            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14647                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14648                return false;
14649            }
14650        } else {
14651            // only when not installed from ADB, skip verification for instant apps when
14652            // the installer and verifier are the same.
14653            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14654                if (mInstantAppInstallerActivity != null
14655                        && mInstantAppInstallerActivity.packageName.equals(
14656                                mRequiredVerifierPackage)) {
14657                    try {
14658                        mContext.getSystemService(AppOpsManager.class)
14659                                .checkPackage(installerUid, mRequiredVerifierPackage);
14660                        if (DEBUG_VERIFY) {
14661                            Slog.i(TAG, "disable verification for instant app");
14662                        }
14663                        return false;
14664                    } catch (SecurityException ignore) { }
14665                }
14666            }
14667        }
14668
14669        if (ensureVerifyAppsEnabled) {
14670            return true;
14671        }
14672
14673        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14674                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14675    }
14676
14677    @Override
14678    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14679            throws RemoteException {
14680        mContext.enforceCallingOrSelfPermission(
14681                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14682                "Only intentfilter verification agents can verify applications");
14683
14684        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14685        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14686                Binder.getCallingUid(), verificationCode, failedDomains);
14687        msg.arg1 = id;
14688        msg.obj = response;
14689        mHandler.sendMessage(msg);
14690    }
14691
14692    @Override
14693    public int getIntentVerificationStatus(String packageName, int userId) {
14694        final int callingUid = Binder.getCallingUid();
14695        if (UserHandle.getUserId(callingUid) != userId) {
14696            mContext.enforceCallingOrSelfPermission(
14697                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14698                    "getIntentVerificationStatus" + userId);
14699        }
14700        if (getInstantAppPackageName(callingUid) != null) {
14701            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14702        }
14703        synchronized (mPackages) {
14704            final PackageSetting ps = mSettings.mPackages.get(packageName);
14705            if (ps == null
14706                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14707                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14708            }
14709            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14710        }
14711    }
14712
14713    @Override
14714    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14715        mContext.enforceCallingOrSelfPermission(
14716                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14717
14718        boolean result = false;
14719        synchronized (mPackages) {
14720            final PackageSetting ps = mSettings.mPackages.get(packageName);
14721            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14722                return false;
14723            }
14724            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14725        }
14726        if (result) {
14727            scheduleWritePackageRestrictionsLocked(userId);
14728        }
14729        return result;
14730    }
14731
14732    @Override
14733    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14734            String packageName) {
14735        final int callingUid = Binder.getCallingUid();
14736        if (getInstantAppPackageName(callingUid) != null) {
14737            return ParceledListSlice.emptyList();
14738        }
14739        synchronized (mPackages) {
14740            final PackageSetting ps = mSettings.mPackages.get(packageName);
14741            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14742                return ParceledListSlice.emptyList();
14743            }
14744            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14745        }
14746    }
14747
14748    @Override
14749    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14750        if (TextUtils.isEmpty(packageName)) {
14751            return ParceledListSlice.emptyList();
14752        }
14753        final int callingUid = Binder.getCallingUid();
14754        final int callingUserId = UserHandle.getUserId(callingUid);
14755        synchronized (mPackages) {
14756            PackageParser.Package pkg = mPackages.get(packageName);
14757            if (pkg == null || pkg.activities == null) {
14758                return ParceledListSlice.emptyList();
14759            }
14760            if (pkg.mExtras == null) {
14761                return ParceledListSlice.emptyList();
14762            }
14763            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14764            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14765                return ParceledListSlice.emptyList();
14766            }
14767            final int count = pkg.activities.size();
14768            ArrayList<IntentFilter> result = new ArrayList<>();
14769            for (int n=0; n<count; n++) {
14770                PackageParser.Activity activity = pkg.activities.get(n);
14771                if (activity.intents != null && activity.intents.size() > 0) {
14772                    result.addAll(activity.intents);
14773                }
14774            }
14775            return new ParceledListSlice<>(result);
14776        }
14777    }
14778
14779    @Override
14780    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14781        mContext.enforceCallingOrSelfPermission(
14782                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14783        if (UserHandle.getCallingUserId() != userId) {
14784            mContext.enforceCallingOrSelfPermission(
14785                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14786        }
14787
14788        synchronized (mPackages) {
14789            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14790            if (packageName != null) {
14791                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14792                        packageName, userId);
14793            }
14794            return result;
14795        }
14796    }
14797
14798    @Override
14799    public String getDefaultBrowserPackageName(int userId) {
14800        if (UserHandle.getCallingUserId() != userId) {
14801            mContext.enforceCallingOrSelfPermission(
14802                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14803        }
14804        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14805            return null;
14806        }
14807        synchronized (mPackages) {
14808            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14809        }
14810    }
14811
14812    /**
14813     * Get the "allow unknown sources" setting.
14814     *
14815     * @return the current "allow unknown sources" setting
14816     */
14817    private int getUnknownSourcesSettings() {
14818        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14819                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14820                -1);
14821    }
14822
14823    @Override
14824    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14825        final int callingUid = Binder.getCallingUid();
14826        if (getInstantAppPackageName(callingUid) != null) {
14827            return;
14828        }
14829        // writer
14830        synchronized (mPackages) {
14831            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14832            if (targetPackageSetting == null
14833                    || filterAppAccessLPr(
14834                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14835                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14836            }
14837
14838            PackageSetting installerPackageSetting;
14839            if (installerPackageName != null) {
14840                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14841                if (installerPackageSetting == null) {
14842                    throw new IllegalArgumentException("Unknown installer package: "
14843                            + installerPackageName);
14844                }
14845            } else {
14846                installerPackageSetting = null;
14847            }
14848
14849            Signature[] callerSignature;
14850            Object obj = mSettings.getUserIdLPr(callingUid);
14851            if (obj != null) {
14852                if (obj instanceof SharedUserSetting) {
14853                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14854                } else if (obj instanceof PackageSetting) {
14855                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14856                } else {
14857                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14858                }
14859            } else {
14860                throw new SecurityException("Unknown calling UID: " + callingUid);
14861            }
14862
14863            // Verify: can't set installerPackageName to a package that is
14864            // not signed with the same cert as the caller.
14865            if (installerPackageSetting != null) {
14866                if (compareSignatures(callerSignature,
14867                        installerPackageSetting.signatures.mSignatures)
14868                        != PackageManager.SIGNATURE_MATCH) {
14869                    throw new SecurityException(
14870                            "Caller does not have same cert as new installer package "
14871                            + installerPackageName);
14872                }
14873            }
14874
14875            // Verify: if target already has an installer package, it must
14876            // be signed with the same cert as the caller.
14877            if (targetPackageSetting.installerPackageName != null) {
14878                PackageSetting setting = mSettings.mPackages.get(
14879                        targetPackageSetting.installerPackageName);
14880                // If the currently set package isn't valid, then it's always
14881                // okay to change it.
14882                if (setting != null) {
14883                    if (compareSignatures(callerSignature,
14884                            setting.signatures.mSignatures)
14885                            != PackageManager.SIGNATURE_MATCH) {
14886                        throw new SecurityException(
14887                                "Caller does not have same cert as old installer package "
14888                                + targetPackageSetting.installerPackageName);
14889                    }
14890                }
14891            }
14892
14893            // Okay!
14894            targetPackageSetting.installerPackageName = installerPackageName;
14895            if (installerPackageName != null) {
14896                mSettings.mInstallerPackages.add(installerPackageName);
14897            }
14898            scheduleWriteSettingsLocked();
14899        }
14900    }
14901
14902    @Override
14903    public void setApplicationCategoryHint(String packageName, int categoryHint,
14904            String callerPackageName) {
14905        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14906            throw new SecurityException("Instant applications don't have access to this method");
14907        }
14908        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14909                callerPackageName);
14910        synchronized (mPackages) {
14911            PackageSetting ps = mSettings.mPackages.get(packageName);
14912            if (ps == null) {
14913                throw new IllegalArgumentException("Unknown target package " + packageName);
14914            }
14915            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14916                throw new IllegalArgumentException("Unknown target package " + packageName);
14917            }
14918            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14919                throw new IllegalArgumentException("Calling package " + callerPackageName
14920                        + " is not installer for " + packageName);
14921            }
14922
14923            if (ps.categoryHint != categoryHint) {
14924                ps.categoryHint = categoryHint;
14925                scheduleWriteSettingsLocked();
14926            }
14927        }
14928    }
14929
14930    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14931        // Queue up an async operation since the package installation may take a little while.
14932        mHandler.post(new Runnable() {
14933            public void run() {
14934                mHandler.removeCallbacks(this);
14935                 // Result object to be returned
14936                PackageInstalledInfo res = new PackageInstalledInfo();
14937                res.setReturnCode(currentStatus);
14938                res.uid = -1;
14939                res.pkg = null;
14940                res.removedInfo = null;
14941                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14942                    args.doPreInstall(res.returnCode);
14943                    synchronized (mInstallLock) {
14944                        installPackageTracedLI(args, res);
14945                    }
14946                    args.doPostInstall(res.returnCode, res.uid);
14947                }
14948
14949                // A restore should be performed at this point if (a) the install
14950                // succeeded, (b) the operation is not an update, and (c) the new
14951                // package has not opted out of backup participation.
14952                final boolean update = res.removedInfo != null
14953                        && res.removedInfo.removedPackage != null;
14954                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14955                boolean doRestore = !update
14956                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14957
14958                // Set up the post-install work request bookkeeping.  This will be used
14959                // and cleaned up by the post-install event handling regardless of whether
14960                // there's a restore pass performed.  Token values are >= 1.
14961                int token;
14962                if (mNextInstallToken < 0) mNextInstallToken = 1;
14963                token = mNextInstallToken++;
14964
14965                PostInstallData data = new PostInstallData(args, res);
14966                mRunningInstalls.put(token, data);
14967                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14968
14969                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14970                    // Pass responsibility to the Backup Manager.  It will perform a
14971                    // restore if appropriate, then pass responsibility back to the
14972                    // Package Manager to run the post-install observer callbacks
14973                    // and broadcasts.
14974                    IBackupManager bm = IBackupManager.Stub.asInterface(
14975                            ServiceManager.getService(Context.BACKUP_SERVICE));
14976                    if (bm != null) {
14977                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14978                                + " to BM for possible restore");
14979                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14980                        try {
14981                            // TODO: http://b/22388012
14982                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14983                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14984                            } else {
14985                                doRestore = false;
14986                            }
14987                        } catch (RemoteException e) {
14988                            // can't happen; the backup manager is local
14989                        } catch (Exception e) {
14990                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14991                            doRestore = false;
14992                        }
14993                    } else {
14994                        Slog.e(TAG, "Backup Manager not found!");
14995                        doRestore = false;
14996                    }
14997                }
14998
14999                if (!doRestore) {
15000                    // No restore possible, or the Backup Manager was mysteriously not
15001                    // available -- just fire the post-install work request directly.
15002                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15003
15004                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15005
15006                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15007                    mHandler.sendMessage(msg);
15008                }
15009            }
15010        });
15011    }
15012
15013    /**
15014     * Callback from PackageSettings whenever an app is first transitioned out of the
15015     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15016     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15017     * here whether the app is the target of an ongoing install, and only send the
15018     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15019     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15020     * handling.
15021     */
15022    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15023        // Serialize this with the rest of the install-process message chain.  In the
15024        // restore-at-install case, this Runnable will necessarily run before the
15025        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15026        // are coherent.  In the non-restore case, the app has already completed install
15027        // and been launched through some other means, so it is not in a problematic
15028        // state for observers to see the FIRST_LAUNCH signal.
15029        mHandler.post(new Runnable() {
15030            @Override
15031            public void run() {
15032                for (int i = 0; i < mRunningInstalls.size(); i++) {
15033                    final PostInstallData data = mRunningInstalls.valueAt(i);
15034                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15035                        continue;
15036                    }
15037                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15038                        // right package; but is it for the right user?
15039                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15040                            if (userId == data.res.newUsers[uIndex]) {
15041                                if (DEBUG_BACKUP) {
15042                                    Slog.i(TAG, "Package " + pkgName
15043                                            + " being restored so deferring FIRST_LAUNCH");
15044                                }
15045                                return;
15046                            }
15047                        }
15048                    }
15049                }
15050                // didn't find it, so not being restored
15051                if (DEBUG_BACKUP) {
15052                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15053                }
15054                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15055            }
15056        });
15057    }
15058
15059    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15060        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15061                installerPkg, null, userIds);
15062    }
15063
15064    private abstract class HandlerParams {
15065        private static final int MAX_RETRIES = 4;
15066
15067        /**
15068         * Number of times startCopy() has been attempted and had a non-fatal
15069         * error.
15070         */
15071        private int mRetries = 0;
15072
15073        /** User handle for the user requesting the information or installation. */
15074        private final UserHandle mUser;
15075        String traceMethod;
15076        int traceCookie;
15077
15078        HandlerParams(UserHandle user) {
15079            mUser = user;
15080        }
15081
15082        UserHandle getUser() {
15083            return mUser;
15084        }
15085
15086        HandlerParams setTraceMethod(String traceMethod) {
15087            this.traceMethod = traceMethod;
15088            return this;
15089        }
15090
15091        HandlerParams setTraceCookie(int traceCookie) {
15092            this.traceCookie = traceCookie;
15093            return this;
15094        }
15095
15096        final boolean startCopy() {
15097            boolean res;
15098            try {
15099                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15100
15101                if (++mRetries > MAX_RETRIES) {
15102                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15103                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15104                    handleServiceError();
15105                    return false;
15106                } else {
15107                    handleStartCopy();
15108                    res = true;
15109                }
15110            } catch (RemoteException e) {
15111                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15112                mHandler.sendEmptyMessage(MCS_RECONNECT);
15113                res = false;
15114            }
15115            handleReturnCode();
15116            return res;
15117        }
15118
15119        final void serviceError() {
15120            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15121            handleServiceError();
15122            handleReturnCode();
15123        }
15124
15125        abstract void handleStartCopy() throws RemoteException;
15126        abstract void handleServiceError();
15127        abstract void handleReturnCode();
15128    }
15129
15130    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15131        for (File path : paths) {
15132            try {
15133                mcs.clearDirectory(path.getAbsolutePath());
15134            } catch (RemoteException e) {
15135            }
15136        }
15137    }
15138
15139    static class OriginInfo {
15140        /**
15141         * Location where install is coming from, before it has been
15142         * copied/renamed into place. This could be a single monolithic APK
15143         * file, or a cluster directory. This location may be untrusted.
15144         */
15145        final File file;
15146
15147        /**
15148         * Flag indicating that {@link #file} or {@link #cid} has already been
15149         * staged, meaning downstream users don't need to defensively copy the
15150         * contents.
15151         */
15152        final boolean staged;
15153
15154        /**
15155         * Flag indicating that {@link #file} or {@link #cid} is an already
15156         * installed app that is being moved.
15157         */
15158        final boolean existing;
15159
15160        final String resolvedPath;
15161        final File resolvedFile;
15162
15163        static OriginInfo fromNothing() {
15164            return new OriginInfo(null, false, false);
15165        }
15166
15167        static OriginInfo fromUntrustedFile(File file) {
15168            return new OriginInfo(file, false, false);
15169        }
15170
15171        static OriginInfo fromExistingFile(File file) {
15172            return new OriginInfo(file, false, true);
15173        }
15174
15175        static OriginInfo fromStagedFile(File file) {
15176            return new OriginInfo(file, true, false);
15177        }
15178
15179        private OriginInfo(File file, boolean staged, boolean existing) {
15180            this.file = file;
15181            this.staged = staged;
15182            this.existing = existing;
15183
15184            if (file != null) {
15185                resolvedPath = file.getAbsolutePath();
15186                resolvedFile = file;
15187            } else {
15188                resolvedPath = null;
15189                resolvedFile = null;
15190            }
15191        }
15192    }
15193
15194    static class MoveInfo {
15195        final int moveId;
15196        final String fromUuid;
15197        final String toUuid;
15198        final String packageName;
15199        final String dataAppName;
15200        final int appId;
15201        final String seinfo;
15202        final int targetSdkVersion;
15203
15204        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15205                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15206            this.moveId = moveId;
15207            this.fromUuid = fromUuid;
15208            this.toUuid = toUuid;
15209            this.packageName = packageName;
15210            this.dataAppName = dataAppName;
15211            this.appId = appId;
15212            this.seinfo = seinfo;
15213            this.targetSdkVersion = targetSdkVersion;
15214        }
15215    }
15216
15217    static class VerificationInfo {
15218        /** A constant used to indicate that a uid value is not present. */
15219        public static final int NO_UID = -1;
15220
15221        /** URI referencing where the package was downloaded from. */
15222        final Uri originatingUri;
15223
15224        /** HTTP referrer URI associated with the originatingURI. */
15225        final Uri referrer;
15226
15227        /** UID of the application that the install request originated from. */
15228        final int originatingUid;
15229
15230        /** UID of application requesting the install */
15231        final int installerUid;
15232
15233        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15234            this.originatingUri = originatingUri;
15235            this.referrer = referrer;
15236            this.originatingUid = originatingUid;
15237            this.installerUid = installerUid;
15238        }
15239    }
15240
15241    class InstallParams extends HandlerParams {
15242        final OriginInfo origin;
15243        final MoveInfo move;
15244        final IPackageInstallObserver2 observer;
15245        int installFlags;
15246        final String installerPackageName;
15247        final String volumeUuid;
15248        private InstallArgs mArgs;
15249        private int mRet;
15250        final String packageAbiOverride;
15251        final String[] grantedRuntimePermissions;
15252        final VerificationInfo verificationInfo;
15253        final Certificate[][] certificates;
15254        final int installReason;
15255
15256        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15257                int installFlags, String installerPackageName, String volumeUuid,
15258                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15259                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15260            super(user);
15261            this.origin = origin;
15262            this.move = move;
15263            this.observer = observer;
15264            this.installFlags = installFlags;
15265            this.installerPackageName = installerPackageName;
15266            this.volumeUuid = volumeUuid;
15267            this.verificationInfo = verificationInfo;
15268            this.packageAbiOverride = packageAbiOverride;
15269            this.grantedRuntimePermissions = grantedPermissions;
15270            this.certificates = certificates;
15271            this.installReason = installReason;
15272        }
15273
15274        @Override
15275        public String toString() {
15276            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15277                    + " file=" + origin.file + "}";
15278        }
15279
15280        private int installLocationPolicy(PackageInfoLite pkgLite) {
15281            String packageName = pkgLite.packageName;
15282            int installLocation = pkgLite.installLocation;
15283            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15284            // reader
15285            synchronized (mPackages) {
15286                // Currently installed package which the new package is attempting to replace or
15287                // null if no such package is installed.
15288                PackageParser.Package installedPkg = mPackages.get(packageName);
15289                // Package which currently owns the data which the new package will own if installed.
15290                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15291                // will be null whereas dataOwnerPkg will contain information about the package
15292                // which was uninstalled while keeping its data.
15293                PackageParser.Package dataOwnerPkg = installedPkg;
15294                if (dataOwnerPkg  == null) {
15295                    PackageSetting ps = mSettings.mPackages.get(packageName);
15296                    if (ps != null) {
15297                        dataOwnerPkg = ps.pkg;
15298                    }
15299                }
15300
15301                if (dataOwnerPkg != null) {
15302                    // If installed, the package will get access to data left on the device by its
15303                    // predecessor. As a security measure, this is permited only if this is not a
15304                    // version downgrade or if the predecessor package is marked as debuggable and
15305                    // a downgrade is explicitly requested.
15306                    //
15307                    // On debuggable platform builds, downgrades are permitted even for
15308                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15309                    // not offer security guarantees and thus it's OK to disable some security
15310                    // mechanisms to make debugging/testing easier on those builds. However, even on
15311                    // debuggable builds downgrades of packages are permitted only if requested via
15312                    // installFlags. This is because we aim to keep the behavior of debuggable
15313                    // platform builds as close as possible to the behavior of non-debuggable
15314                    // platform builds.
15315                    final boolean downgradeRequested =
15316                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15317                    final boolean packageDebuggable =
15318                                (dataOwnerPkg.applicationInfo.flags
15319                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15320                    final boolean downgradePermitted =
15321                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15322                    if (!downgradePermitted) {
15323                        try {
15324                            checkDowngrade(dataOwnerPkg, pkgLite);
15325                        } catch (PackageManagerException e) {
15326                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15327                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15328                        }
15329                    }
15330                }
15331
15332                if (installedPkg != null) {
15333                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15334                        // Check for updated system application.
15335                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15336                            if (onSd) {
15337                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15338                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15339                            }
15340                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15341                        } else {
15342                            if (onSd) {
15343                                // Install flag overrides everything.
15344                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15345                            }
15346                            // If current upgrade specifies particular preference
15347                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15348                                // Application explicitly specified internal.
15349                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15350                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15351                                // App explictly prefers external. Let policy decide
15352                            } else {
15353                                // Prefer previous location
15354                                if (isExternal(installedPkg)) {
15355                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15356                                }
15357                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15358                            }
15359                        }
15360                    } else {
15361                        // Invalid install. Return error code
15362                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15363                    }
15364                }
15365            }
15366            // All the special cases have been taken care of.
15367            // Return result based on recommended install location.
15368            if (onSd) {
15369                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15370            }
15371            return pkgLite.recommendedInstallLocation;
15372        }
15373
15374        /*
15375         * Invoke remote method to get package information and install
15376         * location values. Override install location based on default
15377         * policy if needed and then create install arguments based
15378         * on the install location.
15379         */
15380        public void handleStartCopy() throws RemoteException {
15381            int ret = PackageManager.INSTALL_SUCCEEDED;
15382
15383            // If we're already staged, we've firmly committed to an install location
15384            if (origin.staged) {
15385                if (origin.file != null) {
15386                    installFlags |= PackageManager.INSTALL_INTERNAL;
15387                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15388                } else {
15389                    throw new IllegalStateException("Invalid stage location");
15390                }
15391            }
15392
15393            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15394            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15395            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15396            PackageInfoLite pkgLite = null;
15397
15398            if (onInt && onSd) {
15399                // Check if both bits are set.
15400                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15401                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15402            } else if (onSd && ephemeral) {
15403                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15404                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15405            } else {
15406                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15407                        packageAbiOverride);
15408
15409                if (DEBUG_EPHEMERAL && ephemeral) {
15410                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15411                }
15412
15413                /*
15414                 * If we have too little free space, try to free cache
15415                 * before giving up.
15416                 */
15417                if (!origin.staged && pkgLite.recommendedInstallLocation
15418                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15419                    // TODO: focus freeing disk space on the target device
15420                    final StorageManager storage = StorageManager.from(mContext);
15421                    final long lowThreshold = storage.getStorageLowBytes(
15422                            Environment.getDataDirectory());
15423
15424                    final long sizeBytes = mContainerService.calculateInstalledSize(
15425                            origin.resolvedPath, packageAbiOverride);
15426
15427                    try {
15428                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15429                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15430                                installFlags, packageAbiOverride);
15431                    } catch (InstallerException e) {
15432                        Slog.w(TAG, "Failed to free cache", e);
15433                    }
15434
15435                    /*
15436                     * The cache free must have deleted the file we
15437                     * downloaded to install.
15438                     *
15439                     * TODO: fix the "freeCache" call to not delete
15440                     *       the file we care about.
15441                     */
15442                    if (pkgLite.recommendedInstallLocation
15443                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15444                        pkgLite.recommendedInstallLocation
15445                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15446                    }
15447                }
15448            }
15449
15450            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15451                int loc = pkgLite.recommendedInstallLocation;
15452                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15453                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15454                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15455                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15456                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15457                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15458                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15459                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15460                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15461                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15462                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15463                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15464                } else {
15465                    // Override with defaults if needed.
15466                    loc = installLocationPolicy(pkgLite);
15467                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15468                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15469                    } else if (!onSd && !onInt) {
15470                        // Override install location with flags
15471                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15472                            // Set the flag to install on external media.
15473                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15474                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15475                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15476                            if (DEBUG_EPHEMERAL) {
15477                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15478                            }
15479                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15480                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15481                                    |PackageManager.INSTALL_INTERNAL);
15482                        } else {
15483                            // Make sure the flag for installing on external
15484                            // media is unset
15485                            installFlags |= PackageManager.INSTALL_INTERNAL;
15486                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15487                        }
15488                    }
15489                }
15490            }
15491
15492            final InstallArgs args = createInstallArgs(this);
15493            mArgs = args;
15494
15495            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15496                // TODO: http://b/22976637
15497                // Apps installed for "all" users use the device owner to verify the app
15498                UserHandle verifierUser = getUser();
15499                if (verifierUser == UserHandle.ALL) {
15500                    verifierUser = UserHandle.SYSTEM;
15501                }
15502
15503                /*
15504                 * Determine if we have any installed package verifiers. If we
15505                 * do, then we'll defer to them to verify the packages.
15506                 */
15507                final int requiredUid = mRequiredVerifierPackage == null ? -1
15508                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15509                                verifierUser.getIdentifier());
15510                final int installerUid =
15511                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15512                if (!origin.existing && requiredUid != -1
15513                        && isVerificationEnabled(
15514                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15515                    final Intent verification = new Intent(
15516                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15517                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15518                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15519                            PACKAGE_MIME_TYPE);
15520                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15521
15522                    // Query all live verifiers based on current user state
15523                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15524                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15525                            false /*allowDynamicSplits*/);
15526
15527                    if (DEBUG_VERIFY) {
15528                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15529                                + verification.toString() + " with " + pkgLite.verifiers.length
15530                                + " optional verifiers");
15531                    }
15532
15533                    final int verificationId = mPendingVerificationToken++;
15534
15535                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15536
15537                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15538                            installerPackageName);
15539
15540                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15541                            installFlags);
15542
15543                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15544                            pkgLite.packageName);
15545
15546                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15547                            pkgLite.versionCode);
15548
15549                    if (verificationInfo != null) {
15550                        if (verificationInfo.originatingUri != null) {
15551                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15552                                    verificationInfo.originatingUri);
15553                        }
15554                        if (verificationInfo.referrer != null) {
15555                            verification.putExtra(Intent.EXTRA_REFERRER,
15556                                    verificationInfo.referrer);
15557                        }
15558                        if (verificationInfo.originatingUid >= 0) {
15559                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15560                                    verificationInfo.originatingUid);
15561                        }
15562                        if (verificationInfo.installerUid >= 0) {
15563                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15564                                    verificationInfo.installerUid);
15565                        }
15566                    }
15567
15568                    final PackageVerificationState verificationState = new PackageVerificationState(
15569                            requiredUid, args);
15570
15571                    mPendingVerification.append(verificationId, verificationState);
15572
15573                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15574                            receivers, verificationState);
15575
15576                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15577                    final long idleDuration = getVerificationTimeout();
15578
15579                    /*
15580                     * If any sufficient verifiers were listed in the package
15581                     * manifest, attempt to ask them.
15582                     */
15583                    if (sufficientVerifiers != null) {
15584                        final int N = sufficientVerifiers.size();
15585                        if (N == 0) {
15586                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15587                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15588                        } else {
15589                            for (int i = 0; i < N; i++) {
15590                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15591                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15592                                        verifierComponent.getPackageName(), idleDuration,
15593                                        verifierUser.getIdentifier(), false, "package verifier");
15594
15595                                final Intent sufficientIntent = new Intent(verification);
15596                                sufficientIntent.setComponent(verifierComponent);
15597                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15598                            }
15599                        }
15600                    }
15601
15602                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15603                            mRequiredVerifierPackage, receivers);
15604                    if (ret == PackageManager.INSTALL_SUCCEEDED
15605                            && mRequiredVerifierPackage != null) {
15606                        Trace.asyncTraceBegin(
15607                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15608                        /*
15609                         * Send the intent to the required verification agent,
15610                         * but only start the verification timeout after the
15611                         * target BroadcastReceivers have run.
15612                         */
15613                        verification.setComponent(requiredVerifierComponent);
15614                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15615                                mRequiredVerifierPackage, idleDuration,
15616                                verifierUser.getIdentifier(), false, "package verifier");
15617                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15618                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15619                                new BroadcastReceiver() {
15620                                    @Override
15621                                    public void onReceive(Context context, Intent intent) {
15622                                        final Message msg = mHandler
15623                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15624                                        msg.arg1 = verificationId;
15625                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15626                                    }
15627                                }, null, 0, null, null);
15628
15629                        /*
15630                         * We don't want the copy to proceed until verification
15631                         * succeeds, so null out this field.
15632                         */
15633                        mArgs = null;
15634                    }
15635                } else {
15636                    /*
15637                     * No package verification is enabled, so immediately start
15638                     * the remote call to initiate copy using temporary file.
15639                     */
15640                    ret = args.copyApk(mContainerService, true);
15641                }
15642            }
15643
15644            mRet = ret;
15645        }
15646
15647        @Override
15648        void handleReturnCode() {
15649            // If mArgs is null, then MCS couldn't be reached. When it
15650            // reconnects, it will try again to install. At that point, this
15651            // will succeed.
15652            if (mArgs != null) {
15653                processPendingInstall(mArgs, mRet);
15654            }
15655        }
15656
15657        @Override
15658        void handleServiceError() {
15659            mArgs = createInstallArgs(this);
15660            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15661        }
15662    }
15663
15664    private InstallArgs createInstallArgs(InstallParams params) {
15665        if (params.move != null) {
15666            return new MoveInstallArgs(params);
15667        } else {
15668            return new FileInstallArgs(params);
15669        }
15670    }
15671
15672    /**
15673     * Create args that describe an existing installed package. Typically used
15674     * when cleaning up old installs, or used as a move source.
15675     */
15676    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15677            String resourcePath, String[] instructionSets) {
15678        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15679    }
15680
15681    static abstract class InstallArgs {
15682        /** @see InstallParams#origin */
15683        final OriginInfo origin;
15684        /** @see InstallParams#move */
15685        final MoveInfo move;
15686
15687        final IPackageInstallObserver2 observer;
15688        // Always refers to PackageManager flags only
15689        final int installFlags;
15690        final String installerPackageName;
15691        final String volumeUuid;
15692        final UserHandle user;
15693        final String abiOverride;
15694        final String[] installGrantPermissions;
15695        /** If non-null, drop an async trace when the install completes */
15696        final String traceMethod;
15697        final int traceCookie;
15698        final Certificate[][] certificates;
15699        final int installReason;
15700
15701        // The list of instruction sets supported by this app. This is currently
15702        // only used during the rmdex() phase to clean up resources. We can get rid of this
15703        // if we move dex files under the common app path.
15704        /* nullable */ String[] instructionSets;
15705
15706        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15707                int installFlags, String installerPackageName, String volumeUuid,
15708                UserHandle user, String[] instructionSets,
15709                String abiOverride, String[] installGrantPermissions,
15710                String traceMethod, int traceCookie, Certificate[][] certificates,
15711                int installReason) {
15712            this.origin = origin;
15713            this.move = move;
15714            this.installFlags = installFlags;
15715            this.observer = observer;
15716            this.installerPackageName = installerPackageName;
15717            this.volumeUuid = volumeUuid;
15718            this.user = user;
15719            this.instructionSets = instructionSets;
15720            this.abiOverride = abiOverride;
15721            this.installGrantPermissions = installGrantPermissions;
15722            this.traceMethod = traceMethod;
15723            this.traceCookie = traceCookie;
15724            this.certificates = certificates;
15725            this.installReason = installReason;
15726        }
15727
15728        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15729        abstract int doPreInstall(int status);
15730
15731        /**
15732         * Rename package into final resting place. All paths on the given
15733         * scanned package should be updated to reflect the rename.
15734         */
15735        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15736        abstract int doPostInstall(int status, int uid);
15737
15738        /** @see PackageSettingBase#codePathString */
15739        abstract String getCodePath();
15740        /** @see PackageSettingBase#resourcePathString */
15741        abstract String getResourcePath();
15742
15743        // Need installer lock especially for dex file removal.
15744        abstract void cleanUpResourcesLI();
15745        abstract boolean doPostDeleteLI(boolean delete);
15746
15747        /**
15748         * Called before the source arguments are copied. This is used mostly
15749         * for MoveParams when it needs to read the source file to put it in the
15750         * destination.
15751         */
15752        int doPreCopy() {
15753            return PackageManager.INSTALL_SUCCEEDED;
15754        }
15755
15756        /**
15757         * Called after the source arguments are copied. This is used mostly for
15758         * MoveParams when it needs to read the source file to put it in the
15759         * destination.
15760         */
15761        int doPostCopy(int uid) {
15762            return PackageManager.INSTALL_SUCCEEDED;
15763        }
15764
15765        protected boolean isFwdLocked() {
15766            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15767        }
15768
15769        protected boolean isExternalAsec() {
15770            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15771        }
15772
15773        protected boolean isEphemeral() {
15774            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15775        }
15776
15777        UserHandle getUser() {
15778            return user;
15779        }
15780    }
15781
15782    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15783        if (!allCodePaths.isEmpty()) {
15784            if (instructionSets == null) {
15785                throw new IllegalStateException("instructionSet == null");
15786            }
15787            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15788            for (String codePath : allCodePaths) {
15789                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15790                    try {
15791                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15792                    } catch (InstallerException ignored) {
15793                    }
15794                }
15795            }
15796        }
15797    }
15798
15799    /**
15800     * Logic to handle installation of non-ASEC applications, including copying
15801     * and renaming logic.
15802     */
15803    class FileInstallArgs extends InstallArgs {
15804        private File codeFile;
15805        private File resourceFile;
15806
15807        // Example topology:
15808        // /data/app/com.example/base.apk
15809        // /data/app/com.example/split_foo.apk
15810        // /data/app/com.example/lib/arm/libfoo.so
15811        // /data/app/com.example/lib/arm64/libfoo.so
15812        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15813
15814        /** New install */
15815        FileInstallArgs(InstallParams params) {
15816            super(params.origin, params.move, params.observer, params.installFlags,
15817                    params.installerPackageName, params.volumeUuid,
15818                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15819                    params.grantedRuntimePermissions,
15820                    params.traceMethod, params.traceCookie, params.certificates,
15821                    params.installReason);
15822            if (isFwdLocked()) {
15823                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15824            }
15825        }
15826
15827        /** Existing install */
15828        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15829            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15830                    null, null, null, 0, null /*certificates*/,
15831                    PackageManager.INSTALL_REASON_UNKNOWN);
15832            this.codeFile = (codePath != null) ? new File(codePath) : null;
15833            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15834        }
15835
15836        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15838            try {
15839                return doCopyApk(imcs, temp);
15840            } finally {
15841                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15842            }
15843        }
15844
15845        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15846            if (origin.staged) {
15847                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15848                codeFile = origin.file;
15849                resourceFile = origin.file;
15850                return PackageManager.INSTALL_SUCCEEDED;
15851            }
15852
15853            try {
15854                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15855                final File tempDir =
15856                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15857                codeFile = tempDir;
15858                resourceFile = tempDir;
15859            } catch (IOException e) {
15860                Slog.w(TAG, "Failed to create copy file: " + e);
15861                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15862            }
15863
15864            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15865                @Override
15866                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15867                    if (!FileUtils.isValidExtFilename(name)) {
15868                        throw new IllegalArgumentException("Invalid filename: " + name);
15869                    }
15870                    try {
15871                        final File file = new File(codeFile, name);
15872                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15873                                O_RDWR | O_CREAT, 0644);
15874                        Os.chmod(file.getAbsolutePath(), 0644);
15875                        return new ParcelFileDescriptor(fd);
15876                    } catch (ErrnoException e) {
15877                        throw new RemoteException("Failed to open: " + e.getMessage());
15878                    }
15879                }
15880            };
15881
15882            int ret = PackageManager.INSTALL_SUCCEEDED;
15883            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15884            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15885                Slog.e(TAG, "Failed to copy package");
15886                return ret;
15887            }
15888
15889            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15890            NativeLibraryHelper.Handle handle = null;
15891            try {
15892                handle = NativeLibraryHelper.Handle.create(codeFile);
15893                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15894                        abiOverride);
15895            } catch (IOException e) {
15896                Slog.e(TAG, "Copying native libraries failed", e);
15897                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15898            } finally {
15899                IoUtils.closeQuietly(handle);
15900            }
15901
15902            return ret;
15903        }
15904
15905        int doPreInstall(int status) {
15906            if (status != PackageManager.INSTALL_SUCCEEDED) {
15907                cleanUp();
15908            }
15909            return status;
15910        }
15911
15912        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15913            if (status != PackageManager.INSTALL_SUCCEEDED) {
15914                cleanUp();
15915                return false;
15916            }
15917
15918            final File targetDir = codeFile.getParentFile();
15919            final File beforeCodeFile = codeFile;
15920            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15921
15922            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15923            try {
15924                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15925            } catch (ErrnoException e) {
15926                Slog.w(TAG, "Failed to rename", e);
15927                return false;
15928            }
15929
15930            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15931                Slog.w(TAG, "Failed to restorecon");
15932                return false;
15933            }
15934
15935            // Reflect the rename internally
15936            codeFile = afterCodeFile;
15937            resourceFile = afterCodeFile;
15938
15939            // Reflect the rename in scanned details
15940            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15941            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15942                    afterCodeFile, pkg.baseCodePath));
15943            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15944                    afterCodeFile, pkg.splitCodePaths));
15945
15946            // Reflect the rename in app info
15947            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15948            pkg.setApplicationInfoCodePath(pkg.codePath);
15949            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15950            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15951            pkg.setApplicationInfoResourcePath(pkg.codePath);
15952            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15953            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15954
15955            return true;
15956        }
15957
15958        int doPostInstall(int status, int uid) {
15959            if (status != PackageManager.INSTALL_SUCCEEDED) {
15960                cleanUp();
15961            }
15962            return status;
15963        }
15964
15965        @Override
15966        String getCodePath() {
15967            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15968        }
15969
15970        @Override
15971        String getResourcePath() {
15972            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15973        }
15974
15975        private boolean cleanUp() {
15976            if (codeFile == null || !codeFile.exists()) {
15977                return false;
15978            }
15979
15980            removeCodePathLI(codeFile);
15981
15982            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15983                resourceFile.delete();
15984            }
15985
15986            return true;
15987        }
15988
15989        void cleanUpResourcesLI() {
15990            // Try enumerating all code paths before deleting
15991            List<String> allCodePaths = Collections.EMPTY_LIST;
15992            if (codeFile != null && codeFile.exists()) {
15993                try {
15994                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15995                    allCodePaths = pkg.getAllCodePaths();
15996                } catch (PackageParserException e) {
15997                    // Ignored; we tried our best
15998                }
15999            }
16000
16001            cleanUp();
16002            removeDexFiles(allCodePaths, instructionSets);
16003        }
16004
16005        boolean doPostDeleteLI(boolean delete) {
16006            // XXX err, shouldn't we respect the delete flag?
16007            cleanUpResourcesLI();
16008            return true;
16009        }
16010    }
16011
16012    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16013            PackageManagerException {
16014        if (copyRet < 0) {
16015            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16016                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16017                throw new PackageManagerException(copyRet, message);
16018            }
16019        }
16020    }
16021
16022    /**
16023     * Extract the StorageManagerService "container ID" from the full code path of an
16024     * .apk.
16025     */
16026    static String cidFromCodePath(String fullCodePath) {
16027        int eidx = fullCodePath.lastIndexOf("/");
16028        String subStr1 = fullCodePath.substring(0, eidx);
16029        int sidx = subStr1.lastIndexOf("/");
16030        return subStr1.substring(sidx+1, eidx);
16031    }
16032
16033    /**
16034     * Logic to handle movement of existing installed applications.
16035     */
16036    class MoveInstallArgs extends InstallArgs {
16037        private File codeFile;
16038        private File resourceFile;
16039
16040        /** New install */
16041        MoveInstallArgs(InstallParams params) {
16042            super(params.origin, params.move, params.observer, params.installFlags,
16043                    params.installerPackageName, params.volumeUuid,
16044                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16045                    params.grantedRuntimePermissions,
16046                    params.traceMethod, params.traceCookie, params.certificates,
16047                    params.installReason);
16048        }
16049
16050        int copyApk(IMediaContainerService imcs, boolean temp) {
16051            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16052                    + move.fromUuid + " to " + move.toUuid);
16053            synchronized (mInstaller) {
16054                try {
16055                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16056                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16057                } catch (InstallerException e) {
16058                    Slog.w(TAG, "Failed to move app", e);
16059                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16060                }
16061            }
16062
16063            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16064            resourceFile = codeFile;
16065            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16066
16067            return PackageManager.INSTALL_SUCCEEDED;
16068        }
16069
16070        int doPreInstall(int status) {
16071            if (status != PackageManager.INSTALL_SUCCEEDED) {
16072                cleanUp(move.toUuid);
16073            }
16074            return status;
16075        }
16076
16077        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16078            if (status != PackageManager.INSTALL_SUCCEEDED) {
16079                cleanUp(move.toUuid);
16080                return false;
16081            }
16082
16083            // Reflect the move in app info
16084            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16085            pkg.setApplicationInfoCodePath(pkg.codePath);
16086            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16087            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16088            pkg.setApplicationInfoResourcePath(pkg.codePath);
16089            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16090            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16091
16092            return true;
16093        }
16094
16095        int doPostInstall(int status, int uid) {
16096            if (status == PackageManager.INSTALL_SUCCEEDED) {
16097                cleanUp(move.fromUuid);
16098            } else {
16099                cleanUp(move.toUuid);
16100            }
16101            return status;
16102        }
16103
16104        @Override
16105        String getCodePath() {
16106            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16107        }
16108
16109        @Override
16110        String getResourcePath() {
16111            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16112        }
16113
16114        private boolean cleanUp(String volumeUuid) {
16115            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16116                    move.dataAppName);
16117            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16118            final int[] userIds = sUserManager.getUserIds();
16119            synchronized (mInstallLock) {
16120                // Clean up both app data and code
16121                // All package moves are frozen until finished
16122                for (int userId : userIds) {
16123                    try {
16124                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16125                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16126                    } catch (InstallerException e) {
16127                        Slog.w(TAG, String.valueOf(e));
16128                    }
16129                }
16130                removeCodePathLI(codeFile);
16131            }
16132            return true;
16133        }
16134
16135        void cleanUpResourcesLI() {
16136            throw new UnsupportedOperationException();
16137        }
16138
16139        boolean doPostDeleteLI(boolean delete) {
16140            throw new UnsupportedOperationException();
16141        }
16142    }
16143
16144    static String getAsecPackageName(String packageCid) {
16145        int idx = packageCid.lastIndexOf("-");
16146        if (idx == -1) {
16147            return packageCid;
16148        }
16149        return packageCid.substring(0, idx);
16150    }
16151
16152    // Utility method used to create code paths based on package name and available index.
16153    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16154        String idxStr = "";
16155        int idx = 1;
16156        // Fall back to default value of idx=1 if prefix is not
16157        // part of oldCodePath
16158        if (oldCodePath != null) {
16159            String subStr = oldCodePath;
16160            // Drop the suffix right away
16161            if (suffix != null && subStr.endsWith(suffix)) {
16162                subStr = subStr.substring(0, subStr.length() - suffix.length());
16163            }
16164            // If oldCodePath already contains prefix find out the
16165            // ending index to either increment or decrement.
16166            int sidx = subStr.lastIndexOf(prefix);
16167            if (sidx != -1) {
16168                subStr = subStr.substring(sidx + prefix.length());
16169                if (subStr != null) {
16170                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16171                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16172                    }
16173                    try {
16174                        idx = Integer.parseInt(subStr);
16175                        if (idx <= 1) {
16176                            idx++;
16177                        } else {
16178                            idx--;
16179                        }
16180                    } catch(NumberFormatException e) {
16181                    }
16182                }
16183            }
16184        }
16185        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16186        return prefix + idxStr;
16187    }
16188
16189    private File getNextCodePath(File targetDir, String packageName) {
16190        File result;
16191        SecureRandom random = new SecureRandom();
16192        byte[] bytes = new byte[16];
16193        do {
16194            random.nextBytes(bytes);
16195            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16196            result = new File(targetDir, packageName + "-" + suffix);
16197        } while (result.exists());
16198        return result;
16199    }
16200
16201    // Utility method that returns the relative package path with respect
16202    // to the installation directory. Like say for /data/data/com.test-1.apk
16203    // string com.test-1 is returned.
16204    static String deriveCodePathName(String codePath) {
16205        if (codePath == null) {
16206            return null;
16207        }
16208        final File codeFile = new File(codePath);
16209        final String name = codeFile.getName();
16210        if (codeFile.isDirectory()) {
16211            return name;
16212        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16213            final int lastDot = name.lastIndexOf('.');
16214            return name.substring(0, lastDot);
16215        } else {
16216            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16217            return null;
16218        }
16219    }
16220
16221    static class PackageInstalledInfo {
16222        String name;
16223        int uid;
16224        // The set of users that originally had this package installed.
16225        int[] origUsers;
16226        // The set of users that now have this package installed.
16227        int[] newUsers;
16228        PackageParser.Package pkg;
16229        int returnCode;
16230        String returnMsg;
16231        String installerPackageName;
16232        PackageRemovedInfo removedInfo;
16233        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16234
16235        public void setError(int code, String msg) {
16236            setReturnCode(code);
16237            setReturnMessage(msg);
16238            Slog.w(TAG, msg);
16239        }
16240
16241        public void setError(String msg, PackageParserException e) {
16242            setReturnCode(e.error);
16243            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16244            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16245            for (int i = 0; i < childCount; i++) {
16246                addedChildPackages.valueAt(i).setError(msg, e);
16247            }
16248            Slog.w(TAG, msg, e);
16249        }
16250
16251        public void setError(String msg, PackageManagerException e) {
16252            returnCode = e.error;
16253            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16254            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16255            for (int i = 0; i < childCount; i++) {
16256                addedChildPackages.valueAt(i).setError(msg, e);
16257            }
16258            Slog.w(TAG, msg, e);
16259        }
16260
16261        public void setReturnCode(int returnCode) {
16262            this.returnCode = returnCode;
16263            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16264            for (int i = 0; i < childCount; i++) {
16265                addedChildPackages.valueAt(i).returnCode = returnCode;
16266            }
16267        }
16268
16269        private void setReturnMessage(String returnMsg) {
16270            this.returnMsg = returnMsg;
16271            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16272            for (int i = 0; i < childCount; i++) {
16273                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16274            }
16275        }
16276
16277        // In some error cases we want to convey more info back to the observer
16278        String origPackage;
16279        String origPermission;
16280    }
16281
16282    /*
16283     * Install a non-existing package.
16284     */
16285    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16286            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16287            PackageInstalledInfo res, int installReason) {
16288        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16289
16290        // Remember this for later, in case we need to rollback this install
16291        String pkgName = pkg.packageName;
16292
16293        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16294
16295        synchronized(mPackages) {
16296            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16297            if (renamedPackage != null) {
16298                // A package with the same name is already installed, though
16299                // it has been renamed to an older name.  The package we
16300                // are trying to install should be installed as an update to
16301                // the existing one, but that has not been requested, so bail.
16302                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16303                        + " without first uninstalling package running as "
16304                        + renamedPackage);
16305                return;
16306            }
16307            if (mPackages.containsKey(pkgName)) {
16308                // Don't allow installation over an existing package with the same name.
16309                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16310                        + " without first uninstalling.");
16311                return;
16312            }
16313        }
16314
16315        try {
16316            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16317                    System.currentTimeMillis(), user);
16318
16319            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16320
16321            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16322                prepareAppDataAfterInstallLIF(newPackage);
16323
16324            } else {
16325                // Remove package from internal structures, but keep around any
16326                // data that might have already existed
16327                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16328                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16329            }
16330        } catch (PackageManagerException e) {
16331            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16332        }
16333
16334        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16335    }
16336
16337    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16338        // Can't rotate keys during boot or if sharedUser.
16339        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16340                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16341            return false;
16342        }
16343        // app is using upgradeKeySets; make sure all are valid
16344        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16345        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16346        for (int i = 0; i < upgradeKeySets.length; i++) {
16347            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16348                Slog.wtf(TAG, "Package "
16349                         + (oldPs.name != null ? oldPs.name : "<null>")
16350                         + " contains upgrade-key-set reference to unknown key-set: "
16351                         + upgradeKeySets[i]
16352                         + " reverting to signatures check.");
16353                return false;
16354            }
16355        }
16356        return true;
16357    }
16358
16359    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16360        // Upgrade keysets are being used.  Determine if new package has a superset of the
16361        // required keys.
16362        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16363        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16364        for (int i = 0; i < upgradeKeySets.length; i++) {
16365            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16366            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16367                return true;
16368            }
16369        }
16370        return false;
16371    }
16372
16373    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16374        try (DigestInputStream digestStream =
16375                new DigestInputStream(new FileInputStream(file), digest)) {
16376            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16377        }
16378    }
16379
16380    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16381            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16382            int installReason) {
16383        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16384
16385        final PackageParser.Package oldPackage;
16386        final PackageSetting ps;
16387        final String pkgName = pkg.packageName;
16388        final int[] allUsers;
16389        final int[] installedUsers;
16390
16391        synchronized(mPackages) {
16392            oldPackage = mPackages.get(pkgName);
16393            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16394
16395            // don't allow upgrade to target a release SDK from a pre-release SDK
16396            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16397                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16398            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16399                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16400            if (oldTargetsPreRelease
16401                    && !newTargetsPreRelease
16402                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16403                Slog.w(TAG, "Can't install package targeting released sdk");
16404                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16405                return;
16406            }
16407
16408            ps = mSettings.mPackages.get(pkgName);
16409
16410            // verify signatures are valid
16411            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16412                if (!checkUpgradeKeySetLP(ps, pkg)) {
16413                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16414                            "New package not signed by keys specified by upgrade-keysets: "
16415                                    + pkgName);
16416                    return;
16417                }
16418            } else {
16419                // default to original signature matching
16420                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16421                        != PackageManager.SIGNATURE_MATCH) {
16422                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16423                            "New package has a different signature: " + pkgName);
16424                    return;
16425                }
16426            }
16427
16428            // don't allow a system upgrade unless the upgrade hash matches
16429            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16430                byte[] digestBytes = null;
16431                try {
16432                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16433                    updateDigest(digest, new File(pkg.baseCodePath));
16434                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16435                        for (String path : pkg.splitCodePaths) {
16436                            updateDigest(digest, new File(path));
16437                        }
16438                    }
16439                    digestBytes = digest.digest();
16440                } catch (NoSuchAlgorithmException | IOException e) {
16441                    res.setError(INSTALL_FAILED_INVALID_APK,
16442                            "Could not compute hash: " + pkgName);
16443                    return;
16444                }
16445                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16446                    res.setError(INSTALL_FAILED_INVALID_APK,
16447                            "New package fails restrict-update check: " + pkgName);
16448                    return;
16449                }
16450                // retain upgrade restriction
16451                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16452            }
16453
16454            // Check for shared user id changes
16455            String invalidPackageName =
16456                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16457            if (invalidPackageName != null) {
16458                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16459                        "Package " + invalidPackageName + " tried to change user "
16460                                + oldPackage.mSharedUserId);
16461                return;
16462            }
16463
16464            // In case of rollback, remember per-user/profile install state
16465            allUsers = sUserManager.getUserIds();
16466            installedUsers = ps.queryInstalledUsers(allUsers, true);
16467
16468            // don't allow an upgrade from full to ephemeral
16469            if (isInstantApp) {
16470                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16471                    for (int currentUser : allUsers) {
16472                        if (!ps.getInstantApp(currentUser)) {
16473                            // can't downgrade from full to instant
16474                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16475                                    + " for user: " + currentUser);
16476                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16477                            return;
16478                        }
16479                    }
16480                } else if (!ps.getInstantApp(user.getIdentifier())) {
16481                    // can't downgrade from full to instant
16482                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16483                            + " for user: " + user.getIdentifier());
16484                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16485                    return;
16486                }
16487            }
16488        }
16489
16490        // Update what is removed
16491        res.removedInfo = new PackageRemovedInfo(this);
16492        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16493        res.removedInfo.removedPackage = oldPackage.packageName;
16494        res.removedInfo.installerPackageName = ps.installerPackageName;
16495        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16496        res.removedInfo.isUpdate = true;
16497        res.removedInfo.origUsers = installedUsers;
16498        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16499        for (int i = 0; i < installedUsers.length; i++) {
16500            final int userId = installedUsers[i];
16501            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16502        }
16503
16504        final int childCount = (oldPackage.childPackages != null)
16505                ? oldPackage.childPackages.size() : 0;
16506        for (int i = 0; i < childCount; i++) {
16507            boolean childPackageUpdated = false;
16508            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16509            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16510            if (res.addedChildPackages != null) {
16511                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16512                if (childRes != null) {
16513                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16514                    childRes.removedInfo.removedPackage = childPkg.packageName;
16515                    if (childPs != null) {
16516                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16517                    }
16518                    childRes.removedInfo.isUpdate = true;
16519                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16520                    childPackageUpdated = true;
16521                }
16522            }
16523            if (!childPackageUpdated) {
16524                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16525                childRemovedRes.removedPackage = childPkg.packageName;
16526                if (childPs != null) {
16527                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16528                }
16529                childRemovedRes.isUpdate = false;
16530                childRemovedRes.dataRemoved = true;
16531                synchronized (mPackages) {
16532                    if (childPs != null) {
16533                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16534                    }
16535                }
16536                if (res.removedInfo.removedChildPackages == null) {
16537                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16538                }
16539                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16540            }
16541        }
16542
16543        boolean sysPkg = (isSystemApp(oldPackage));
16544        if (sysPkg) {
16545            // Set the system/privileged/oem flags as needed
16546            final boolean privileged =
16547                    (oldPackage.applicationInfo.privateFlags
16548                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16549            final boolean oem =
16550                    (oldPackage.applicationInfo.privateFlags
16551                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16552            final int systemPolicyFlags = policyFlags
16553                    | PackageParser.PARSE_IS_SYSTEM
16554                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16555                    | (oem ? PARSE_IS_OEM : 0);
16556
16557            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16558                    user, allUsers, installerPackageName, res, installReason);
16559        } else {
16560            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16561                    user, allUsers, installerPackageName, res, installReason);
16562        }
16563    }
16564
16565    @Override
16566    public List<String> getPreviousCodePaths(String packageName) {
16567        final int callingUid = Binder.getCallingUid();
16568        final List<String> result = new ArrayList<>();
16569        if (getInstantAppPackageName(callingUid) != null) {
16570            return result;
16571        }
16572        final PackageSetting ps = mSettings.mPackages.get(packageName);
16573        if (ps != null
16574                && ps.oldCodePaths != null
16575                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16576            result.addAll(ps.oldCodePaths);
16577        }
16578        return result;
16579    }
16580
16581    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16582            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16583            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16584            int installReason) {
16585        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16586                + deletedPackage);
16587
16588        String pkgName = deletedPackage.packageName;
16589        boolean deletedPkg = true;
16590        boolean addedPkg = false;
16591        boolean updatedSettings = false;
16592        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16593        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16594                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16595
16596        final long origUpdateTime = (pkg.mExtras != null)
16597                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16598
16599        // First delete the existing package while retaining the data directory
16600        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16601                res.removedInfo, true, pkg)) {
16602            // If the existing package wasn't successfully deleted
16603            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16604            deletedPkg = false;
16605        } else {
16606            // Successfully deleted the old package; proceed with replace.
16607
16608            // If deleted package lived in a container, give users a chance to
16609            // relinquish resources before killing.
16610            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16611                if (DEBUG_INSTALL) {
16612                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16613                }
16614                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16615                final ArrayList<String> pkgList = new ArrayList<String>(1);
16616                pkgList.add(deletedPackage.applicationInfo.packageName);
16617                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16618            }
16619
16620            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16621                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16622            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16623
16624            try {
16625                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16626                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16627                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16628                        installReason);
16629
16630                // Update the in-memory copy of the previous code paths.
16631                PackageSetting ps = mSettings.mPackages.get(pkgName);
16632                if (!killApp) {
16633                    if (ps.oldCodePaths == null) {
16634                        ps.oldCodePaths = new ArraySet<>();
16635                    }
16636                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16637                    if (deletedPackage.splitCodePaths != null) {
16638                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16639                    }
16640                } else {
16641                    ps.oldCodePaths = null;
16642                }
16643                if (ps.childPackageNames != null) {
16644                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16645                        final String childPkgName = ps.childPackageNames.get(i);
16646                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16647                        childPs.oldCodePaths = ps.oldCodePaths;
16648                    }
16649                }
16650                // set instant app status, but, only if it's explicitly specified
16651                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16652                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16653                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16654                prepareAppDataAfterInstallLIF(newPackage);
16655                addedPkg = true;
16656                mDexManager.notifyPackageUpdated(newPackage.packageName,
16657                        newPackage.baseCodePath, newPackage.splitCodePaths);
16658            } catch (PackageManagerException e) {
16659                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16660            }
16661        }
16662
16663        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16664            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16665
16666            // Revert all internal state mutations and added folders for the failed install
16667            if (addedPkg) {
16668                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16669                        res.removedInfo, true, null);
16670            }
16671
16672            // Restore the old package
16673            if (deletedPkg) {
16674                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16675                File restoreFile = new File(deletedPackage.codePath);
16676                // Parse old package
16677                boolean oldExternal = isExternal(deletedPackage);
16678                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16679                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16680                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16681                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16682                try {
16683                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16684                            null);
16685                } catch (PackageManagerException e) {
16686                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16687                            + e.getMessage());
16688                    return;
16689                }
16690
16691                synchronized (mPackages) {
16692                    // Ensure the installer package name up to date
16693                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16694
16695                    // Update permissions for restored package
16696                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16697
16698                    mSettings.writeLPr();
16699                }
16700
16701                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16702            }
16703        } else {
16704            synchronized (mPackages) {
16705                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16706                if (ps != null) {
16707                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16708                    if (res.removedInfo.removedChildPackages != null) {
16709                        final int childCount = res.removedInfo.removedChildPackages.size();
16710                        // Iterate in reverse as we may modify the collection
16711                        for (int i = childCount - 1; i >= 0; i--) {
16712                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16713                            if (res.addedChildPackages.containsKey(childPackageName)) {
16714                                res.removedInfo.removedChildPackages.removeAt(i);
16715                            } else {
16716                                PackageRemovedInfo childInfo = res.removedInfo
16717                                        .removedChildPackages.valueAt(i);
16718                                childInfo.removedForAllUsers = mPackages.get(
16719                                        childInfo.removedPackage) == null;
16720                            }
16721                        }
16722                    }
16723                }
16724            }
16725        }
16726    }
16727
16728    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16729            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16730            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16731            int installReason) {
16732        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16733                + ", old=" + deletedPackage);
16734
16735        final boolean disabledSystem;
16736
16737        // Remove existing system package
16738        removePackageLI(deletedPackage, true);
16739
16740        synchronized (mPackages) {
16741            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16742        }
16743        if (!disabledSystem) {
16744            // We didn't need to disable the .apk as a current system package,
16745            // which means we are replacing another update that is already
16746            // installed.  We need to make sure to delete the older one's .apk.
16747            res.removedInfo.args = createInstallArgsForExisting(0,
16748                    deletedPackage.applicationInfo.getCodePath(),
16749                    deletedPackage.applicationInfo.getResourcePath(),
16750                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16751        } else {
16752            res.removedInfo.args = null;
16753        }
16754
16755        // Successfully disabled the old package. Now proceed with re-installation
16756        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16757                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16758        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16759
16760        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16761        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16762                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16763
16764        PackageParser.Package newPackage = null;
16765        try {
16766            // Add the package to the internal data structures
16767            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16768
16769            // Set the update and install times
16770            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16771            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16772                    System.currentTimeMillis());
16773
16774            // Update the package dynamic state if succeeded
16775            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16776                // Now that the install succeeded make sure we remove data
16777                // directories for any child package the update removed.
16778                final int deletedChildCount = (deletedPackage.childPackages != null)
16779                        ? deletedPackage.childPackages.size() : 0;
16780                final int newChildCount = (newPackage.childPackages != null)
16781                        ? newPackage.childPackages.size() : 0;
16782                for (int i = 0; i < deletedChildCount; i++) {
16783                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16784                    boolean childPackageDeleted = true;
16785                    for (int j = 0; j < newChildCount; j++) {
16786                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16787                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16788                            childPackageDeleted = false;
16789                            break;
16790                        }
16791                    }
16792                    if (childPackageDeleted) {
16793                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16794                                deletedChildPkg.packageName);
16795                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16796                            PackageRemovedInfo removedChildRes = res.removedInfo
16797                                    .removedChildPackages.get(deletedChildPkg.packageName);
16798                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16799                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16800                        }
16801                    }
16802                }
16803
16804                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16805                        installReason);
16806                prepareAppDataAfterInstallLIF(newPackage);
16807
16808                mDexManager.notifyPackageUpdated(newPackage.packageName,
16809                            newPackage.baseCodePath, newPackage.splitCodePaths);
16810            }
16811        } catch (PackageManagerException e) {
16812            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16813            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16814        }
16815
16816        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16817            // Re installation failed. Restore old information
16818            // Remove new pkg information
16819            if (newPackage != null) {
16820                removeInstalledPackageLI(newPackage, true);
16821            }
16822            // Add back the old system package
16823            try {
16824                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16825            } catch (PackageManagerException e) {
16826                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16827            }
16828
16829            synchronized (mPackages) {
16830                if (disabledSystem) {
16831                    enableSystemPackageLPw(deletedPackage);
16832                }
16833
16834                // Ensure the installer package name up to date
16835                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16836
16837                // Update permissions for restored package
16838                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16839
16840                mSettings.writeLPr();
16841            }
16842
16843            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16844                    + " after failed upgrade");
16845        }
16846    }
16847
16848    /**
16849     * Checks whether the parent or any of the child packages have a change shared
16850     * user. For a package to be a valid update the shred users of the parent and
16851     * the children should match. We may later support changing child shared users.
16852     * @param oldPkg The updated package.
16853     * @param newPkg The update package.
16854     * @return The shared user that change between the versions.
16855     */
16856    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16857            PackageParser.Package newPkg) {
16858        // Check parent shared user
16859        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16860            return newPkg.packageName;
16861        }
16862        // Check child shared users
16863        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16864        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16865        for (int i = 0; i < newChildCount; i++) {
16866            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16867            // If this child was present, did it have the same shared user?
16868            for (int j = 0; j < oldChildCount; j++) {
16869                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16870                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16871                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16872                    return newChildPkg.packageName;
16873                }
16874            }
16875        }
16876        return null;
16877    }
16878
16879    private void removeNativeBinariesLI(PackageSetting ps) {
16880        // Remove the lib path for the parent package
16881        if (ps != null) {
16882            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16883            // Remove the lib path for the child packages
16884            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16885            for (int i = 0; i < childCount; i++) {
16886                PackageSetting childPs = null;
16887                synchronized (mPackages) {
16888                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16889                }
16890                if (childPs != null) {
16891                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16892                            .legacyNativeLibraryPathString);
16893                }
16894            }
16895        }
16896    }
16897
16898    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16899        // Enable the parent package
16900        mSettings.enableSystemPackageLPw(pkg.packageName);
16901        // Enable the child packages
16902        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16903        for (int i = 0; i < childCount; i++) {
16904            PackageParser.Package childPkg = pkg.childPackages.get(i);
16905            mSettings.enableSystemPackageLPw(childPkg.packageName);
16906        }
16907    }
16908
16909    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16910            PackageParser.Package newPkg) {
16911        // Disable the parent package (parent always replaced)
16912        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16913        // Disable the child packages
16914        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16915        for (int i = 0; i < childCount; i++) {
16916            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16917            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16918            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16919        }
16920        return disabled;
16921    }
16922
16923    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16924            String installerPackageName) {
16925        // Enable the parent package
16926        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16927        // Enable the child packages
16928        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16929        for (int i = 0; i < childCount; i++) {
16930            PackageParser.Package childPkg = pkg.childPackages.get(i);
16931            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16932        }
16933    }
16934
16935    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16936            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16937        // Update the parent package setting
16938        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16939                res, user, installReason);
16940        // Update the child packages setting
16941        final int childCount = (newPackage.childPackages != null)
16942                ? newPackage.childPackages.size() : 0;
16943        for (int i = 0; i < childCount; i++) {
16944            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16945            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16946            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16947                    childRes.origUsers, childRes, user, installReason);
16948        }
16949    }
16950
16951    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16952            String installerPackageName, int[] allUsers, int[] installedForUsers,
16953            PackageInstalledInfo res, UserHandle user, int installReason) {
16954        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16955
16956        String pkgName = newPackage.packageName;
16957        synchronized (mPackages) {
16958            //write settings. the installStatus will be incomplete at this stage.
16959            //note that the new package setting would have already been
16960            //added to mPackages. It hasn't been persisted yet.
16961            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16962            // TODO: Remove this write? It's also written at the end of this method
16963            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16964            mSettings.writeLPr();
16965            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16966        }
16967
16968        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16969        synchronized (mPackages) {
16970            updatePermissionsLPw(newPackage.packageName, newPackage,
16971                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16972                            ? UPDATE_PERMISSIONS_ALL : 0));
16973            // For system-bundled packages, we assume that installing an upgraded version
16974            // of the package implies that the user actually wants to run that new code,
16975            // so we enable the package.
16976            PackageSetting ps = mSettings.mPackages.get(pkgName);
16977            final int userId = user.getIdentifier();
16978            if (ps != null) {
16979                if (isSystemApp(newPackage)) {
16980                    if (DEBUG_INSTALL) {
16981                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16982                    }
16983                    // Enable system package for requested users
16984                    if (res.origUsers != null) {
16985                        for (int origUserId : res.origUsers) {
16986                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16987                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16988                                        origUserId, installerPackageName);
16989                            }
16990                        }
16991                    }
16992                    // Also convey the prior install/uninstall state
16993                    if (allUsers != null && installedForUsers != null) {
16994                        for (int currentUserId : allUsers) {
16995                            final boolean installed = ArrayUtils.contains(
16996                                    installedForUsers, currentUserId);
16997                            if (DEBUG_INSTALL) {
16998                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16999                            }
17000                            ps.setInstalled(installed, currentUserId);
17001                        }
17002                        // these install state changes will be persisted in the
17003                        // upcoming call to mSettings.writeLPr().
17004                    }
17005                }
17006                // It's implied that when a user requests installation, they want the app to be
17007                // installed and enabled.
17008                if (userId != UserHandle.USER_ALL) {
17009                    ps.setInstalled(true, userId);
17010                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17011                }
17012
17013                // When replacing an existing package, preserve the original install reason for all
17014                // users that had the package installed before.
17015                final Set<Integer> previousUserIds = new ArraySet<>();
17016                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17017                    final int installReasonCount = res.removedInfo.installReasons.size();
17018                    for (int i = 0; i < installReasonCount; i++) {
17019                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17020                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17021                        ps.setInstallReason(previousInstallReason, previousUserId);
17022                        previousUserIds.add(previousUserId);
17023                    }
17024                }
17025
17026                // Set install reason for users that are having the package newly installed.
17027                if (userId == UserHandle.USER_ALL) {
17028                    for (int currentUserId : sUserManager.getUserIds()) {
17029                        if (!previousUserIds.contains(currentUserId)) {
17030                            ps.setInstallReason(installReason, currentUserId);
17031                        }
17032                    }
17033                } else if (!previousUserIds.contains(userId)) {
17034                    ps.setInstallReason(installReason, userId);
17035                }
17036                mSettings.writeKernelMappingLPr(ps);
17037            }
17038            res.name = pkgName;
17039            res.uid = newPackage.applicationInfo.uid;
17040            res.pkg = newPackage;
17041            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17042            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17043            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17044            //to update install status
17045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17046            mSettings.writeLPr();
17047            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17048        }
17049
17050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17051    }
17052
17053    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17054        try {
17055            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17056            installPackageLI(args, res);
17057        } finally {
17058            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17059        }
17060    }
17061
17062    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17063        final int installFlags = args.installFlags;
17064        final String installerPackageName = args.installerPackageName;
17065        final String volumeUuid = args.volumeUuid;
17066        final File tmpPackageFile = new File(args.getCodePath());
17067        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17068        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17069                || (args.volumeUuid != null));
17070        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17071        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17072        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17073        final boolean virtualPreload =
17074                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17075        boolean replace = false;
17076        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17077        if (args.move != null) {
17078            // moving a complete application; perform an initial scan on the new install location
17079            scanFlags |= SCAN_INITIAL;
17080        }
17081        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17082            scanFlags |= SCAN_DONT_KILL_APP;
17083        }
17084        if (instantApp) {
17085            scanFlags |= SCAN_AS_INSTANT_APP;
17086        }
17087        if (fullApp) {
17088            scanFlags |= SCAN_AS_FULL_APP;
17089        }
17090        if (virtualPreload) {
17091            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17092        }
17093
17094        // Result object to be returned
17095        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17096        res.installerPackageName = installerPackageName;
17097
17098        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17099
17100        // Sanity check
17101        if (instantApp && (forwardLocked || onExternal)) {
17102            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17103                    + " external=" + onExternal);
17104            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17105            return;
17106        }
17107
17108        // Retrieve PackageSettings and parse package
17109        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17110                | PackageParser.PARSE_ENFORCE_CODE
17111                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17112                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17113                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17114                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17115        PackageParser pp = new PackageParser();
17116        pp.setSeparateProcesses(mSeparateProcesses);
17117        pp.setDisplayMetrics(mMetrics);
17118        pp.setCallback(mPackageParserCallback);
17119
17120        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17121        final PackageParser.Package pkg;
17122        try {
17123            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17124        } catch (PackageParserException e) {
17125            res.setError("Failed parse during installPackageLI", e);
17126            return;
17127        } finally {
17128            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17129        }
17130
17131        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17132        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17133            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17134            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17135                    "Instant app package must target O");
17136            return;
17137        }
17138        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17139            Slog.w(TAG, "Instant app package " + pkg.packageName
17140                    + " does not target targetSandboxVersion 2");
17141            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17142                    "Instant app package must use targetSanboxVersion 2");
17143            return;
17144        }
17145
17146        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17147            // Static shared libraries have synthetic package names
17148            renameStaticSharedLibraryPackage(pkg);
17149
17150            // No static shared libs on external storage
17151            if (onExternal) {
17152                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17153                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17154                        "Packages declaring static-shared libs cannot be updated");
17155                return;
17156            }
17157        }
17158
17159        // If we are installing a clustered package add results for the children
17160        if (pkg.childPackages != null) {
17161            synchronized (mPackages) {
17162                final int childCount = pkg.childPackages.size();
17163                for (int i = 0; i < childCount; i++) {
17164                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17165                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17166                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17167                    childRes.pkg = childPkg;
17168                    childRes.name = childPkg.packageName;
17169                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17170                    if (childPs != null) {
17171                        childRes.origUsers = childPs.queryInstalledUsers(
17172                                sUserManager.getUserIds(), true);
17173                    }
17174                    if ((mPackages.containsKey(childPkg.packageName))) {
17175                        childRes.removedInfo = new PackageRemovedInfo(this);
17176                        childRes.removedInfo.removedPackage = childPkg.packageName;
17177                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17178                    }
17179                    if (res.addedChildPackages == null) {
17180                        res.addedChildPackages = new ArrayMap<>();
17181                    }
17182                    res.addedChildPackages.put(childPkg.packageName, childRes);
17183                }
17184            }
17185        }
17186
17187        // If package doesn't declare API override, mark that we have an install
17188        // time CPU ABI override.
17189        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17190            pkg.cpuAbiOverride = args.abiOverride;
17191        }
17192
17193        String pkgName = res.name = pkg.packageName;
17194        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17195            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17196                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17197                return;
17198            }
17199        }
17200
17201        try {
17202            // either use what we've been given or parse directly from the APK
17203            if (args.certificates != null) {
17204                try {
17205                    PackageParser.populateCertificates(pkg, args.certificates);
17206                } catch (PackageParserException e) {
17207                    // there was something wrong with the certificates we were given;
17208                    // try to pull them from the APK
17209                    PackageParser.collectCertificates(pkg, parseFlags);
17210                }
17211            } else {
17212                PackageParser.collectCertificates(pkg, parseFlags);
17213            }
17214        } catch (PackageParserException e) {
17215            res.setError("Failed collect during installPackageLI", e);
17216            return;
17217        }
17218
17219        // Get rid of all references to package scan path via parser.
17220        pp = null;
17221        String oldCodePath = null;
17222        boolean systemApp = false;
17223        synchronized (mPackages) {
17224            // Check if installing already existing package
17225            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17226                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17227                if (pkg.mOriginalPackages != null
17228                        && pkg.mOriginalPackages.contains(oldName)
17229                        && mPackages.containsKey(oldName)) {
17230                    // This package is derived from an original package,
17231                    // and this device has been updating from that original
17232                    // name.  We must continue using the original name, so
17233                    // rename the new package here.
17234                    pkg.setPackageName(oldName);
17235                    pkgName = pkg.packageName;
17236                    replace = true;
17237                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17238                            + oldName + " pkgName=" + pkgName);
17239                } else if (mPackages.containsKey(pkgName)) {
17240                    // This package, under its official name, already exists
17241                    // on the device; we should replace it.
17242                    replace = true;
17243                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17244                }
17245
17246                // Child packages are installed through the parent package
17247                if (pkg.parentPackage != null) {
17248                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17249                            "Package " + pkg.packageName + " is child of package "
17250                                    + pkg.parentPackage.parentPackage + ". Child packages "
17251                                    + "can be updated only through the parent package.");
17252                    return;
17253                }
17254
17255                if (replace) {
17256                    // Prevent apps opting out from runtime permissions
17257                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17258                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17259                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17260                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17261                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17262                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17263                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17264                                        + " doesn't support runtime permissions but the old"
17265                                        + " target SDK " + oldTargetSdk + " does.");
17266                        return;
17267                    }
17268                    // Prevent apps from downgrading their targetSandbox.
17269                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17270                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17271                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17272                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17273                                "Package " + pkg.packageName + " new target sandbox "
17274                                + newTargetSandbox + " is incompatible with the previous value of"
17275                                + oldTargetSandbox + ".");
17276                        return;
17277                    }
17278
17279                    // Prevent installing of child packages
17280                    if (oldPackage.parentPackage != null) {
17281                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17282                                "Package " + pkg.packageName + " is child of package "
17283                                        + oldPackage.parentPackage + ". Child packages "
17284                                        + "can be updated only through the parent package.");
17285                        return;
17286                    }
17287                }
17288            }
17289
17290            PackageSetting ps = mSettings.mPackages.get(pkgName);
17291            if (ps != null) {
17292                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17293
17294                // Static shared libs have same package with different versions where
17295                // we internally use a synthetic package name to allow multiple versions
17296                // of the same package, therefore we need to compare signatures against
17297                // the package setting for the latest library version.
17298                PackageSetting signatureCheckPs = ps;
17299                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17300                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17301                    if (libraryEntry != null) {
17302                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17303                    }
17304                }
17305
17306                // Quick sanity check that we're signed correctly if updating;
17307                // we'll check this again later when scanning, but we want to
17308                // bail early here before tripping over redefined permissions.
17309                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17310                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17311                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17312                                + pkg.packageName + " upgrade keys do not match the "
17313                                + "previously installed version");
17314                        return;
17315                    }
17316                } else {
17317                    try {
17318                        verifySignaturesLP(signatureCheckPs, pkg);
17319                    } catch (PackageManagerException e) {
17320                        res.setError(e.error, e.getMessage());
17321                        return;
17322                    }
17323                }
17324
17325                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17326                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17327                    systemApp = (ps.pkg.applicationInfo.flags &
17328                            ApplicationInfo.FLAG_SYSTEM) != 0;
17329                }
17330                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17331            }
17332
17333            int N = pkg.permissions.size();
17334            for (int i = N-1; i >= 0; i--) {
17335                final PackageParser.Permission perm = pkg.permissions.get(i);
17336                final BasePermission bp =
17337                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17338
17339                // Don't allow anyone but the system to define ephemeral permissions.
17340                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17341                        && !systemApp) {
17342                    Slog.w(TAG, "Non-System package " + pkg.packageName
17343                            + " attempting to delcare ephemeral permission "
17344                            + perm.info.name + "; Removing ephemeral.");
17345                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17346                }
17347
17348                // Check whether the newly-scanned package wants to define an already-defined perm
17349                if (bp != null) {
17350                    // If the defining package is signed with our cert, it's okay.  This
17351                    // also includes the "updating the same package" case, of course.
17352                    // "updating same package" could also involve key-rotation.
17353                    final boolean sigsOk;
17354                    final String sourcePackageName = bp.getSourcePackageName();
17355                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17356                    if (sourcePackageName.equals(pkg.packageName)
17357                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17358                                    scanFlags))) {
17359                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17360                    } else {
17361                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17362                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17363                    }
17364                    if (!sigsOk) {
17365                        // If the owning package is the system itself, we log but allow
17366                        // install to proceed; we fail the install on all other permission
17367                        // redefinitions.
17368                        if (!sourcePackageName.equals("android")) {
17369                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17370                                    + pkg.packageName + " attempting to redeclare permission "
17371                                    + perm.info.name + " already owned by " + sourcePackageName);
17372                            res.origPermission = perm.info.name;
17373                            res.origPackage = sourcePackageName;
17374                            return;
17375                        } else {
17376                            Slog.w(TAG, "Package " + pkg.packageName
17377                                    + " attempting to redeclare system permission "
17378                                    + perm.info.name + "; ignoring new declaration");
17379                            pkg.permissions.remove(i);
17380                        }
17381                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17382                        // Prevent apps to change protection level to dangerous from any other
17383                        // type as this would allow a privilege escalation where an app adds a
17384                        // normal/signature permission in other app's group and later redefines
17385                        // it as dangerous leading to the group auto-grant.
17386                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17387                                == PermissionInfo.PROTECTION_DANGEROUS) {
17388                            if (bp != null && !bp.isRuntime()) {
17389                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17390                                        + "non-runtime permission " + perm.info.name
17391                                        + " to runtime; keeping old protection level");
17392                                perm.info.protectionLevel = bp.getProtectionLevel();
17393                            }
17394                        }
17395                    }
17396                }
17397            }
17398        }
17399
17400        if (systemApp) {
17401            if (onExternal) {
17402                // Abort update; system app can't be replaced with app on sdcard
17403                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17404                        "Cannot install updates to system apps on sdcard");
17405                return;
17406            } else if (instantApp) {
17407                // Abort update; system app can't be replaced with an instant app
17408                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17409                        "Cannot update a system app with an instant app");
17410                return;
17411            }
17412        }
17413
17414        if (args.move != null) {
17415            // We did an in-place move, so dex is ready to roll
17416            scanFlags |= SCAN_NO_DEX;
17417            scanFlags |= SCAN_MOVE;
17418
17419            synchronized (mPackages) {
17420                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17421                if (ps == null) {
17422                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17423                            "Missing settings for moved package " + pkgName);
17424                }
17425
17426                // We moved the entire application as-is, so bring over the
17427                // previously derived ABI information.
17428                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17429                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17430            }
17431
17432        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17433            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17434            scanFlags |= SCAN_NO_DEX;
17435
17436            try {
17437                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17438                    args.abiOverride : pkg.cpuAbiOverride);
17439                final boolean extractNativeLibs = !pkg.isLibrary();
17440                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17441                        extractNativeLibs, mAppLib32InstallDir);
17442            } catch (PackageManagerException pme) {
17443                Slog.e(TAG, "Error deriving application ABI", pme);
17444                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17445                return;
17446            }
17447
17448            // Shared libraries for the package need to be updated.
17449            synchronized (mPackages) {
17450                try {
17451                    updateSharedLibrariesLPr(pkg, null);
17452                } catch (PackageManagerException e) {
17453                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17454                }
17455            }
17456        }
17457
17458        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17459            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17460            return;
17461        }
17462
17463        // Verify if we need to dexopt the app.
17464        //
17465        // NOTE: it is *important* to call dexopt after doRename which will sync the
17466        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17467        //
17468        // We only need to dexopt if the package meets ALL of the following conditions:
17469        //   1) it is not forward locked.
17470        //   2) it is not on on an external ASEC container.
17471        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17472        //
17473        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17474        // complete, so we skip this step during installation. Instead, we'll take extra time
17475        // the first time the instant app starts. It's preferred to do it this way to provide
17476        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17477        // middle of running an instant app. The default behaviour can be overridden
17478        // via gservices.
17479        final boolean performDexopt = !forwardLocked
17480            && !pkg.applicationInfo.isExternalAsec()
17481            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17482                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17483
17484        if (performDexopt) {
17485            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17486            // Do not run PackageDexOptimizer through the local performDexOpt
17487            // method because `pkg` may not be in `mPackages` yet.
17488            //
17489            // Also, don't fail application installs if the dexopt step fails.
17490            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17491                REASON_INSTALL,
17492                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17493            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17494                null /* instructionSets */,
17495                getOrCreateCompilerPackageStats(pkg),
17496                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17497                dexoptOptions);
17498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17499        }
17500
17501        // Notify BackgroundDexOptService that the package has been changed.
17502        // If this is an update of a package which used to fail to compile,
17503        // BackgroundDexOptService will remove it from its blacklist.
17504        // TODO: Layering violation
17505        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17506
17507        if (!instantApp) {
17508            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17509        } else {
17510            if (DEBUG_DOMAIN_VERIFICATION) {
17511                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17512            }
17513        }
17514
17515        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17516                "installPackageLI")) {
17517            if (replace) {
17518                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17519                    // Static libs have a synthetic package name containing the version
17520                    // and cannot be updated as an update would get a new package name,
17521                    // unless this is the exact same version code which is useful for
17522                    // development.
17523                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17524                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17525                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17526                                + "static-shared libs cannot be updated");
17527                        return;
17528                    }
17529                }
17530                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17531                        installerPackageName, res, args.installReason);
17532            } else {
17533                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17534                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17535            }
17536        }
17537
17538        synchronized (mPackages) {
17539            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17540            if (ps != null) {
17541                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17542                ps.setUpdateAvailable(false /*updateAvailable*/);
17543            }
17544
17545            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17546            for (int i = 0; i < childCount; i++) {
17547                PackageParser.Package childPkg = pkg.childPackages.get(i);
17548                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17549                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17550                if (childPs != null) {
17551                    childRes.newUsers = childPs.queryInstalledUsers(
17552                            sUserManager.getUserIds(), true);
17553                }
17554            }
17555
17556            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17557                updateSequenceNumberLP(ps, res.newUsers);
17558                updateInstantAppInstallerLocked(pkgName);
17559            }
17560        }
17561    }
17562
17563    private void startIntentFilterVerifications(int userId, boolean replacing,
17564            PackageParser.Package pkg) {
17565        if (mIntentFilterVerifierComponent == null) {
17566            Slog.w(TAG, "No IntentFilter verification will not be done as "
17567                    + "there is no IntentFilterVerifier available!");
17568            return;
17569        }
17570
17571        final int verifierUid = getPackageUid(
17572                mIntentFilterVerifierComponent.getPackageName(),
17573                MATCH_DEBUG_TRIAGED_MISSING,
17574                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17575
17576        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17577        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17578        mHandler.sendMessage(msg);
17579
17580        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17581        for (int i = 0; i < childCount; i++) {
17582            PackageParser.Package childPkg = pkg.childPackages.get(i);
17583            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17584            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17585            mHandler.sendMessage(msg);
17586        }
17587    }
17588
17589    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17590            PackageParser.Package pkg) {
17591        int size = pkg.activities.size();
17592        if (size == 0) {
17593            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17594                    "No activity, so no need to verify any IntentFilter!");
17595            return;
17596        }
17597
17598        final boolean hasDomainURLs = hasDomainURLs(pkg);
17599        if (!hasDomainURLs) {
17600            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17601                    "No domain URLs, so no need to verify any IntentFilter!");
17602            return;
17603        }
17604
17605        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17606                + " if any IntentFilter from the " + size
17607                + " Activities needs verification ...");
17608
17609        int count = 0;
17610        final String packageName = pkg.packageName;
17611
17612        synchronized (mPackages) {
17613            // If this is a new install and we see that we've already run verification for this
17614            // package, we have nothing to do: it means the state was restored from backup.
17615            if (!replacing) {
17616                IntentFilterVerificationInfo ivi =
17617                        mSettings.getIntentFilterVerificationLPr(packageName);
17618                if (ivi != null) {
17619                    if (DEBUG_DOMAIN_VERIFICATION) {
17620                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17621                                + ivi.getStatusString());
17622                    }
17623                    return;
17624                }
17625            }
17626
17627            // If any filters need to be verified, then all need to be.
17628            boolean needToVerify = false;
17629            for (PackageParser.Activity a : pkg.activities) {
17630                for (ActivityIntentInfo filter : a.intents) {
17631                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17632                        if (DEBUG_DOMAIN_VERIFICATION) {
17633                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17634                        }
17635                        needToVerify = true;
17636                        break;
17637                    }
17638                }
17639            }
17640
17641            if (needToVerify) {
17642                final int verificationId = mIntentFilterVerificationToken++;
17643                for (PackageParser.Activity a : pkg.activities) {
17644                    for (ActivityIntentInfo filter : a.intents) {
17645                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17646                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17647                                    "Verification needed for IntentFilter:" + filter.toString());
17648                            mIntentFilterVerifier.addOneIntentFilterVerification(
17649                                    verifierUid, userId, verificationId, filter, packageName);
17650                            count++;
17651                        }
17652                    }
17653                }
17654            }
17655        }
17656
17657        if (count > 0) {
17658            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17659                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17660                    +  " for userId:" + userId);
17661            mIntentFilterVerifier.startVerifications(userId);
17662        } else {
17663            if (DEBUG_DOMAIN_VERIFICATION) {
17664                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17665            }
17666        }
17667    }
17668
17669    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17670        final ComponentName cn  = filter.activity.getComponentName();
17671        final String packageName = cn.getPackageName();
17672
17673        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17674                packageName);
17675        if (ivi == null) {
17676            return true;
17677        }
17678        int status = ivi.getStatus();
17679        switch (status) {
17680            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17681            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17682                return true;
17683
17684            default:
17685                // Nothing to do
17686                return false;
17687        }
17688    }
17689
17690    private static boolean isMultiArch(ApplicationInfo info) {
17691        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17692    }
17693
17694    private static boolean isExternal(PackageParser.Package pkg) {
17695        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17696    }
17697
17698    private static boolean isExternal(PackageSetting ps) {
17699        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17700    }
17701
17702    private static boolean isSystemApp(PackageParser.Package pkg) {
17703        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17704    }
17705
17706    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17707        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17708    }
17709
17710    private static boolean isOemApp(PackageParser.Package pkg) {
17711        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17712    }
17713
17714    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17715        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17716    }
17717
17718    private static boolean isSystemApp(PackageSetting ps) {
17719        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17720    }
17721
17722    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17723        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17724    }
17725
17726    private int packageFlagsToInstallFlags(PackageSetting ps) {
17727        int installFlags = 0;
17728        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17729            // This existing package was an external ASEC install when we have
17730            // the external flag without a UUID
17731            installFlags |= PackageManager.INSTALL_EXTERNAL;
17732        }
17733        if (ps.isForwardLocked()) {
17734            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17735        }
17736        return installFlags;
17737    }
17738
17739    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17740        if (isExternal(pkg)) {
17741            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17742                return StorageManager.UUID_PRIMARY_PHYSICAL;
17743            } else {
17744                return pkg.volumeUuid;
17745            }
17746        } else {
17747            return StorageManager.UUID_PRIVATE_INTERNAL;
17748        }
17749    }
17750
17751    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17752        if (isExternal(pkg)) {
17753            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17754                return mSettings.getExternalVersion();
17755            } else {
17756                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17757            }
17758        } else {
17759            return mSettings.getInternalVersion();
17760        }
17761    }
17762
17763    private void deleteTempPackageFiles() {
17764        final FilenameFilter filter = new FilenameFilter() {
17765            public boolean accept(File dir, String name) {
17766                return name.startsWith("vmdl") && name.endsWith(".tmp");
17767            }
17768        };
17769        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17770            file.delete();
17771        }
17772    }
17773
17774    @Override
17775    public void deletePackageAsUser(String packageName, int versionCode,
17776            IPackageDeleteObserver observer, int userId, int flags) {
17777        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17778                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17779    }
17780
17781    @Override
17782    public void deletePackageVersioned(VersionedPackage versionedPackage,
17783            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17784        final int callingUid = Binder.getCallingUid();
17785        mContext.enforceCallingOrSelfPermission(
17786                android.Manifest.permission.DELETE_PACKAGES, null);
17787        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17788        Preconditions.checkNotNull(versionedPackage);
17789        Preconditions.checkNotNull(observer);
17790        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17791                PackageManager.VERSION_CODE_HIGHEST,
17792                Integer.MAX_VALUE, "versionCode must be >= -1");
17793
17794        final String packageName = versionedPackage.getPackageName();
17795        final int versionCode = versionedPackage.getVersionCode();
17796        final String internalPackageName;
17797        synchronized (mPackages) {
17798            // Normalize package name to handle renamed packages and static libs
17799            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17800                    versionedPackage.getVersionCode());
17801        }
17802
17803        final int uid = Binder.getCallingUid();
17804        if (!isOrphaned(internalPackageName)
17805                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17806            try {
17807                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17808                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17809                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17810                observer.onUserActionRequired(intent);
17811            } catch (RemoteException re) {
17812            }
17813            return;
17814        }
17815        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17816        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17817        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17818            mContext.enforceCallingOrSelfPermission(
17819                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17820                    "deletePackage for user " + userId);
17821        }
17822
17823        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17824            try {
17825                observer.onPackageDeleted(packageName,
17826                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17827            } catch (RemoteException re) {
17828            }
17829            return;
17830        }
17831
17832        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17833            try {
17834                observer.onPackageDeleted(packageName,
17835                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17836            } catch (RemoteException re) {
17837            }
17838            return;
17839        }
17840
17841        if (DEBUG_REMOVE) {
17842            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17843                    + " deleteAllUsers: " + deleteAllUsers + " version="
17844                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17845                    ? "VERSION_CODE_HIGHEST" : versionCode));
17846        }
17847        // Queue up an async operation since the package deletion may take a little while.
17848        mHandler.post(new Runnable() {
17849            public void run() {
17850                mHandler.removeCallbacks(this);
17851                int returnCode;
17852                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17853                boolean doDeletePackage = true;
17854                if (ps != null) {
17855                    final boolean targetIsInstantApp =
17856                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17857                    doDeletePackage = !targetIsInstantApp
17858                            || canViewInstantApps;
17859                }
17860                if (doDeletePackage) {
17861                    if (!deleteAllUsers) {
17862                        returnCode = deletePackageX(internalPackageName, versionCode,
17863                                userId, deleteFlags);
17864                    } else {
17865                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17866                                internalPackageName, users);
17867                        // If nobody is blocking uninstall, proceed with delete for all users
17868                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17869                            returnCode = deletePackageX(internalPackageName, versionCode,
17870                                    userId, deleteFlags);
17871                        } else {
17872                            // Otherwise uninstall individually for users with blockUninstalls=false
17873                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17874                            for (int userId : users) {
17875                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17876                                    returnCode = deletePackageX(internalPackageName, versionCode,
17877                                            userId, userFlags);
17878                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17879                                        Slog.w(TAG, "Package delete failed for user " + userId
17880                                                + ", returnCode " + returnCode);
17881                                    }
17882                                }
17883                            }
17884                            // The app has only been marked uninstalled for certain users.
17885                            // We still need to report that delete was blocked
17886                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17887                        }
17888                    }
17889                } else {
17890                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17891                }
17892                try {
17893                    observer.onPackageDeleted(packageName, returnCode, null);
17894                } catch (RemoteException e) {
17895                    Log.i(TAG, "Observer no longer exists.");
17896                } //end catch
17897            } //end run
17898        });
17899    }
17900
17901    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17902        if (pkg.staticSharedLibName != null) {
17903            return pkg.manifestPackageName;
17904        }
17905        return pkg.packageName;
17906    }
17907
17908    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17909        // Handle renamed packages
17910        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17911        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17912
17913        // Is this a static library?
17914        SparseArray<SharedLibraryEntry> versionedLib =
17915                mStaticLibsByDeclaringPackage.get(packageName);
17916        if (versionedLib == null || versionedLib.size() <= 0) {
17917            return packageName;
17918        }
17919
17920        // Figure out which lib versions the caller can see
17921        SparseIntArray versionsCallerCanSee = null;
17922        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17923        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17924                && callingAppId != Process.ROOT_UID) {
17925            versionsCallerCanSee = new SparseIntArray();
17926            String libName = versionedLib.valueAt(0).info.getName();
17927            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17928            if (uidPackages != null) {
17929                for (String uidPackage : uidPackages) {
17930                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17931                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17932                    if (libIdx >= 0) {
17933                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17934                        versionsCallerCanSee.append(libVersion, libVersion);
17935                    }
17936                }
17937            }
17938        }
17939
17940        // Caller can see nothing - done
17941        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17942            return packageName;
17943        }
17944
17945        // Find the version the caller can see and the app version code
17946        SharedLibraryEntry highestVersion = null;
17947        final int versionCount = versionedLib.size();
17948        for (int i = 0; i < versionCount; i++) {
17949            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17950            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17951                    libEntry.info.getVersion()) < 0) {
17952                continue;
17953            }
17954            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
17955            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17956                if (libVersionCode == versionCode) {
17957                    return libEntry.apk;
17958                }
17959            } else if (highestVersion == null) {
17960                highestVersion = libEntry;
17961            } else if (libVersionCode  > highestVersion.info
17962                    .getDeclaringPackage().getVersionCode()) {
17963                highestVersion = libEntry;
17964            }
17965        }
17966
17967        if (highestVersion != null) {
17968            return highestVersion.apk;
17969        }
17970
17971        return packageName;
17972    }
17973
17974    boolean isCallerVerifier(int callingUid) {
17975        final int callingUserId = UserHandle.getUserId(callingUid);
17976        return mRequiredVerifierPackage != null &&
17977                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17978    }
17979
17980    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17981        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17982              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17983            return true;
17984        }
17985        final int callingUserId = UserHandle.getUserId(callingUid);
17986        // If the caller installed the pkgName, then allow it to silently uninstall.
17987        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17988            return true;
17989        }
17990
17991        // Allow package verifier to silently uninstall.
17992        if (mRequiredVerifierPackage != null &&
17993                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17994            return true;
17995        }
17996
17997        // Allow package uninstaller to silently uninstall.
17998        if (mRequiredUninstallerPackage != null &&
17999                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18000            return true;
18001        }
18002
18003        // Allow storage manager to silently uninstall.
18004        if (mStorageManagerPackage != null &&
18005                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18006            return true;
18007        }
18008
18009        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18010        // uninstall for device owner provisioning.
18011        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18012                == PERMISSION_GRANTED) {
18013            return true;
18014        }
18015
18016        return false;
18017    }
18018
18019    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18020        int[] result = EMPTY_INT_ARRAY;
18021        for (int userId : userIds) {
18022            if (getBlockUninstallForUser(packageName, userId)) {
18023                result = ArrayUtils.appendInt(result, userId);
18024            }
18025        }
18026        return result;
18027    }
18028
18029    @Override
18030    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18031        final int callingUid = Binder.getCallingUid();
18032        if (getInstantAppPackageName(callingUid) != null
18033                && !isCallerSameApp(packageName, callingUid)) {
18034            return false;
18035        }
18036        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18037    }
18038
18039    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18040        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18041                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18042        try {
18043            if (dpm != null) {
18044                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18045                        /* callingUserOnly =*/ false);
18046                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18047                        : deviceOwnerComponentName.getPackageName();
18048                // Does the package contains the device owner?
18049                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18050                // this check is probably not needed, since DO should be registered as a device
18051                // admin on some user too. (Original bug for this: b/17657954)
18052                if (packageName.equals(deviceOwnerPackageName)) {
18053                    return true;
18054                }
18055                // Does it contain a device admin for any user?
18056                int[] users;
18057                if (userId == UserHandle.USER_ALL) {
18058                    users = sUserManager.getUserIds();
18059                } else {
18060                    users = new int[]{userId};
18061                }
18062                for (int i = 0; i < users.length; ++i) {
18063                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18064                        return true;
18065                    }
18066                }
18067            }
18068        } catch (RemoteException e) {
18069        }
18070        return false;
18071    }
18072
18073    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18074        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18075    }
18076
18077    /**
18078     *  This method is an internal method that could be get invoked either
18079     *  to delete an installed package or to clean up a failed installation.
18080     *  After deleting an installed package, a broadcast is sent to notify any
18081     *  listeners that the package has been removed. For cleaning up a failed
18082     *  installation, the broadcast is not necessary since the package's
18083     *  installation wouldn't have sent the initial broadcast either
18084     *  The key steps in deleting a package are
18085     *  deleting the package information in internal structures like mPackages,
18086     *  deleting the packages base directories through installd
18087     *  updating mSettings to reflect current status
18088     *  persisting settings for later use
18089     *  sending a broadcast if necessary
18090     */
18091    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18092        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18093        final boolean res;
18094
18095        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18096                ? UserHandle.USER_ALL : userId;
18097
18098        if (isPackageDeviceAdmin(packageName, removeUser)) {
18099            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18100            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18101        }
18102
18103        PackageSetting uninstalledPs = null;
18104        PackageParser.Package pkg = null;
18105
18106        // for the uninstall-updates case and restricted profiles, remember the per-
18107        // user handle installed state
18108        int[] allUsers;
18109        synchronized (mPackages) {
18110            uninstalledPs = mSettings.mPackages.get(packageName);
18111            if (uninstalledPs == null) {
18112                Slog.w(TAG, "Not removing non-existent package " + packageName);
18113                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18114            }
18115
18116            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18117                    && uninstalledPs.versionCode != versionCode) {
18118                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18119                        + uninstalledPs.versionCode + " != " + versionCode);
18120                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18121            }
18122
18123            // Static shared libs can be declared by any package, so let us not
18124            // allow removing a package if it provides a lib others depend on.
18125            pkg = mPackages.get(packageName);
18126
18127            allUsers = sUserManager.getUserIds();
18128
18129            if (pkg != null && pkg.staticSharedLibName != null) {
18130                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18131                        pkg.staticSharedLibVersion);
18132                if (libEntry != null) {
18133                    for (int currUserId : allUsers) {
18134                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18135                            continue;
18136                        }
18137                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18138                                libEntry.info, 0, currUserId);
18139                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18140                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18141                                    + " hosting lib " + libEntry.info.getName() + " version "
18142                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18143                                    + " for user " + currUserId);
18144                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18145                        }
18146                    }
18147                }
18148            }
18149
18150            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18151        }
18152
18153        final int freezeUser;
18154        if (isUpdatedSystemApp(uninstalledPs)
18155                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18156            // We're downgrading a system app, which will apply to all users, so
18157            // freeze them all during the downgrade
18158            freezeUser = UserHandle.USER_ALL;
18159        } else {
18160            freezeUser = removeUser;
18161        }
18162
18163        synchronized (mInstallLock) {
18164            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18165            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18166                    deleteFlags, "deletePackageX")) {
18167                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18168                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18169            }
18170            synchronized (mPackages) {
18171                if (res) {
18172                    if (pkg != null) {
18173                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18174                    }
18175                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18176                    updateInstantAppInstallerLocked(packageName);
18177                }
18178            }
18179        }
18180
18181        if (res) {
18182            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18183            info.sendPackageRemovedBroadcasts(killApp);
18184            info.sendSystemPackageUpdatedBroadcasts();
18185            info.sendSystemPackageAppearedBroadcasts();
18186        }
18187        // Force a gc here.
18188        Runtime.getRuntime().gc();
18189        // Delete the resources here after sending the broadcast to let
18190        // other processes clean up before deleting resources.
18191        if (info.args != null) {
18192            synchronized (mInstallLock) {
18193                info.args.doPostDeleteLI(true);
18194            }
18195        }
18196
18197        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18198    }
18199
18200    static class PackageRemovedInfo {
18201        final PackageSender packageSender;
18202        String removedPackage;
18203        String installerPackageName;
18204        int uid = -1;
18205        int removedAppId = -1;
18206        int[] origUsers;
18207        int[] removedUsers = null;
18208        int[] broadcastUsers = null;
18209        SparseArray<Integer> installReasons;
18210        boolean isRemovedPackageSystemUpdate = false;
18211        boolean isUpdate;
18212        boolean dataRemoved;
18213        boolean removedForAllUsers;
18214        boolean isStaticSharedLib;
18215        // Clean up resources deleted packages.
18216        InstallArgs args = null;
18217        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18218        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18219
18220        PackageRemovedInfo(PackageSender packageSender) {
18221            this.packageSender = packageSender;
18222        }
18223
18224        void sendPackageRemovedBroadcasts(boolean killApp) {
18225            sendPackageRemovedBroadcastInternal(killApp);
18226            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18227            for (int i = 0; i < childCount; i++) {
18228                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18229                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18230            }
18231        }
18232
18233        void sendSystemPackageUpdatedBroadcasts() {
18234            if (isRemovedPackageSystemUpdate) {
18235                sendSystemPackageUpdatedBroadcastsInternal();
18236                final int childCount = (removedChildPackages != null)
18237                        ? removedChildPackages.size() : 0;
18238                for (int i = 0; i < childCount; i++) {
18239                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18240                    if (childInfo.isRemovedPackageSystemUpdate) {
18241                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18242                    }
18243                }
18244            }
18245        }
18246
18247        void sendSystemPackageAppearedBroadcasts() {
18248            final int packageCount = (appearedChildPackages != null)
18249                    ? appearedChildPackages.size() : 0;
18250            for (int i = 0; i < packageCount; i++) {
18251                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18252                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18253                    true /*sendBootCompleted*/, false /*startReceiver*/,
18254                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18255            }
18256        }
18257
18258        private void sendSystemPackageUpdatedBroadcastsInternal() {
18259            Bundle extras = new Bundle(2);
18260            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18261            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18262            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18263                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18264            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18265                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18266            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18267                null, null, 0, removedPackage, null, null);
18268            if (installerPackageName != null) {
18269                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18270                        removedPackage, extras, 0 /*flags*/,
18271                        installerPackageName, null, null);
18272                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18273                        removedPackage, extras, 0 /*flags*/,
18274                        installerPackageName, null, null);
18275            }
18276        }
18277
18278        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18279            // Don't send static shared library removal broadcasts as these
18280            // libs are visible only the the apps that depend on them an one
18281            // cannot remove the library if it has a dependency.
18282            if (isStaticSharedLib) {
18283                return;
18284            }
18285            Bundle extras = new Bundle(2);
18286            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18287            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18288            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18289            if (isUpdate || isRemovedPackageSystemUpdate) {
18290                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18291            }
18292            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18293            if (removedPackage != null) {
18294                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18295                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18296                if (installerPackageName != null) {
18297                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18298                            removedPackage, extras, 0 /*flags*/,
18299                            installerPackageName, null, broadcastUsers);
18300                }
18301                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18302                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18303                        removedPackage, extras,
18304                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18305                        null, null, broadcastUsers);
18306                }
18307            }
18308            if (removedAppId >= 0) {
18309                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18310                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18311                    null, null, broadcastUsers);
18312            }
18313        }
18314
18315        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18316            removedUsers = userIds;
18317            if (removedUsers == null) {
18318                broadcastUsers = null;
18319                return;
18320            }
18321
18322            broadcastUsers = EMPTY_INT_ARRAY;
18323            for (int i = userIds.length - 1; i >= 0; --i) {
18324                final int userId = userIds[i];
18325                if (deletedPackageSetting.getInstantApp(userId)) {
18326                    continue;
18327                }
18328                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18329            }
18330        }
18331    }
18332
18333    /*
18334     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18335     * flag is not set, the data directory is removed as well.
18336     * make sure this flag is set for partially installed apps. If not its meaningless to
18337     * delete a partially installed application.
18338     */
18339    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18340            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18341        String packageName = ps.name;
18342        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18343        // Retrieve object to delete permissions for shared user later on
18344        final PackageParser.Package deletedPkg;
18345        final PackageSetting deletedPs;
18346        // reader
18347        synchronized (mPackages) {
18348            deletedPkg = mPackages.get(packageName);
18349            deletedPs = mSettings.mPackages.get(packageName);
18350            if (outInfo != null) {
18351                outInfo.removedPackage = packageName;
18352                outInfo.installerPackageName = ps.installerPackageName;
18353                outInfo.isStaticSharedLib = deletedPkg != null
18354                        && deletedPkg.staticSharedLibName != null;
18355                outInfo.populateUsers(deletedPs == null ? null
18356                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18357            }
18358        }
18359
18360        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18361
18362        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18363            final PackageParser.Package resolvedPkg;
18364            if (deletedPkg != null) {
18365                resolvedPkg = deletedPkg;
18366            } else {
18367                // We don't have a parsed package when it lives on an ejected
18368                // adopted storage device, so fake something together
18369                resolvedPkg = new PackageParser.Package(ps.name);
18370                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18371            }
18372            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18373                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18374            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18375            if (outInfo != null) {
18376                outInfo.dataRemoved = true;
18377            }
18378            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18379        }
18380
18381        int removedAppId = -1;
18382
18383        // writer
18384        synchronized (mPackages) {
18385            boolean installedStateChanged = false;
18386            if (deletedPs != null) {
18387                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18388                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18389                    clearDefaultBrowserIfNeeded(packageName);
18390                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18391                    removedAppId = mSettings.removePackageLPw(packageName);
18392                    if (outInfo != null) {
18393                        outInfo.removedAppId = removedAppId;
18394                    }
18395                    updatePermissionsLPw(deletedPs.name, null, 0);
18396                    if (deletedPs.sharedUser != null) {
18397                        // Remove permissions associated with package. Since runtime
18398                        // permissions are per user we have to kill the removed package
18399                        // or packages running under the shared user of the removed
18400                        // package if revoking the permissions requested only by the removed
18401                        // package is successful and this causes a change in gids.
18402                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18403                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18404                                    userId);
18405                            if (userIdToKill == UserHandle.USER_ALL
18406                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18407                                // If gids changed for this user, kill all affected packages.
18408                                mHandler.post(new Runnable() {
18409                                    @Override
18410                                    public void run() {
18411                                        // This has to happen with no lock held.
18412                                        killApplication(deletedPs.name, deletedPs.appId,
18413                                                KILL_APP_REASON_GIDS_CHANGED);
18414                                    }
18415                                });
18416                                break;
18417                            }
18418                        }
18419                    }
18420                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18421                }
18422                // make sure to preserve per-user disabled state if this removal was just
18423                // a downgrade of a system app to the factory package
18424                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18425                    if (DEBUG_REMOVE) {
18426                        Slog.d(TAG, "Propagating install state across downgrade");
18427                    }
18428                    for (int userId : allUserHandles) {
18429                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18430                        if (DEBUG_REMOVE) {
18431                            Slog.d(TAG, "    user " + userId + " => " + installed);
18432                        }
18433                        if (installed != ps.getInstalled(userId)) {
18434                            installedStateChanged = true;
18435                        }
18436                        ps.setInstalled(installed, userId);
18437                    }
18438                }
18439            }
18440            // can downgrade to reader
18441            if (writeSettings) {
18442                // Save settings now
18443                mSettings.writeLPr();
18444            }
18445            if (installedStateChanged) {
18446                mSettings.writeKernelMappingLPr(ps);
18447            }
18448        }
18449        if (removedAppId != -1) {
18450            // A user ID was deleted here. Go through all users and remove it
18451            // from KeyStore.
18452            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18453        }
18454    }
18455
18456    static boolean locationIsPrivileged(File path) {
18457        try {
18458            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18459                    .getCanonicalPath();
18460            return path.getCanonicalPath().startsWith(privilegedAppDir);
18461        } catch (IOException e) {
18462            Slog.e(TAG, "Unable to access code path " + path);
18463        }
18464        return false;
18465    }
18466
18467    static boolean locationIsOem(File path) {
18468        try {
18469            return path.getCanonicalPath().startsWith(
18470                    Environment.getOemDirectory().getCanonicalPath());
18471        } catch (IOException e) {
18472            Slog.e(TAG, "Unable to access code path " + path);
18473        }
18474        return false;
18475    }
18476
18477    /*
18478     * Tries to delete system package.
18479     */
18480    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18481            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18482            boolean writeSettings) {
18483        if (deletedPs.parentPackageName != null) {
18484            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18485            return false;
18486        }
18487
18488        final boolean applyUserRestrictions
18489                = (allUserHandles != null) && (outInfo.origUsers != null);
18490        final PackageSetting disabledPs;
18491        // Confirm if the system package has been updated
18492        // An updated system app can be deleted. This will also have to restore
18493        // the system pkg from system partition
18494        // reader
18495        synchronized (mPackages) {
18496            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18497        }
18498
18499        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18500                + " disabledPs=" + disabledPs);
18501
18502        if (disabledPs == null) {
18503            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18504            return false;
18505        } else if (DEBUG_REMOVE) {
18506            Slog.d(TAG, "Deleting system pkg from data partition");
18507        }
18508
18509        if (DEBUG_REMOVE) {
18510            if (applyUserRestrictions) {
18511                Slog.d(TAG, "Remembering install states:");
18512                for (int userId : allUserHandles) {
18513                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18514                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18515                }
18516            }
18517        }
18518
18519        // Delete the updated package
18520        outInfo.isRemovedPackageSystemUpdate = true;
18521        if (outInfo.removedChildPackages != null) {
18522            final int childCount = (deletedPs.childPackageNames != null)
18523                    ? deletedPs.childPackageNames.size() : 0;
18524            for (int i = 0; i < childCount; i++) {
18525                String childPackageName = deletedPs.childPackageNames.get(i);
18526                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18527                        .contains(childPackageName)) {
18528                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18529                            childPackageName);
18530                    if (childInfo != null) {
18531                        childInfo.isRemovedPackageSystemUpdate = true;
18532                    }
18533                }
18534            }
18535        }
18536
18537        if (disabledPs.versionCode < deletedPs.versionCode) {
18538            // Delete data for downgrades
18539            flags &= ~PackageManager.DELETE_KEEP_DATA;
18540        } else {
18541            // Preserve data by setting flag
18542            flags |= PackageManager.DELETE_KEEP_DATA;
18543        }
18544
18545        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18546                outInfo, writeSettings, disabledPs.pkg);
18547        if (!ret) {
18548            return false;
18549        }
18550
18551        // writer
18552        synchronized (mPackages) {
18553            // NOTE: The system package always needs to be enabled; even if it's for
18554            // a compressed stub. If we don't, installing the system package fails
18555            // during scan [scanning checks the disabled packages]. We will reverse
18556            // this later, after we've "installed" the stub.
18557            // Reinstate the old system package
18558            enableSystemPackageLPw(disabledPs.pkg);
18559            // Remove any native libraries from the upgraded package.
18560            removeNativeBinariesLI(deletedPs);
18561        }
18562
18563        // Install the system package
18564        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18565        try {
18566            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18567                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18568        } catch (PackageManagerException e) {
18569            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18570                    + e.getMessage());
18571            return false;
18572        } finally {
18573            if (disabledPs.pkg.isStub) {
18574                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18575            }
18576        }
18577        return true;
18578    }
18579
18580    /**
18581     * Installs a package that's already on the system partition.
18582     */
18583    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18584            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18585            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18586                    throws PackageManagerException {
18587        int parseFlags = mDefParseFlags
18588                | PackageParser.PARSE_MUST_BE_APK
18589                | PackageParser.PARSE_IS_SYSTEM
18590                | PackageParser.PARSE_IS_SYSTEM_DIR;
18591        if (isPrivileged || locationIsPrivileged(codePath)) {
18592            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18593        }
18594        if (locationIsOem(codePath)) {
18595            parseFlags |= PackageParser.PARSE_IS_OEM;
18596        }
18597
18598        final PackageParser.Package newPkg =
18599                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18600
18601        try {
18602            // update shared libraries for the newly re-installed system package
18603            updateSharedLibrariesLPr(newPkg, null);
18604        } catch (PackageManagerException e) {
18605            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18606        }
18607
18608        prepareAppDataAfterInstallLIF(newPkg);
18609
18610        // writer
18611        synchronized (mPackages) {
18612            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18613
18614            // Propagate the permissions state as we do not want to drop on the floor
18615            // runtime permissions. The update permissions method below will take
18616            // care of removing obsolete permissions and grant install permissions.
18617            if (origPermissionState != null) {
18618                ps.getPermissionsState().copyFrom(origPermissionState);
18619            }
18620            updatePermissionsLPw(newPkg.packageName, newPkg,
18621                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18622
18623            final boolean applyUserRestrictions
18624                    = (allUserHandles != null) && (origUserHandles != null);
18625            if (applyUserRestrictions) {
18626                boolean installedStateChanged = false;
18627                if (DEBUG_REMOVE) {
18628                    Slog.d(TAG, "Propagating install state across reinstall");
18629                }
18630                for (int userId : allUserHandles) {
18631                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18632                    if (DEBUG_REMOVE) {
18633                        Slog.d(TAG, "    user " + userId + " => " + installed);
18634                    }
18635                    if (installed != ps.getInstalled(userId)) {
18636                        installedStateChanged = true;
18637                    }
18638                    ps.setInstalled(installed, userId);
18639
18640                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18641                }
18642                // Regardless of writeSettings we need to ensure that this restriction
18643                // state propagation is persisted
18644                mSettings.writeAllUsersPackageRestrictionsLPr();
18645                if (installedStateChanged) {
18646                    mSettings.writeKernelMappingLPr(ps);
18647                }
18648            }
18649            // can downgrade to reader here
18650            if (writeSettings) {
18651                mSettings.writeLPr();
18652            }
18653        }
18654        return newPkg;
18655    }
18656
18657    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18658            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18659            PackageRemovedInfo outInfo, boolean writeSettings,
18660            PackageParser.Package replacingPackage) {
18661        synchronized (mPackages) {
18662            if (outInfo != null) {
18663                outInfo.uid = ps.appId;
18664            }
18665
18666            if (outInfo != null && outInfo.removedChildPackages != null) {
18667                final int childCount = (ps.childPackageNames != null)
18668                        ? ps.childPackageNames.size() : 0;
18669                for (int i = 0; i < childCount; i++) {
18670                    String childPackageName = ps.childPackageNames.get(i);
18671                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18672                    if (childPs == null) {
18673                        return false;
18674                    }
18675                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18676                            childPackageName);
18677                    if (childInfo != null) {
18678                        childInfo.uid = childPs.appId;
18679                    }
18680                }
18681            }
18682        }
18683
18684        // Delete package data from internal structures and also remove data if flag is set
18685        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18686
18687        // Delete the child packages data
18688        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18689        for (int i = 0; i < childCount; i++) {
18690            PackageSetting childPs;
18691            synchronized (mPackages) {
18692                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18693            }
18694            if (childPs != null) {
18695                PackageRemovedInfo childOutInfo = (outInfo != null
18696                        && outInfo.removedChildPackages != null)
18697                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18698                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18699                        && (replacingPackage != null
18700                        && !replacingPackage.hasChildPackage(childPs.name))
18701                        ? flags & ~DELETE_KEEP_DATA : flags;
18702                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18703                        deleteFlags, writeSettings);
18704            }
18705        }
18706
18707        // Delete application code and resources only for parent packages
18708        if (ps.parentPackageName == null) {
18709            if (deleteCodeAndResources && (outInfo != null)) {
18710                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18711                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18712                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18713            }
18714        }
18715
18716        return true;
18717    }
18718
18719    @Override
18720    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18721            int userId) {
18722        mContext.enforceCallingOrSelfPermission(
18723                android.Manifest.permission.DELETE_PACKAGES, null);
18724        synchronized (mPackages) {
18725            // Cannot block uninstall of static shared libs as they are
18726            // considered a part of the using app (emulating static linking).
18727            // Also static libs are installed always on internal storage.
18728            PackageParser.Package pkg = mPackages.get(packageName);
18729            if (pkg != null && pkg.staticSharedLibName != null) {
18730                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18731                        + " providing static shared library: " + pkg.staticSharedLibName);
18732                return false;
18733            }
18734            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18735            mSettings.writePackageRestrictionsLPr(userId);
18736        }
18737        return true;
18738    }
18739
18740    @Override
18741    public boolean getBlockUninstallForUser(String packageName, int userId) {
18742        synchronized (mPackages) {
18743            final PackageSetting ps = mSettings.mPackages.get(packageName);
18744            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18745                return false;
18746            }
18747            return mSettings.getBlockUninstallLPr(userId, packageName);
18748        }
18749    }
18750
18751    @Override
18752    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18753        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18754        synchronized (mPackages) {
18755            PackageSetting ps = mSettings.mPackages.get(packageName);
18756            if (ps == null) {
18757                Log.w(TAG, "Package doesn't exist: " + packageName);
18758                return false;
18759            }
18760            if (systemUserApp) {
18761                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18762            } else {
18763                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18764            }
18765            mSettings.writeLPr();
18766        }
18767        return true;
18768    }
18769
18770    /*
18771     * This method handles package deletion in general
18772     */
18773    private boolean deletePackageLIF(String packageName, UserHandle user,
18774            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18775            PackageRemovedInfo outInfo, boolean writeSettings,
18776            PackageParser.Package replacingPackage) {
18777        if (packageName == null) {
18778            Slog.w(TAG, "Attempt to delete null packageName.");
18779            return false;
18780        }
18781
18782        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18783
18784        PackageSetting ps;
18785        synchronized (mPackages) {
18786            ps = mSettings.mPackages.get(packageName);
18787            if (ps == null) {
18788                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18789                return false;
18790            }
18791
18792            if (ps.parentPackageName != null && (!isSystemApp(ps)
18793                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18794                if (DEBUG_REMOVE) {
18795                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18796                            + ((user == null) ? UserHandle.USER_ALL : user));
18797                }
18798                final int removedUserId = (user != null) ? user.getIdentifier()
18799                        : UserHandle.USER_ALL;
18800                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18801                    return false;
18802                }
18803                markPackageUninstalledForUserLPw(ps, user);
18804                scheduleWritePackageRestrictionsLocked(user);
18805                return true;
18806            }
18807        }
18808
18809        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18810                && user.getIdentifier() != UserHandle.USER_ALL)) {
18811            // The caller is asking that the package only be deleted for a single
18812            // user.  To do this, we just mark its uninstalled state and delete
18813            // its data. If this is a system app, we only allow this to happen if
18814            // they have set the special DELETE_SYSTEM_APP which requests different
18815            // semantics than normal for uninstalling system apps.
18816            markPackageUninstalledForUserLPw(ps, user);
18817
18818            if (!isSystemApp(ps)) {
18819                // Do not uninstall the APK if an app should be cached
18820                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18821                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18822                    // Other user still have this package installed, so all
18823                    // we need to do is clear this user's data and save that
18824                    // it is uninstalled.
18825                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18826                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18827                        return false;
18828                    }
18829                    scheduleWritePackageRestrictionsLocked(user);
18830                    return true;
18831                } else {
18832                    // We need to set it back to 'installed' so the uninstall
18833                    // broadcasts will be sent correctly.
18834                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18835                    ps.setInstalled(true, user.getIdentifier());
18836                    mSettings.writeKernelMappingLPr(ps);
18837                }
18838            } else {
18839                // This is a system app, so we assume that the
18840                // other users still have this package installed, so all
18841                // we need to do is clear this user's data and save that
18842                // it is uninstalled.
18843                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18844                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18845                    return false;
18846                }
18847                scheduleWritePackageRestrictionsLocked(user);
18848                return true;
18849            }
18850        }
18851
18852        // If we are deleting a composite package for all users, keep track
18853        // of result for each child.
18854        if (ps.childPackageNames != null && outInfo != null) {
18855            synchronized (mPackages) {
18856                final int childCount = ps.childPackageNames.size();
18857                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18858                for (int i = 0; i < childCount; i++) {
18859                    String childPackageName = ps.childPackageNames.get(i);
18860                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18861                    childInfo.removedPackage = childPackageName;
18862                    childInfo.installerPackageName = ps.installerPackageName;
18863                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18864                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18865                    if (childPs != null) {
18866                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18867                    }
18868                }
18869            }
18870        }
18871
18872        boolean ret = false;
18873        if (isSystemApp(ps)) {
18874            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18875            // When an updated system application is deleted we delete the existing resources
18876            // as well and fall back to existing code in system partition
18877            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18878        } else {
18879            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18880            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18881                    outInfo, writeSettings, replacingPackage);
18882        }
18883
18884        // Take a note whether we deleted the package for all users
18885        if (outInfo != null) {
18886            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18887            if (outInfo.removedChildPackages != null) {
18888                synchronized (mPackages) {
18889                    final int childCount = outInfo.removedChildPackages.size();
18890                    for (int i = 0; i < childCount; i++) {
18891                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18892                        if (childInfo != null) {
18893                            childInfo.removedForAllUsers = mPackages.get(
18894                                    childInfo.removedPackage) == null;
18895                        }
18896                    }
18897                }
18898            }
18899            // If we uninstalled an update to a system app there may be some
18900            // child packages that appeared as they are declared in the system
18901            // app but were not declared in the update.
18902            if (isSystemApp(ps)) {
18903                synchronized (mPackages) {
18904                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18905                    final int childCount = (updatedPs.childPackageNames != null)
18906                            ? updatedPs.childPackageNames.size() : 0;
18907                    for (int i = 0; i < childCount; i++) {
18908                        String childPackageName = updatedPs.childPackageNames.get(i);
18909                        if (outInfo.removedChildPackages == null
18910                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18911                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18912                            if (childPs == null) {
18913                                continue;
18914                            }
18915                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18916                            installRes.name = childPackageName;
18917                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18918                            installRes.pkg = mPackages.get(childPackageName);
18919                            installRes.uid = childPs.pkg.applicationInfo.uid;
18920                            if (outInfo.appearedChildPackages == null) {
18921                                outInfo.appearedChildPackages = new ArrayMap<>();
18922                            }
18923                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18924                        }
18925                    }
18926                }
18927            }
18928        }
18929
18930        return ret;
18931    }
18932
18933    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18934        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18935                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18936        for (int nextUserId : userIds) {
18937            if (DEBUG_REMOVE) {
18938                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18939            }
18940            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18941                    false /*installed*/,
18942                    true /*stopped*/,
18943                    true /*notLaunched*/,
18944                    false /*hidden*/,
18945                    false /*suspended*/,
18946                    false /*instantApp*/,
18947                    false /*virtualPreload*/,
18948                    null /*lastDisableAppCaller*/,
18949                    null /*enabledComponents*/,
18950                    null /*disabledComponents*/,
18951                    ps.readUserState(nextUserId).domainVerificationStatus,
18952                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18953        }
18954        mSettings.writeKernelMappingLPr(ps);
18955    }
18956
18957    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18958            PackageRemovedInfo outInfo) {
18959        final PackageParser.Package pkg;
18960        synchronized (mPackages) {
18961            pkg = mPackages.get(ps.name);
18962        }
18963
18964        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18965                : new int[] {userId};
18966        for (int nextUserId : userIds) {
18967            if (DEBUG_REMOVE) {
18968                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18969                        + nextUserId);
18970            }
18971
18972            destroyAppDataLIF(pkg, userId,
18973                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18974            destroyAppProfilesLIF(pkg, userId);
18975            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18976            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18977            schedulePackageCleaning(ps.name, nextUserId, false);
18978            synchronized (mPackages) {
18979                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18980                    scheduleWritePackageRestrictionsLocked(nextUserId);
18981                }
18982                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18983            }
18984        }
18985
18986        if (outInfo != null) {
18987            outInfo.removedPackage = ps.name;
18988            outInfo.installerPackageName = ps.installerPackageName;
18989            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18990            outInfo.removedAppId = ps.appId;
18991            outInfo.removedUsers = userIds;
18992            outInfo.broadcastUsers = userIds;
18993        }
18994
18995        return true;
18996    }
18997
18998    private final class ClearStorageConnection implements ServiceConnection {
18999        IMediaContainerService mContainerService;
19000
19001        @Override
19002        public void onServiceConnected(ComponentName name, IBinder service) {
19003            synchronized (this) {
19004                mContainerService = IMediaContainerService.Stub
19005                        .asInterface(Binder.allowBlocking(service));
19006                notifyAll();
19007            }
19008        }
19009
19010        @Override
19011        public void onServiceDisconnected(ComponentName name) {
19012        }
19013    }
19014
19015    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19016        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19017
19018        final boolean mounted;
19019        if (Environment.isExternalStorageEmulated()) {
19020            mounted = true;
19021        } else {
19022            final String status = Environment.getExternalStorageState();
19023
19024            mounted = status.equals(Environment.MEDIA_MOUNTED)
19025                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19026        }
19027
19028        if (!mounted) {
19029            return;
19030        }
19031
19032        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19033        int[] users;
19034        if (userId == UserHandle.USER_ALL) {
19035            users = sUserManager.getUserIds();
19036        } else {
19037            users = new int[] { userId };
19038        }
19039        final ClearStorageConnection conn = new ClearStorageConnection();
19040        if (mContext.bindServiceAsUser(
19041                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19042            try {
19043                for (int curUser : users) {
19044                    long timeout = SystemClock.uptimeMillis() + 5000;
19045                    synchronized (conn) {
19046                        long now;
19047                        while (conn.mContainerService == null &&
19048                                (now = SystemClock.uptimeMillis()) < timeout) {
19049                            try {
19050                                conn.wait(timeout - now);
19051                            } catch (InterruptedException e) {
19052                            }
19053                        }
19054                    }
19055                    if (conn.mContainerService == null) {
19056                        return;
19057                    }
19058
19059                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19060                    clearDirectory(conn.mContainerService,
19061                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19062                    if (allData) {
19063                        clearDirectory(conn.mContainerService,
19064                                userEnv.buildExternalStorageAppDataDirs(packageName));
19065                        clearDirectory(conn.mContainerService,
19066                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19067                    }
19068                }
19069            } finally {
19070                mContext.unbindService(conn);
19071            }
19072        }
19073    }
19074
19075    @Override
19076    public void clearApplicationProfileData(String packageName) {
19077        enforceSystemOrRoot("Only the system can clear all profile data");
19078
19079        final PackageParser.Package pkg;
19080        synchronized (mPackages) {
19081            pkg = mPackages.get(packageName);
19082        }
19083
19084        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19085            synchronized (mInstallLock) {
19086                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19087            }
19088        }
19089    }
19090
19091    @Override
19092    public void clearApplicationUserData(final String packageName,
19093            final IPackageDataObserver observer, final int userId) {
19094        mContext.enforceCallingOrSelfPermission(
19095                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19096
19097        final int callingUid = Binder.getCallingUid();
19098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19099                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19100
19101        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19102        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19103        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19104            throw new SecurityException("Cannot clear data for a protected package: "
19105                    + packageName);
19106        }
19107        // Queue up an async operation since the package deletion may take a little while.
19108        mHandler.post(new Runnable() {
19109            public void run() {
19110                mHandler.removeCallbacks(this);
19111                final boolean succeeded;
19112                if (!filterApp) {
19113                    try (PackageFreezer freezer = freezePackage(packageName,
19114                            "clearApplicationUserData")) {
19115                        synchronized (mInstallLock) {
19116                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19117                        }
19118                        clearExternalStorageDataSync(packageName, userId, true);
19119                        synchronized (mPackages) {
19120                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19121                                    packageName, userId);
19122                        }
19123                    }
19124                    if (succeeded) {
19125                        // invoke DeviceStorageMonitor's update method to clear any notifications
19126                        DeviceStorageMonitorInternal dsm = LocalServices
19127                                .getService(DeviceStorageMonitorInternal.class);
19128                        if (dsm != null) {
19129                            dsm.checkMemory();
19130                        }
19131                    }
19132                } else {
19133                    succeeded = false;
19134                }
19135                if (observer != null) {
19136                    try {
19137                        observer.onRemoveCompleted(packageName, succeeded);
19138                    } catch (RemoteException e) {
19139                        Log.i(TAG, "Observer no longer exists.");
19140                    }
19141                } //end if observer
19142            } //end run
19143        });
19144    }
19145
19146    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19147        if (packageName == null) {
19148            Slog.w(TAG, "Attempt to delete null packageName.");
19149            return false;
19150        }
19151
19152        // Try finding details about the requested package
19153        PackageParser.Package pkg;
19154        synchronized (mPackages) {
19155            pkg = mPackages.get(packageName);
19156            if (pkg == null) {
19157                final PackageSetting ps = mSettings.mPackages.get(packageName);
19158                if (ps != null) {
19159                    pkg = ps.pkg;
19160                }
19161            }
19162
19163            if (pkg == null) {
19164                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19165                return false;
19166            }
19167
19168            PackageSetting ps = (PackageSetting) pkg.mExtras;
19169            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19170        }
19171
19172        clearAppDataLIF(pkg, userId,
19173                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19174
19175        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19176        removeKeystoreDataIfNeeded(userId, appId);
19177
19178        UserManagerInternal umInternal = getUserManagerInternal();
19179        final int flags;
19180        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19181            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19182        } else if (umInternal.isUserRunning(userId)) {
19183            flags = StorageManager.FLAG_STORAGE_DE;
19184        } else {
19185            flags = 0;
19186        }
19187        prepareAppDataContentsLIF(pkg, userId, flags);
19188
19189        return true;
19190    }
19191
19192    /**
19193     * Reverts user permission state changes (permissions and flags) in
19194     * all packages for a given user.
19195     *
19196     * @param userId The device user for which to do a reset.
19197     */
19198    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19199        final int packageCount = mPackages.size();
19200        for (int i = 0; i < packageCount; i++) {
19201            PackageParser.Package pkg = mPackages.valueAt(i);
19202            PackageSetting ps = (PackageSetting) pkg.mExtras;
19203            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19204        }
19205    }
19206
19207    private void resetNetworkPolicies(int userId) {
19208        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19209    }
19210
19211    /**
19212     * Reverts user permission state changes (permissions and flags).
19213     *
19214     * @param ps The package for which to reset.
19215     * @param userId The device user for which to do a reset.
19216     */
19217    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19218            final PackageSetting ps, final int userId) {
19219        if (ps.pkg == null) {
19220            return;
19221        }
19222
19223        // These are flags that can change base on user actions.
19224        final int userSettableMask = FLAG_PERMISSION_USER_SET
19225                | FLAG_PERMISSION_USER_FIXED
19226                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19227                | FLAG_PERMISSION_REVIEW_REQUIRED;
19228
19229        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19230                | FLAG_PERMISSION_POLICY_FIXED;
19231
19232        boolean writeInstallPermissions = false;
19233        boolean writeRuntimePermissions = false;
19234
19235        final int permissionCount = ps.pkg.requestedPermissions.size();
19236        for (int i = 0; i < permissionCount; i++) {
19237            final String permName = ps.pkg.requestedPermissions.get(i);
19238            final BasePermission bp =
19239                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19240            if (bp == null) {
19241                continue;
19242            }
19243
19244            // If shared user we just reset the state to which only this app contributed.
19245            if (ps.sharedUser != null) {
19246                boolean used = false;
19247                final int packageCount = ps.sharedUser.packages.size();
19248                for (int j = 0; j < packageCount; j++) {
19249                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19250                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19251                            && pkg.pkg.requestedPermissions.contains(permName)) {
19252                        used = true;
19253                        break;
19254                    }
19255                }
19256                if (used) {
19257                    continue;
19258                }
19259            }
19260
19261            final PermissionsState permissionsState = ps.getPermissionsState();
19262
19263            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19264
19265            // Always clear the user settable flags.
19266            final boolean hasInstallState =
19267                    permissionsState.getInstallPermissionState(permName) != null;
19268            // If permission review is enabled and this is a legacy app, mark the
19269            // permission as requiring a review as this is the initial state.
19270            int flags = 0;
19271            if (mPermissionReviewRequired
19272                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19273                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19274            }
19275            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19276                if (hasInstallState) {
19277                    writeInstallPermissions = true;
19278                } else {
19279                    writeRuntimePermissions = true;
19280                }
19281            }
19282
19283            // Below is only runtime permission handling.
19284            if (!bp.isRuntime()) {
19285                continue;
19286            }
19287
19288            // Never clobber system or policy.
19289            if ((oldFlags & policyOrSystemFlags) != 0) {
19290                continue;
19291            }
19292
19293            // If this permission was granted by default, make sure it is.
19294            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19295                if (permissionsState.grantRuntimePermission(bp, userId)
19296                        != PERMISSION_OPERATION_FAILURE) {
19297                    writeRuntimePermissions = true;
19298                }
19299            // If permission review is enabled the permissions for a legacy apps
19300            // are represented as constantly granted runtime ones, so don't revoke.
19301            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19302                // Otherwise, reset the permission.
19303                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19304                switch (revokeResult) {
19305                    case PERMISSION_OPERATION_SUCCESS:
19306                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19307                        writeRuntimePermissions = true;
19308                        final int appId = ps.appId;
19309                        mHandler.post(new Runnable() {
19310                            @Override
19311                            public void run() {
19312                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19313                            }
19314                        });
19315                    } break;
19316                }
19317            }
19318        }
19319
19320        // Synchronously write as we are taking permissions away.
19321        if (writeRuntimePermissions) {
19322            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19323        }
19324
19325        // Synchronously write as we are taking permissions away.
19326        if (writeInstallPermissions) {
19327            mSettings.writeLPr();
19328        }
19329    }
19330
19331    /**
19332     * Remove entries from the keystore daemon. Will only remove it if the
19333     * {@code appId} is valid.
19334     */
19335    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19336        if (appId < 0) {
19337            return;
19338        }
19339
19340        final KeyStore keyStore = KeyStore.getInstance();
19341        if (keyStore != null) {
19342            if (userId == UserHandle.USER_ALL) {
19343                for (final int individual : sUserManager.getUserIds()) {
19344                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19345                }
19346            } else {
19347                keyStore.clearUid(UserHandle.getUid(userId, appId));
19348            }
19349        } else {
19350            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19351        }
19352    }
19353
19354    @Override
19355    public void deleteApplicationCacheFiles(final String packageName,
19356            final IPackageDataObserver observer) {
19357        final int userId = UserHandle.getCallingUserId();
19358        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19359    }
19360
19361    @Override
19362    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19363            final IPackageDataObserver observer) {
19364        final int callingUid = Binder.getCallingUid();
19365        mContext.enforceCallingOrSelfPermission(
19366                android.Manifest.permission.DELETE_CACHE_FILES, null);
19367        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19368                /* requireFullPermission= */ true, /* checkShell= */ false,
19369                "delete application cache files");
19370        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19371                android.Manifest.permission.ACCESS_INSTANT_APPS);
19372
19373        final PackageParser.Package pkg;
19374        synchronized (mPackages) {
19375            pkg = mPackages.get(packageName);
19376        }
19377
19378        // Queue up an async operation since the package deletion may take a little while.
19379        mHandler.post(new Runnable() {
19380            public void run() {
19381                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19382                boolean doClearData = true;
19383                if (ps != null) {
19384                    final boolean targetIsInstantApp =
19385                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19386                    doClearData = !targetIsInstantApp
19387                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19388                }
19389                if (doClearData) {
19390                    synchronized (mInstallLock) {
19391                        final int flags = StorageManager.FLAG_STORAGE_DE
19392                                | StorageManager.FLAG_STORAGE_CE;
19393                        // We're only clearing cache files, so we don't care if the
19394                        // app is unfrozen and still able to run
19395                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19396                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19397                    }
19398                    clearExternalStorageDataSync(packageName, userId, false);
19399                }
19400                if (observer != null) {
19401                    try {
19402                        observer.onRemoveCompleted(packageName, true);
19403                    } catch (RemoteException e) {
19404                        Log.i(TAG, "Observer no longer exists.");
19405                    }
19406                }
19407            }
19408        });
19409    }
19410
19411    @Override
19412    public void getPackageSizeInfo(final String packageName, int userHandle,
19413            final IPackageStatsObserver observer) {
19414        throw new UnsupportedOperationException(
19415                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19416    }
19417
19418    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19419        final PackageSetting ps;
19420        synchronized (mPackages) {
19421            ps = mSettings.mPackages.get(packageName);
19422            if (ps == null) {
19423                Slog.w(TAG, "Failed to find settings for " + packageName);
19424                return false;
19425            }
19426        }
19427
19428        final String[] packageNames = { packageName };
19429        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19430        final String[] codePaths = { ps.codePathString };
19431
19432        try {
19433            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19434                    ps.appId, ceDataInodes, codePaths, stats);
19435
19436            // For now, ignore code size of packages on system partition
19437            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19438                stats.codeSize = 0;
19439            }
19440
19441            // External clients expect these to be tracked separately
19442            stats.dataSize -= stats.cacheSize;
19443
19444        } catch (InstallerException e) {
19445            Slog.w(TAG, String.valueOf(e));
19446            return false;
19447        }
19448
19449        return true;
19450    }
19451
19452    private int getUidTargetSdkVersionLockedLPr(int uid) {
19453        Object obj = mSettings.getUserIdLPr(uid);
19454        if (obj instanceof SharedUserSetting) {
19455            final SharedUserSetting sus = (SharedUserSetting) obj;
19456            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19457            final Iterator<PackageSetting> it = sus.packages.iterator();
19458            while (it.hasNext()) {
19459                final PackageSetting ps = it.next();
19460                if (ps.pkg != null) {
19461                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19462                    if (v < vers) vers = v;
19463                }
19464            }
19465            return vers;
19466        } else if (obj instanceof PackageSetting) {
19467            final PackageSetting ps = (PackageSetting) obj;
19468            if (ps.pkg != null) {
19469                return ps.pkg.applicationInfo.targetSdkVersion;
19470            }
19471        }
19472        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19473    }
19474
19475    @Override
19476    public void addPreferredActivity(IntentFilter filter, int match,
19477            ComponentName[] set, ComponentName activity, int userId) {
19478        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19479                "Adding preferred");
19480    }
19481
19482    private void addPreferredActivityInternal(IntentFilter filter, int match,
19483            ComponentName[] set, ComponentName activity, boolean always, int userId,
19484            String opname) {
19485        // writer
19486        int callingUid = Binder.getCallingUid();
19487        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19488                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19489        if (filter.countActions() == 0) {
19490            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19491            return;
19492        }
19493        synchronized (mPackages) {
19494            if (mContext.checkCallingOrSelfPermission(
19495                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19496                    != PackageManager.PERMISSION_GRANTED) {
19497                if (getUidTargetSdkVersionLockedLPr(callingUid)
19498                        < Build.VERSION_CODES.FROYO) {
19499                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19500                            + callingUid);
19501                    return;
19502                }
19503                mContext.enforceCallingOrSelfPermission(
19504                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19505            }
19506
19507            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19508            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19509                    + userId + ":");
19510            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19511            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19512            scheduleWritePackageRestrictionsLocked(userId);
19513            postPreferredActivityChangedBroadcast(userId);
19514        }
19515    }
19516
19517    private void postPreferredActivityChangedBroadcast(int userId) {
19518        mHandler.post(() -> {
19519            final IActivityManager am = ActivityManager.getService();
19520            if (am == null) {
19521                return;
19522            }
19523
19524            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19525            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19526            try {
19527                am.broadcastIntent(null, intent, null, null,
19528                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19529                        null, false, false, userId);
19530            } catch (RemoteException e) {
19531            }
19532        });
19533    }
19534
19535    @Override
19536    public void replacePreferredActivity(IntentFilter filter, int match,
19537            ComponentName[] set, ComponentName activity, int userId) {
19538        if (filter.countActions() != 1) {
19539            throw new IllegalArgumentException(
19540                    "replacePreferredActivity expects filter to have only 1 action.");
19541        }
19542        if (filter.countDataAuthorities() != 0
19543                || filter.countDataPaths() != 0
19544                || filter.countDataSchemes() > 1
19545                || filter.countDataTypes() != 0) {
19546            throw new IllegalArgumentException(
19547                    "replacePreferredActivity expects filter to have no data authorities, " +
19548                    "paths, or types; and at most one scheme.");
19549        }
19550
19551        final int callingUid = Binder.getCallingUid();
19552        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19553                true /* requireFullPermission */, false /* checkShell */,
19554                "replace preferred activity");
19555        synchronized (mPackages) {
19556            if (mContext.checkCallingOrSelfPermission(
19557                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19558                    != PackageManager.PERMISSION_GRANTED) {
19559                if (getUidTargetSdkVersionLockedLPr(callingUid)
19560                        < Build.VERSION_CODES.FROYO) {
19561                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19562                            + Binder.getCallingUid());
19563                    return;
19564                }
19565                mContext.enforceCallingOrSelfPermission(
19566                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19567            }
19568
19569            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19570            if (pir != null) {
19571                // Get all of the existing entries that exactly match this filter.
19572                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19573                if (existing != null && existing.size() == 1) {
19574                    PreferredActivity cur = existing.get(0);
19575                    if (DEBUG_PREFERRED) {
19576                        Slog.i(TAG, "Checking replace of preferred:");
19577                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19578                        if (!cur.mPref.mAlways) {
19579                            Slog.i(TAG, "  -- CUR; not mAlways!");
19580                        } else {
19581                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19582                            Slog.i(TAG, "  -- CUR: mSet="
19583                                    + Arrays.toString(cur.mPref.mSetComponents));
19584                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19585                            Slog.i(TAG, "  -- NEW: mMatch="
19586                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19587                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19588                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19589                        }
19590                    }
19591                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19592                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19593                            && cur.mPref.sameSet(set)) {
19594                        // Setting the preferred activity to what it happens to be already
19595                        if (DEBUG_PREFERRED) {
19596                            Slog.i(TAG, "Replacing with same preferred activity "
19597                                    + cur.mPref.mShortComponent + " for user "
19598                                    + userId + ":");
19599                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19600                        }
19601                        return;
19602                    }
19603                }
19604
19605                if (existing != null) {
19606                    if (DEBUG_PREFERRED) {
19607                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19608                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19609                    }
19610                    for (int i = 0; i < existing.size(); i++) {
19611                        PreferredActivity pa = existing.get(i);
19612                        if (DEBUG_PREFERRED) {
19613                            Slog.i(TAG, "Removing existing preferred activity "
19614                                    + pa.mPref.mComponent + ":");
19615                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19616                        }
19617                        pir.removeFilter(pa);
19618                    }
19619                }
19620            }
19621            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19622                    "Replacing preferred");
19623        }
19624    }
19625
19626    @Override
19627    public void clearPackagePreferredActivities(String packageName) {
19628        final int callingUid = Binder.getCallingUid();
19629        if (getInstantAppPackageName(callingUid) != null) {
19630            return;
19631        }
19632        // writer
19633        synchronized (mPackages) {
19634            PackageParser.Package pkg = mPackages.get(packageName);
19635            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19636                if (mContext.checkCallingOrSelfPermission(
19637                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19638                        != PackageManager.PERMISSION_GRANTED) {
19639                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19640                            < Build.VERSION_CODES.FROYO) {
19641                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19642                                + callingUid);
19643                        return;
19644                    }
19645                    mContext.enforceCallingOrSelfPermission(
19646                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19647                }
19648            }
19649            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19650            if (ps != null
19651                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19652                return;
19653            }
19654            int user = UserHandle.getCallingUserId();
19655            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19656                scheduleWritePackageRestrictionsLocked(user);
19657            }
19658        }
19659    }
19660
19661    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19662    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19663        ArrayList<PreferredActivity> removed = null;
19664        boolean changed = false;
19665        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19666            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19667            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19668            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19669                continue;
19670            }
19671            Iterator<PreferredActivity> it = pir.filterIterator();
19672            while (it.hasNext()) {
19673                PreferredActivity pa = it.next();
19674                // Mark entry for removal only if it matches the package name
19675                // and the entry is of type "always".
19676                if (packageName == null ||
19677                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19678                                && pa.mPref.mAlways)) {
19679                    if (removed == null) {
19680                        removed = new ArrayList<PreferredActivity>();
19681                    }
19682                    removed.add(pa);
19683                }
19684            }
19685            if (removed != null) {
19686                for (int j=0; j<removed.size(); j++) {
19687                    PreferredActivity pa = removed.get(j);
19688                    pir.removeFilter(pa);
19689                }
19690                changed = true;
19691            }
19692        }
19693        if (changed) {
19694            postPreferredActivityChangedBroadcast(userId);
19695        }
19696        return changed;
19697    }
19698
19699    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19700    private void clearIntentFilterVerificationsLPw(int userId) {
19701        final int packageCount = mPackages.size();
19702        for (int i = 0; i < packageCount; i++) {
19703            PackageParser.Package pkg = mPackages.valueAt(i);
19704            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19705        }
19706    }
19707
19708    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19709    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19710        if (userId == UserHandle.USER_ALL) {
19711            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19712                    sUserManager.getUserIds())) {
19713                for (int oneUserId : sUserManager.getUserIds()) {
19714                    scheduleWritePackageRestrictionsLocked(oneUserId);
19715                }
19716            }
19717        } else {
19718            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19719                scheduleWritePackageRestrictionsLocked(userId);
19720            }
19721        }
19722    }
19723
19724    /** Clears state for all users, and touches intent filter verification policy */
19725    void clearDefaultBrowserIfNeeded(String packageName) {
19726        for (int oneUserId : sUserManager.getUserIds()) {
19727            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19728        }
19729    }
19730
19731    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19732        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19733        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19734            if (packageName.equals(defaultBrowserPackageName)) {
19735                setDefaultBrowserPackageName(null, userId);
19736            }
19737        }
19738    }
19739
19740    @Override
19741    public void resetApplicationPreferences(int userId) {
19742        mContext.enforceCallingOrSelfPermission(
19743                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19744        final long identity = Binder.clearCallingIdentity();
19745        // writer
19746        try {
19747            synchronized (mPackages) {
19748                clearPackagePreferredActivitiesLPw(null, userId);
19749                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19750                // TODO: We have to reset the default SMS and Phone. This requires
19751                // significant refactoring to keep all default apps in the package
19752                // manager (cleaner but more work) or have the services provide
19753                // callbacks to the package manager to request a default app reset.
19754                applyFactoryDefaultBrowserLPw(userId);
19755                clearIntentFilterVerificationsLPw(userId);
19756                primeDomainVerificationsLPw(userId);
19757                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19758                scheduleWritePackageRestrictionsLocked(userId);
19759            }
19760            resetNetworkPolicies(userId);
19761        } finally {
19762            Binder.restoreCallingIdentity(identity);
19763        }
19764    }
19765
19766    @Override
19767    public int getPreferredActivities(List<IntentFilter> outFilters,
19768            List<ComponentName> outActivities, String packageName) {
19769        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19770            return 0;
19771        }
19772        int num = 0;
19773        final int userId = UserHandle.getCallingUserId();
19774        // reader
19775        synchronized (mPackages) {
19776            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19777            if (pir != null) {
19778                final Iterator<PreferredActivity> it = pir.filterIterator();
19779                while (it.hasNext()) {
19780                    final PreferredActivity pa = it.next();
19781                    if (packageName == null
19782                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19783                                    && pa.mPref.mAlways)) {
19784                        if (outFilters != null) {
19785                            outFilters.add(new IntentFilter(pa));
19786                        }
19787                        if (outActivities != null) {
19788                            outActivities.add(pa.mPref.mComponent);
19789                        }
19790                    }
19791                }
19792            }
19793        }
19794
19795        return num;
19796    }
19797
19798    @Override
19799    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19800            int userId) {
19801        int callingUid = Binder.getCallingUid();
19802        if (callingUid != Process.SYSTEM_UID) {
19803            throw new SecurityException(
19804                    "addPersistentPreferredActivity can only be run by the system");
19805        }
19806        if (filter.countActions() == 0) {
19807            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19808            return;
19809        }
19810        synchronized (mPackages) {
19811            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19812                    ":");
19813            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19814            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19815                    new PersistentPreferredActivity(filter, activity));
19816            scheduleWritePackageRestrictionsLocked(userId);
19817            postPreferredActivityChangedBroadcast(userId);
19818        }
19819    }
19820
19821    @Override
19822    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19823        int callingUid = Binder.getCallingUid();
19824        if (callingUid != Process.SYSTEM_UID) {
19825            throw new SecurityException(
19826                    "clearPackagePersistentPreferredActivities can only be run by the system");
19827        }
19828        ArrayList<PersistentPreferredActivity> removed = null;
19829        boolean changed = false;
19830        synchronized (mPackages) {
19831            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19832                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19833                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19834                        .valueAt(i);
19835                if (userId != thisUserId) {
19836                    continue;
19837                }
19838                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19839                while (it.hasNext()) {
19840                    PersistentPreferredActivity ppa = it.next();
19841                    // Mark entry for removal only if it matches the package name.
19842                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19843                        if (removed == null) {
19844                            removed = new ArrayList<PersistentPreferredActivity>();
19845                        }
19846                        removed.add(ppa);
19847                    }
19848                }
19849                if (removed != null) {
19850                    for (int j=0; j<removed.size(); j++) {
19851                        PersistentPreferredActivity ppa = removed.get(j);
19852                        ppir.removeFilter(ppa);
19853                    }
19854                    changed = true;
19855                }
19856            }
19857
19858            if (changed) {
19859                scheduleWritePackageRestrictionsLocked(userId);
19860                postPreferredActivityChangedBroadcast(userId);
19861            }
19862        }
19863    }
19864
19865    /**
19866     * Common machinery for picking apart a restored XML blob and passing
19867     * it to a caller-supplied functor to be applied to the running system.
19868     */
19869    private void restoreFromXml(XmlPullParser parser, int userId,
19870            String expectedStartTag, BlobXmlRestorer functor)
19871            throws IOException, XmlPullParserException {
19872        int type;
19873        while ((type = parser.next()) != XmlPullParser.START_TAG
19874                && type != XmlPullParser.END_DOCUMENT) {
19875        }
19876        if (type != XmlPullParser.START_TAG) {
19877            // oops didn't find a start tag?!
19878            if (DEBUG_BACKUP) {
19879                Slog.e(TAG, "Didn't find start tag during restore");
19880            }
19881            return;
19882        }
19883Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19884        // this is supposed to be TAG_PREFERRED_BACKUP
19885        if (!expectedStartTag.equals(parser.getName())) {
19886            if (DEBUG_BACKUP) {
19887                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19888            }
19889            return;
19890        }
19891
19892        // skip interfering stuff, then we're aligned with the backing implementation
19893        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19894Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19895        functor.apply(parser, userId);
19896    }
19897
19898    private interface BlobXmlRestorer {
19899        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19900    }
19901
19902    /**
19903     * Non-Binder method, support for the backup/restore mechanism: write the
19904     * full set of preferred activities in its canonical XML format.  Returns the
19905     * XML output as a byte array, or null if there is none.
19906     */
19907    @Override
19908    public byte[] getPreferredActivityBackup(int userId) {
19909        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19910            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19911        }
19912
19913        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19914        try {
19915            final XmlSerializer serializer = new FastXmlSerializer();
19916            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19917            serializer.startDocument(null, true);
19918            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19919
19920            synchronized (mPackages) {
19921                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19922            }
19923
19924            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19925            serializer.endDocument();
19926            serializer.flush();
19927        } catch (Exception e) {
19928            if (DEBUG_BACKUP) {
19929                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19930            }
19931            return null;
19932        }
19933
19934        return dataStream.toByteArray();
19935    }
19936
19937    @Override
19938    public void restorePreferredActivities(byte[] backup, int userId) {
19939        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19940            throw new SecurityException("Only the system may call restorePreferredActivities()");
19941        }
19942
19943        try {
19944            final XmlPullParser parser = Xml.newPullParser();
19945            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19946            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19947                    new BlobXmlRestorer() {
19948                        @Override
19949                        public void apply(XmlPullParser parser, int userId)
19950                                throws XmlPullParserException, IOException {
19951                            synchronized (mPackages) {
19952                                mSettings.readPreferredActivitiesLPw(parser, userId);
19953                            }
19954                        }
19955                    } );
19956        } catch (Exception e) {
19957            if (DEBUG_BACKUP) {
19958                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19959            }
19960        }
19961    }
19962
19963    /**
19964     * Non-Binder method, support for the backup/restore mechanism: write the
19965     * default browser (etc) settings in its canonical XML format.  Returns the default
19966     * browser XML representation as a byte array, or null if there is none.
19967     */
19968    @Override
19969    public byte[] getDefaultAppsBackup(int userId) {
19970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19971            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19972        }
19973
19974        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19975        try {
19976            final XmlSerializer serializer = new FastXmlSerializer();
19977            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19978            serializer.startDocument(null, true);
19979            serializer.startTag(null, TAG_DEFAULT_APPS);
19980
19981            synchronized (mPackages) {
19982                mSettings.writeDefaultAppsLPr(serializer, userId);
19983            }
19984
19985            serializer.endTag(null, TAG_DEFAULT_APPS);
19986            serializer.endDocument();
19987            serializer.flush();
19988        } catch (Exception e) {
19989            if (DEBUG_BACKUP) {
19990                Slog.e(TAG, "Unable to write default apps for backup", e);
19991            }
19992            return null;
19993        }
19994
19995        return dataStream.toByteArray();
19996    }
19997
19998    @Override
19999    public void restoreDefaultApps(byte[] backup, int userId) {
20000        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20001            throw new SecurityException("Only the system may call restoreDefaultApps()");
20002        }
20003
20004        try {
20005            final XmlPullParser parser = Xml.newPullParser();
20006            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20007            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20008                    new BlobXmlRestorer() {
20009                        @Override
20010                        public void apply(XmlPullParser parser, int userId)
20011                                throws XmlPullParserException, IOException {
20012                            synchronized (mPackages) {
20013                                mSettings.readDefaultAppsLPw(parser, userId);
20014                            }
20015                        }
20016                    } );
20017        } catch (Exception e) {
20018            if (DEBUG_BACKUP) {
20019                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20020            }
20021        }
20022    }
20023
20024    @Override
20025    public byte[] getIntentFilterVerificationBackup(int userId) {
20026        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20027            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
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_INTENT_FILTER_VERIFICATION);
20036
20037            synchronized (mPackages) {
20038                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20039            }
20040
20041            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
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 restoreIntentFilterVerification(byte[] backup, int userId) {
20056        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20057            throw new SecurityException("Only the system may call restorePreferredActivities()");
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_INTENT_FILTER_VERIFICATION,
20064                    new BlobXmlRestorer() {
20065                        @Override
20066                        public void apply(XmlPullParser parser, int userId)
20067                                throws XmlPullParserException, IOException {
20068                            synchronized (mPackages) {
20069                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20070                                mSettings.writeLPr();
20071                            }
20072                        }
20073                    } );
20074        } catch (Exception e) {
20075            if (DEBUG_BACKUP) {
20076                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20077            }
20078        }
20079    }
20080
20081    @Override
20082    public byte[] getPermissionGrantBackup(int userId) {
20083        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20084            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20085        }
20086
20087        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20088        try {
20089            final XmlSerializer serializer = new FastXmlSerializer();
20090            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20091            serializer.startDocument(null, true);
20092            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20093
20094            synchronized (mPackages) {
20095                serializeRuntimePermissionGrantsLPr(serializer, userId);
20096            }
20097
20098            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20099            serializer.endDocument();
20100            serializer.flush();
20101        } catch (Exception e) {
20102            if (DEBUG_BACKUP) {
20103                Slog.e(TAG, "Unable to write default apps for backup", e);
20104            }
20105            return null;
20106        }
20107
20108        return dataStream.toByteArray();
20109    }
20110
20111    @Override
20112    public void restorePermissionGrants(byte[] backup, int userId) {
20113        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20114            throw new SecurityException("Only the system may call restorePermissionGrants()");
20115        }
20116
20117        try {
20118            final XmlPullParser parser = Xml.newPullParser();
20119            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20120            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20121                    new BlobXmlRestorer() {
20122                        @Override
20123                        public void apply(XmlPullParser parser, int userId)
20124                                throws XmlPullParserException, IOException {
20125                            synchronized (mPackages) {
20126                                processRestoredPermissionGrantsLPr(parser, userId);
20127                            }
20128                        }
20129                    } );
20130        } catch (Exception e) {
20131            if (DEBUG_BACKUP) {
20132                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20133            }
20134        }
20135    }
20136
20137    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20138            throws IOException {
20139        serializer.startTag(null, TAG_ALL_GRANTS);
20140
20141        final int N = mSettings.mPackages.size();
20142        for (int i = 0; i < N; i++) {
20143            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20144            boolean pkgGrantsKnown = false;
20145
20146            PermissionsState packagePerms = ps.getPermissionsState();
20147
20148            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20149                final int grantFlags = state.getFlags();
20150                // only look at grants that are not system/policy fixed
20151                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20152                    final boolean isGranted = state.isGranted();
20153                    // And only back up the user-twiddled state bits
20154                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20155                        final String packageName = mSettings.mPackages.keyAt(i);
20156                        if (!pkgGrantsKnown) {
20157                            serializer.startTag(null, TAG_GRANT);
20158                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20159                            pkgGrantsKnown = true;
20160                        }
20161
20162                        final boolean userSet =
20163                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20164                        final boolean userFixed =
20165                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20166                        final boolean revoke =
20167                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20168
20169                        serializer.startTag(null, TAG_PERMISSION);
20170                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20171                        if (isGranted) {
20172                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20173                        }
20174                        if (userSet) {
20175                            serializer.attribute(null, ATTR_USER_SET, "true");
20176                        }
20177                        if (userFixed) {
20178                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20179                        }
20180                        if (revoke) {
20181                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20182                        }
20183                        serializer.endTag(null, TAG_PERMISSION);
20184                    }
20185                }
20186            }
20187
20188            if (pkgGrantsKnown) {
20189                serializer.endTag(null, TAG_GRANT);
20190            }
20191        }
20192
20193        serializer.endTag(null, TAG_ALL_GRANTS);
20194    }
20195
20196    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20197            throws XmlPullParserException, IOException {
20198        String pkgName = null;
20199        int outerDepth = parser.getDepth();
20200        int type;
20201        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20202                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20203            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20204                continue;
20205            }
20206
20207            final String tagName = parser.getName();
20208            if (tagName.equals(TAG_GRANT)) {
20209                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20210                if (DEBUG_BACKUP) {
20211                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20212                }
20213            } else if (tagName.equals(TAG_PERMISSION)) {
20214
20215                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20216                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20217
20218                int newFlagSet = 0;
20219                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20220                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20221                }
20222                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20223                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20224                }
20225                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20226                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20227                }
20228                if (DEBUG_BACKUP) {
20229                    Slog.v(TAG, "  + Restoring grant:"
20230                            + " pkg=" + pkgName
20231                            + " perm=" + permName
20232                            + " granted=" + isGranted
20233                            + " bits=0x" + Integer.toHexString(newFlagSet));
20234                }
20235                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20236                if (ps != null) {
20237                    // Already installed so we apply the grant immediately
20238                    if (DEBUG_BACKUP) {
20239                        Slog.v(TAG, "        + already installed; applying");
20240                    }
20241                    PermissionsState perms = ps.getPermissionsState();
20242                    BasePermission bp =
20243                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20244                    if (bp != null) {
20245                        if (isGranted) {
20246                            perms.grantRuntimePermission(bp, userId);
20247                        }
20248                        if (newFlagSet != 0) {
20249                            perms.updatePermissionFlags(
20250                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20251                        }
20252                    }
20253                } else {
20254                    // Need to wait for post-restore install to apply the grant
20255                    if (DEBUG_BACKUP) {
20256                        Slog.v(TAG, "        - not yet installed; saving for later");
20257                    }
20258                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20259                            isGranted, newFlagSet, userId);
20260                }
20261            } else {
20262                PackageManagerService.reportSettingsProblem(Log.WARN,
20263                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20264                XmlUtils.skipCurrentTag(parser);
20265            }
20266        }
20267
20268        scheduleWriteSettingsLocked();
20269        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20270    }
20271
20272    @Override
20273    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20274            int sourceUserId, int targetUserId, int flags) {
20275        mContext.enforceCallingOrSelfPermission(
20276                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20277        int callingUid = Binder.getCallingUid();
20278        enforceOwnerRights(ownerPackage, callingUid);
20279        PackageManagerServiceUtils.enforceShellRestriction(
20280                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20281        if (intentFilter.countActions() == 0) {
20282            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20283            return;
20284        }
20285        synchronized (mPackages) {
20286            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20287                    ownerPackage, targetUserId, flags);
20288            CrossProfileIntentResolver resolver =
20289                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20290            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20291            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20292            if (existing != null) {
20293                int size = existing.size();
20294                for (int i = 0; i < size; i++) {
20295                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20296                        return;
20297                    }
20298                }
20299            }
20300            resolver.addFilter(newFilter);
20301            scheduleWritePackageRestrictionsLocked(sourceUserId);
20302        }
20303    }
20304
20305    @Override
20306    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20307        mContext.enforceCallingOrSelfPermission(
20308                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20309        final int callingUid = Binder.getCallingUid();
20310        enforceOwnerRights(ownerPackage, callingUid);
20311        PackageManagerServiceUtils.enforceShellRestriction(
20312                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20313        synchronized (mPackages) {
20314            CrossProfileIntentResolver resolver =
20315                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20316            ArraySet<CrossProfileIntentFilter> set =
20317                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20318            for (CrossProfileIntentFilter filter : set) {
20319                if (filter.getOwnerPackage().equals(ownerPackage)) {
20320                    resolver.removeFilter(filter);
20321                }
20322            }
20323            scheduleWritePackageRestrictionsLocked(sourceUserId);
20324        }
20325    }
20326
20327    // Enforcing that callingUid is owning pkg on userId
20328    private void enforceOwnerRights(String pkg, int callingUid) {
20329        // The system owns everything.
20330        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20331            return;
20332        }
20333        final int callingUserId = UserHandle.getUserId(callingUid);
20334        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20335        if (pi == null) {
20336            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20337                    + callingUserId);
20338        }
20339        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20340            throw new SecurityException("Calling uid " + callingUid
20341                    + " does not own package " + pkg);
20342        }
20343    }
20344
20345    @Override
20346    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20347        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20348            return null;
20349        }
20350        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20351    }
20352
20353    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20354        UserManagerService ums = UserManagerService.getInstance();
20355        if (ums != null) {
20356            final UserInfo parent = ums.getProfileParent(userId);
20357            final int launcherUid = (parent != null) ? parent.id : userId;
20358            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20359            if (launcherComponent != null) {
20360                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20361                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20362                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20363                        .setPackage(launcherComponent.getPackageName());
20364                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20365            }
20366        }
20367    }
20368
20369    /**
20370     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20371     * then reports the most likely home activity or null if there are more than one.
20372     */
20373    private ComponentName getDefaultHomeActivity(int userId) {
20374        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20375        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20376        if (cn != null) {
20377            return cn;
20378        }
20379
20380        // Find the launcher with the highest priority and return that component if there are no
20381        // other home activity with the same priority.
20382        int lastPriority = Integer.MIN_VALUE;
20383        ComponentName lastComponent = null;
20384        final int size = allHomeCandidates.size();
20385        for (int i = 0; i < size; i++) {
20386            final ResolveInfo ri = allHomeCandidates.get(i);
20387            if (ri.priority > lastPriority) {
20388                lastComponent = ri.activityInfo.getComponentName();
20389                lastPriority = ri.priority;
20390            } else if (ri.priority == lastPriority) {
20391                // Two components found with same priority.
20392                lastComponent = null;
20393            }
20394        }
20395        return lastComponent;
20396    }
20397
20398    private Intent getHomeIntent() {
20399        Intent intent = new Intent(Intent.ACTION_MAIN);
20400        intent.addCategory(Intent.CATEGORY_HOME);
20401        intent.addCategory(Intent.CATEGORY_DEFAULT);
20402        return intent;
20403    }
20404
20405    private IntentFilter getHomeFilter() {
20406        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20407        filter.addCategory(Intent.CATEGORY_HOME);
20408        filter.addCategory(Intent.CATEGORY_DEFAULT);
20409        return filter;
20410    }
20411
20412    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20413            int userId) {
20414        Intent intent  = getHomeIntent();
20415        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20416                PackageManager.GET_META_DATA, userId);
20417        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20418                true, false, false, userId);
20419
20420        allHomeCandidates.clear();
20421        if (list != null) {
20422            for (ResolveInfo ri : list) {
20423                allHomeCandidates.add(ri);
20424            }
20425        }
20426        return (preferred == null || preferred.activityInfo == null)
20427                ? null
20428                : new ComponentName(preferred.activityInfo.packageName,
20429                        preferred.activityInfo.name);
20430    }
20431
20432    @Override
20433    public void setHomeActivity(ComponentName comp, int userId) {
20434        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20435            return;
20436        }
20437        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20438        getHomeActivitiesAsUser(homeActivities, userId);
20439
20440        boolean found = false;
20441
20442        final int size = homeActivities.size();
20443        final ComponentName[] set = new ComponentName[size];
20444        for (int i = 0; i < size; i++) {
20445            final ResolveInfo candidate = homeActivities.get(i);
20446            final ActivityInfo info = candidate.activityInfo;
20447            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20448            set[i] = activityName;
20449            if (!found && activityName.equals(comp)) {
20450                found = true;
20451            }
20452        }
20453        if (!found) {
20454            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20455                    + userId);
20456        }
20457        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20458                set, comp, userId);
20459    }
20460
20461    private @Nullable String getSetupWizardPackageName() {
20462        final Intent intent = new Intent(Intent.ACTION_MAIN);
20463        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20464
20465        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20466                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20467                        | MATCH_DISABLED_COMPONENTS,
20468                UserHandle.myUserId());
20469        if (matches.size() == 1) {
20470            return matches.get(0).getComponentInfo().packageName;
20471        } else {
20472            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20473                    + ": matches=" + matches);
20474            return null;
20475        }
20476    }
20477
20478    private @Nullable String getStorageManagerPackageName() {
20479        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20480
20481        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20482                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20483                        | MATCH_DISABLED_COMPONENTS,
20484                UserHandle.myUserId());
20485        if (matches.size() == 1) {
20486            return matches.get(0).getComponentInfo().packageName;
20487        } else {
20488            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20489                    + matches.size() + ": matches=" + matches);
20490            return null;
20491        }
20492    }
20493
20494    @Override
20495    public void setApplicationEnabledSetting(String appPackageName,
20496            int newState, int flags, int userId, String callingPackage) {
20497        if (!sUserManager.exists(userId)) return;
20498        if (callingPackage == null) {
20499            callingPackage = Integer.toString(Binder.getCallingUid());
20500        }
20501        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20502    }
20503
20504    @Override
20505    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20506        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20507        synchronized (mPackages) {
20508            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20509            if (pkgSetting != null) {
20510                pkgSetting.setUpdateAvailable(updateAvailable);
20511            }
20512        }
20513    }
20514
20515    @Override
20516    public void setComponentEnabledSetting(ComponentName componentName,
20517            int newState, int flags, int userId) {
20518        if (!sUserManager.exists(userId)) return;
20519        setEnabledSetting(componentName.getPackageName(),
20520                componentName.getClassName(), newState, flags, userId, null);
20521    }
20522
20523    private void setEnabledSetting(final String packageName, String className, int newState,
20524            final int flags, int userId, String callingPackage) {
20525        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20526              || newState == COMPONENT_ENABLED_STATE_ENABLED
20527              || newState == COMPONENT_ENABLED_STATE_DISABLED
20528              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20529              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20530            throw new IllegalArgumentException("Invalid new component state: "
20531                    + newState);
20532        }
20533        PackageSetting pkgSetting;
20534        final int callingUid = Binder.getCallingUid();
20535        final int permission;
20536        if (callingUid == Process.SYSTEM_UID) {
20537            permission = PackageManager.PERMISSION_GRANTED;
20538        } else {
20539            permission = mContext.checkCallingOrSelfPermission(
20540                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20541        }
20542        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20543                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20544        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20545        boolean sendNow = false;
20546        boolean isApp = (className == null);
20547        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20548        String componentName = isApp ? packageName : className;
20549        int packageUid = -1;
20550        ArrayList<String> components;
20551
20552        // reader
20553        synchronized (mPackages) {
20554            pkgSetting = mSettings.mPackages.get(packageName);
20555            if (pkgSetting == null) {
20556                if (!isCallerInstantApp) {
20557                    if (className == null) {
20558                        throw new IllegalArgumentException("Unknown package: " + packageName);
20559                    }
20560                    throw new IllegalArgumentException(
20561                            "Unknown component: " + packageName + "/" + className);
20562                } else {
20563                    // throw SecurityException to prevent leaking package information
20564                    throw new SecurityException(
20565                            "Attempt to change component state; "
20566                            + "pid=" + Binder.getCallingPid()
20567                            + ", uid=" + callingUid
20568                            + (className == null
20569                                    ? ", package=" + packageName
20570                                    : ", component=" + packageName + "/" + className));
20571                }
20572            }
20573        }
20574
20575        // Limit who can change which apps
20576        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20577            // Don't allow apps that don't have permission to modify other apps
20578            if (!allowedByPermission
20579                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20580                throw new SecurityException(
20581                        "Attempt to change component state; "
20582                        + "pid=" + Binder.getCallingPid()
20583                        + ", uid=" + callingUid
20584                        + (className == null
20585                                ? ", package=" + packageName
20586                                : ", component=" + packageName + "/" + className));
20587            }
20588            // Don't allow changing protected packages.
20589            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20590                throw new SecurityException("Cannot disable a protected package: " + packageName);
20591            }
20592        }
20593
20594        synchronized (mPackages) {
20595            if (callingUid == Process.SHELL_UID
20596                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20597                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20598                // unless it is a test package.
20599                int oldState = pkgSetting.getEnabled(userId);
20600                if (className == null
20601                        &&
20602                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20603                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20604                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20605                        &&
20606                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20607                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20608                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20609                    // ok
20610                } else {
20611                    throw new SecurityException(
20612                            "Shell cannot change component state for " + packageName + "/"
20613                                    + className + " to " + newState);
20614                }
20615            }
20616        }
20617        if (className == null) {
20618            // We're dealing with an application/package level state change
20619            synchronized (mPackages) {
20620                if (pkgSetting.getEnabled(userId) == newState) {
20621                    // Nothing to do
20622                    return;
20623                }
20624            }
20625            // If we're enabling a system stub, there's a little more work to do.
20626            // Prior to enabling the package, we need to decompress the APK(s) to the
20627            // data partition and then replace the version on the system partition.
20628            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20629            final boolean isSystemStub = deletedPkg.isStub
20630                    && deletedPkg.isSystemApp();
20631            if (isSystemStub
20632                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20633                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20634                final File codePath = decompressPackage(deletedPkg);
20635                if (codePath == null) {
20636                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20637                    return;
20638                }
20639                // TODO remove direct parsing of the package object during internal cleanup
20640                // of scan package
20641                // We need to call parse directly here for no other reason than we need
20642                // the new package in order to disable the old one [we use the information
20643                // for some internal optimization to optionally create a new package setting
20644                // object on replace]. However, we can't get the package from the scan
20645                // because the scan modifies live structures and we need to remove the
20646                // old [system] package from the system before a scan can be attempted.
20647                // Once scan is indempotent we can remove this parse and use the package
20648                // object we scanned, prior to adding it to package settings.
20649                final PackageParser pp = new PackageParser();
20650                pp.setSeparateProcesses(mSeparateProcesses);
20651                pp.setDisplayMetrics(mMetrics);
20652                pp.setCallback(mPackageParserCallback);
20653                final PackageParser.Package tmpPkg;
20654                try {
20655                    final int parseFlags = mDefParseFlags
20656                            | PackageParser.PARSE_MUST_BE_APK
20657                            | PackageParser.PARSE_IS_SYSTEM
20658                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20659                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20660                } catch (PackageParserException e) {
20661                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20662                    return;
20663                }
20664                synchronized (mInstallLock) {
20665                    // Disable the stub and remove any package entries
20666                    removePackageLI(deletedPkg, true);
20667                    synchronized (mPackages) {
20668                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20669                    }
20670                    final PackageParser.Package newPkg;
20671                    try (PackageFreezer freezer =
20672                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20673                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20674                                | PackageParser.PARSE_ENFORCE_CODE;
20675                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20676                                0 /*currentTime*/, null /*user*/);
20677                        prepareAppDataAfterInstallLIF(newPkg);
20678                        synchronized (mPackages) {
20679                            try {
20680                                updateSharedLibrariesLPr(newPkg, null);
20681                            } catch (PackageManagerException e) {
20682                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20683                            }
20684                            updatePermissionsLPw(newPkg.packageName, newPkg,
20685                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20686                            mSettings.writeLPr();
20687                        }
20688                    } catch (PackageManagerException e) {
20689                        // Whoops! Something went wrong; try to roll back to the stub
20690                        Slog.w(TAG, "Failed to install compressed system package:"
20691                                + pkgSetting.name, e);
20692                        // Remove the failed install
20693                        removeCodePathLI(codePath);
20694
20695                        // Install the system package
20696                        try (PackageFreezer freezer =
20697                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20698                            synchronized (mPackages) {
20699                                // NOTE: The system package always needs to be enabled; even
20700                                // if it's for a compressed stub. If we don't, installing the
20701                                // system package fails during scan [scanning checks the disabled
20702                                // packages]. We will reverse this later, after we've "installed"
20703                                // the stub.
20704                                // This leaves us in a fragile state; the stub should never be
20705                                // enabled, so, cross your fingers and hope nothing goes wrong
20706                                // until we can disable the package later.
20707                                enableSystemPackageLPw(deletedPkg);
20708                            }
20709                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20710                                    false /*isPrivileged*/, null /*allUserHandles*/,
20711                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20712                                    true /*writeSettings*/);
20713                        } catch (PackageManagerException pme) {
20714                            Slog.w(TAG, "Failed to restore system package:"
20715                                    + deletedPkg.packageName, pme);
20716                        } finally {
20717                            synchronized (mPackages) {
20718                                mSettings.disableSystemPackageLPw(
20719                                        deletedPkg.packageName, true /*replaced*/);
20720                                mSettings.writeLPr();
20721                            }
20722                        }
20723                        return;
20724                    }
20725                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20726                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20727                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20728                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20729                            newPkg.baseCodePath, newPkg.splitCodePaths);
20730                }
20731            }
20732            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20733                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20734                // Don't care about who enables an app.
20735                callingPackage = null;
20736            }
20737            synchronized (mPackages) {
20738                pkgSetting.setEnabled(newState, userId, callingPackage);
20739            }
20740        } else {
20741            synchronized (mPackages) {
20742                // We're dealing with a component level state change
20743                // First, verify that this is a valid class name.
20744                PackageParser.Package pkg = pkgSetting.pkg;
20745                if (pkg == null || !pkg.hasComponentClassName(className)) {
20746                    if (pkg != null &&
20747                            pkg.applicationInfo.targetSdkVersion >=
20748                                    Build.VERSION_CODES.JELLY_BEAN) {
20749                        throw new IllegalArgumentException("Component class " + className
20750                                + " does not exist in " + packageName);
20751                    } else {
20752                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20753                                + className + " does not exist in " + packageName);
20754                    }
20755                }
20756                switch (newState) {
20757                    case COMPONENT_ENABLED_STATE_ENABLED:
20758                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20759                            return;
20760                        }
20761                        break;
20762                    case COMPONENT_ENABLED_STATE_DISABLED:
20763                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20764                            return;
20765                        }
20766                        break;
20767                    case COMPONENT_ENABLED_STATE_DEFAULT:
20768                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20769                            return;
20770                        }
20771                        break;
20772                    default:
20773                        Slog.e(TAG, "Invalid new component state: " + newState);
20774                        return;
20775                }
20776            }
20777        }
20778        synchronized (mPackages) {
20779            scheduleWritePackageRestrictionsLocked(userId);
20780            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20781            final long callingId = Binder.clearCallingIdentity();
20782            try {
20783                updateInstantAppInstallerLocked(packageName);
20784            } finally {
20785                Binder.restoreCallingIdentity(callingId);
20786            }
20787            components = mPendingBroadcasts.get(userId, packageName);
20788            final boolean newPackage = components == null;
20789            if (newPackage) {
20790                components = new ArrayList<String>();
20791            }
20792            if (!components.contains(componentName)) {
20793                components.add(componentName);
20794            }
20795            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20796                sendNow = true;
20797                // Purge entry from pending broadcast list if another one exists already
20798                // since we are sending one right away.
20799                mPendingBroadcasts.remove(userId, packageName);
20800            } else {
20801                if (newPackage) {
20802                    mPendingBroadcasts.put(userId, packageName, components);
20803                }
20804                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20805                    // Schedule a message
20806                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20807                }
20808            }
20809        }
20810
20811        long callingId = Binder.clearCallingIdentity();
20812        try {
20813            if (sendNow) {
20814                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20815                sendPackageChangedBroadcast(packageName,
20816                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20817            }
20818        } finally {
20819            Binder.restoreCallingIdentity(callingId);
20820        }
20821    }
20822
20823    @Override
20824    public void flushPackageRestrictionsAsUser(int userId) {
20825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20826            return;
20827        }
20828        if (!sUserManager.exists(userId)) {
20829            return;
20830        }
20831        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20832                false /* checkShell */, "flushPackageRestrictions");
20833        synchronized (mPackages) {
20834            mSettings.writePackageRestrictionsLPr(userId);
20835            mDirtyUsers.remove(userId);
20836            if (mDirtyUsers.isEmpty()) {
20837                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20838            }
20839        }
20840    }
20841
20842    private void sendPackageChangedBroadcast(String packageName,
20843            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20844        if (DEBUG_INSTALL)
20845            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20846                    + componentNames);
20847        Bundle extras = new Bundle(4);
20848        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20849        String nameList[] = new String[componentNames.size()];
20850        componentNames.toArray(nameList);
20851        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20852        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20853        extras.putInt(Intent.EXTRA_UID, packageUid);
20854        // If this is not reporting a change of the overall package, then only send it
20855        // to registered receivers.  We don't want to launch a swath of apps for every
20856        // little component state change.
20857        final int flags = !componentNames.contains(packageName)
20858                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20859        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20860                new int[] {UserHandle.getUserId(packageUid)});
20861    }
20862
20863    @Override
20864    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20865        if (!sUserManager.exists(userId)) return;
20866        final int callingUid = Binder.getCallingUid();
20867        if (getInstantAppPackageName(callingUid) != null) {
20868            return;
20869        }
20870        final int permission = mContext.checkCallingOrSelfPermission(
20871                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20872        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20873        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20874                true /* requireFullPermission */, true /* checkShell */, "stop package");
20875        // writer
20876        synchronized (mPackages) {
20877            final PackageSetting ps = mSettings.mPackages.get(packageName);
20878            if (!filterAppAccessLPr(ps, callingUid, userId)
20879                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20880                            allowedByPermission, callingUid, userId)) {
20881                scheduleWritePackageRestrictionsLocked(userId);
20882            }
20883        }
20884    }
20885
20886    @Override
20887    public String getInstallerPackageName(String packageName) {
20888        final int callingUid = Binder.getCallingUid();
20889        if (getInstantAppPackageName(callingUid) != null) {
20890            return null;
20891        }
20892        // reader
20893        synchronized (mPackages) {
20894            final PackageSetting ps = mSettings.mPackages.get(packageName);
20895            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20896                return null;
20897            }
20898            return mSettings.getInstallerPackageNameLPr(packageName);
20899        }
20900    }
20901
20902    public boolean isOrphaned(String packageName) {
20903        // reader
20904        synchronized (mPackages) {
20905            return mSettings.isOrphaned(packageName);
20906        }
20907    }
20908
20909    @Override
20910    public int getApplicationEnabledSetting(String packageName, int userId) {
20911        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20912        int callingUid = Binder.getCallingUid();
20913        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20914                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20915        // reader
20916        synchronized (mPackages) {
20917            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20918                return COMPONENT_ENABLED_STATE_DISABLED;
20919            }
20920            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20921        }
20922    }
20923
20924    @Override
20925    public int getComponentEnabledSetting(ComponentName component, int userId) {
20926        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20927        int callingUid = Binder.getCallingUid();
20928        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20929                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20930        synchronized (mPackages) {
20931            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20932                    component, TYPE_UNKNOWN, userId)) {
20933                return COMPONENT_ENABLED_STATE_DISABLED;
20934            }
20935            return mSettings.getComponentEnabledSettingLPr(component, userId);
20936        }
20937    }
20938
20939    @Override
20940    public void enterSafeMode() {
20941        enforceSystemOrRoot("Only the system can request entering safe mode");
20942
20943        if (!mSystemReady) {
20944            mSafeMode = true;
20945        }
20946    }
20947
20948    @Override
20949    public void systemReady() {
20950        enforceSystemOrRoot("Only the system can claim the system is ready");
20951
20952        mSystemReady = true;
20953        final ContentResolver resolver = mContext.getContentResolver();
20954        ContentObserver co = new ContentObserver(mHandler) {
20955            @Override
20956            public void onChange(boolean selfChange) {
20957                mEphemeralAppsDisabled =
20958                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20959                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20960            }
20961        };
20962        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20963                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20964                false, co, UserHandle.USER_SYSTEM);
20965        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20966                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20967        co.onChange(true);
20968
20969        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20970        // disabled after already being started.
20971        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20972                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20973
20974        // Read the compatibilty setting when the system is ready.
20975        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20976                mContext.getContentResolver(),
20977                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20978        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20979        if (DEBUG_SETTINGS) {
20980            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20981        }
20982
20983        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20984
20985        synchronized (mPackages) {
20986            // Verify that all of the preferred activity components actually
20987            // exist.  It is possible for applications to be updated and at
20988            // that point remove a previously declared activity component that
20989            // had been set as a preferred activity.  We try to clean this up
20990            // the next time we encounter that preferred activity, but it is
20991            // possible for the user flow to never be able to return to that
20992            // situation so here we do a sanity check to make sure we haven't
20993            // left any junk around.
20994            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20995            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20996                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20997                removed.clear();
20998                for (PreferredActivity pa : pir.filterSet()) {
20999                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21000                        removed.add(pa);
21001                    }
21002                }
21003                if (removed.size() > 0) {
21004                    for (int r=0; r<removed.size(); r++) {
21005                        PreferredActivity pa = removed.get(r);
21006                        Slog.w(TAG, "Removing dangling preferred activity: "
21007                                + pa.mPref.mComponent);
21008                        pir.removeFilter(pa);
21009                    }
21010                    mSettings.writePackageRestrictionsLPr(
21011                            mSettings.mPreferredActivities.keyAt(i));
21012                }
21013            }
21014
21015            for (int userId : UserManagerService.getInstance().getUserIds()) {
21016                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21017                    grantPermissionsUserIds = ArrayUtils.appendInt(
21018                            grantPermissionsUserIds, userId);
21019                }
21020            }
21021        }
21022        sUserManager.systemReady();
21023
21024        // If we upgraded grant all default permissions before kicking off.
21025        for (int userId : grantPermissionsUserIds) {
21026            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21027        }
21028
21029        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21030            // If we did not grant default permissions, we preload from this the
21031            // default permission exceptions lazily to ensure we don't hit the
21032            // disk on a new user creation.
21033            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21034        }
21035
21036        // Now that we've scanned all packages, and granted any default
21037        // permissions, ensure permissions are updated. Beware of dragons if you
21038        // try optimizing this.
21039        synchronized (mPackages) {
21040            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21041                    UPDATE_PERMISSIONS_ALL);
21042        }
21043
21044        // Kick off any messages waiting for system ready
21045        if (mPostSystemReadyMessages != null) {
21046            for (Message msg : mPostSystemReadyMessages) {
21047                msg.sendToTarget();
21048            }
21049            mPostSystemReadyMessages = null;
21050        }
21051
21052        // Watch for external volumes that come and go over time
21053        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21054        storage.registerListener(mStorageListener);
21055
21056        mInstallerService.systemReady();
21057        mPackageDexOptimizer.systemReady();
21058
21059        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21060                StorageManagerInternal.class);
21061        StorageManagerInternal.addExternalStoragePolicy(
21062                new StorageManagerInternal.ExternalStorageMountPolicy() {
21063            @Override
21064            public int getMountMode(int uid, String packageName) {
21065                if (Process.isIsolated(uid)) {
21066                    return Zygote.MOUNT_EXTERNAL_NONE;
21067                }
21068                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21069                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21070                }
21071                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21072                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21073                }
21074                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21075                    return Zygote.MOUNT_EXTERNAL_READ;
21076                }
21077                return Zygote.MOUNT_EXTERNAL_WRITE;
21078            }
21079
21080            @Override
21081            public boolean hasExternalStorage(int uid, String packageName) {
21082                return true;
21083            }
21084        });
21085
21086        // Now that we're mostly running, clean up stale users and apps
21087        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21088        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21089
21090        if (mPrivappPermissionsViolations != null) {
21091            throw new IllegalStateException("Signature|privileged permissions not in "
21092                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21093        }
21094    }
21095
21096    public void waitForAppDataPrepared() {
21097        if (mPrepareAppDataFuture == null) {
21098            return;
21099        }
21100        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21101        mPrepareAppDataFuture = null;
21102    }
21103
21104    @Override
21105    public boolean isSafeMode() {
21106        // allow instant applications
21107        return mSafeMode;
21108    }
21109
21110    @Override
21111    public boolean hasSystemUidErrors() {
21112        // allow instant applications
21113        return mHasSystemUidErrors;
21114    }
21115
21116    static String arrayToString(int[] array) {
21117        StringBuffer buf = new StringBuffer(128);
21118        buf.append('[');
21119        if (array != null) {
21120            for (int i=0; i<array.length; i++) {
21121                if (i > 0) buf.append(", ");
21122                buf.append(array[i]);
21123            }
21124        }
21125        buf.append(']');
21126        return buf.toString();
21127    }
21128
21129    @Override
21130    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21131            FileDescriptor err, String[] args, ShellCallback callback,
21132            ResultReceiver resultReceiver) {
21133        (new PackageManagerShellCommand(this)).exec(
21134                this, in, out, err, args, callback, resultReceiver);
21135    }
21136
21137    @Override
21138    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21139        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21140
21141        DumpState dumpState = new DumpState();
21142        boolean fullPreferred = false;
21143        boolean checkin = false;
21144
21145        String packageName = null;
21146        ArraySet<String> permissionNames = null;
21147
21148        int opti = 0;
21149        while (opti < args.length) {
21150            String opt = args[opti];
21151            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21152                break;
21153            }
21154            opti++;
21155
21156            if ("-a".equals(opt)) {
21157                // Right now we only know how to print all.
21158            } else if ("-h".equals(opt)) {
21159                pw.println("Package manager dump options:");
21160                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21161                pw.println("    --checkin: dump for a checkin");
21162                pw.println("    -f: print details of intent filters");
21163                pw.println("    -h: print this help");
21164                pw.println("  cmd may be one of:");
21165                pw.println("    l[ibraries]: list known shared libraries");
21166                pw.println("    f[eatures]: list device features");
21167                pw.println("    k[eysets]: print known keysets");
21168                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21169                pw.println("    perm[issions]: dump permissions");
21170                pw.println("    permission [name ...]: dump declaration and use of given permission");
21171                pw.println("    pref[erred]: print preferred package settings");
21172                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21173                pw.println("    prov[iders]: dump content providers");
21174                pw.println("    p[ackages]: dump installed packages");
21175                pw.println("    s[hared-users]: dump shared user IDs");
21176                pw.println("    m[essages]: print collected runtime messages");
21177                pw.println("    v[erifiers]: print package verifier info");
21178                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21179                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21180                pw.println("    version: print database version info");
21181                pw.println("    write: write current settings now");
21182                pw.println("    installs: details about install sessions");
21183                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21184                pw.println("    dexopt: dump dexopt state");
21185                pw.println("    compiler-stats: dump compiler statistics");
21186                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21187                pw.println("    <package.name>: info about given package");
21188                return;
21189            } else if ("--checkin".equals(opt)) {
21190                checkin = true;
21191            } else if ("-f".equals(opt)) {
21192                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21193            } else if ("--proto".equals(opt)) {
21194                dumpProto(fd);
21195                return;
21196            } else {
21197                pw.println("Unknown argument: " + opt + "; use -h for help");
21198            }
21199        }
21200
21201        // Is the caller requesting to dump a particular piece of data?
21202        if (opti < args.length) {
21203            String cmd = args[opti];
21204            opti++;
21205            // Is this a package name?
21206            if ("android".equals(cmd) || cmd.contains(".")) {
21207                packageName = cmd;
21208                // When dumping a single package, we always dump all of its
21209                // filter information since the amount of data will be reasonable.
21210                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21211            } else if ("check-permission".equals(cmd)) {
21212                if (opti >= args.length) {
21213                    pw.println("Error: check-permission missing permission argument");
21214                    return;
21215                }
21216                String perm = args[opti];
21217                opti++;
21218                if (opti >= args.length) {
21219                    pw.println("Error: check-permission missing package argument");
21220                    return;
21221                }
21222
21223                String pkg = args[opti];
21224                opti++;
21225                int user = UserHandle.getUserId(Binder.getCallingUid());
21226                if (opti < args.length) {
21227                    try {
21228                        user = Integer.parseInt(args[opti]);
21229                    } catch (NumberFormatException e) {
21230                        pw.println("Error: check-permission user argument is not a number: "
21231                                + args[opti]);
21232                        return;
21233                    }
21234                }
21235
21236                // Normalize package name to handle renamed packages and static libs
21237                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21238
21239                pw.println(checkPermission(perm, pkg, user));
21240                return;
21241            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21242                dumpState.setDump(DumpState.DUMP_LIBS);
21243            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21244                dumpState.setDump(DumpState.DUMP_FEATURES);
21245            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21246                if (opti >= args.length) {
21247                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21248                            | DumpState.DUMP_SERVICE_RESOLVERS
21249                            | DumpState.DUMP_RECEIVER_RESOLVERS
21250                            | DumpState.DUMP_CONTENT_RESOLVERS);
21251                } else {
21252                    while (opti < args.length) {
21253                        String name = args[opti];
21254                        if ("a".equals(name) || "activity".equals(name)) {
21255                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21256                        } else if ("s".equals(name) || "service".equals(name)) {
21257                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21258                        } else if ("r".equals(name) || "receiver".equals(name)) {
21259                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21260                        } else if ("c".equals(name) || "content".equals(name)) {
21261                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21262                        } else {
21263                            pw.println("Error: unknown resolver table type: " + name);
21264                            return;
21265                        }
21266                        opti++;
21267                    }
21268                }
21269            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21270                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21271            } else if ("permission".equals(cmd)) {
21272                if (opti >= args.length) {
21273                    pw.println("Error: permission requires permission name");
21274                    return;
21275                }
21276                permissionNames = new ArraySet<>();
21277                while (opti < args.length) {
21278                    permissionNames.add(args[opti]);
21279                    opti++;
21280                }
21281                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21282                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21283            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21284                dumpState.setDump(DumpState.DUMP_PREFERRED);
21285            } else if ("preferred-xml".equals(cmd)) {
21286                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21287                if (opti < args.length && "--full".equals(args[opti])) {
21288                    fullPreferred = true;
21289                    opti++;
21290                }
21291            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21292                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21293            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21294                dumpState.setDump(DumpState.DUMP_PACKAGES);
21295            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21296                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21297            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21298                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21299            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21300                dumpState.setDump(DumpState.DUMP_MESSAGES);
21301            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21302                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21303            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21304                    || "intent-filter-verifiers".equals(cmd)) {
21305                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21306            } else if ("version".equals(cmd)) {
21307                dumpState.setDump(DumpState.DUMP_VERSION);
21308            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21309                dumpState.setDump(DumpState.DUMP_KEYSETS);
21310            } else if ("installs".equals(cmd)) {
21311                dumpState.setDump(DumpState.DUMP_INSTALLS);
21312            } else if ("frozen".equals(cmd)) {
21313                dumpState.setDump(DumpState.DUMP_FROZEN);
21314            } else if ("volumes".equals(cmd)) {
21315                dumpState.setDump(DumpState.DUMP_VOLUMES);
21316            } else if ("dexopt".equals(cmd)) {
21317                dumpState.setDump(DumpState.DUMP_DEXOPT);
21318            } else if ("compiler-stats".equals(cmd)) {
21319                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21320            } else if ("changes".equals(cmd)) {
21321                dumpState.setDump(DumpState.DUMP_CHANGES);
21322            } else if ("write".equals(cmd)) {
21323                synchronized (mPackages) {
21324                    mSettings.writeLPr();
21325                    pw.println("Settings written.");
21326                    return;
21327                }
21328            }
21329        }
21330
21331        if (checkin) {
21332            pw.println("vers,1");
21333        }
21334
21335        // reader
21336        synchronized (mPackages) {
21337            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21338                if (!checkin) {
21339                    if (dumpState.onTitlePrinted())
21340                        pw.println();
21341                    pw.println("Database versions:");
21342                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21343                }
21344            }
21345
21346            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21347                if (!checkin) {
21348                    if (dumpState.onTitlePrinted())
21349                        pw.println();
21350                    pw.println("Verifiers:");
21351                    pw.print("  Required: ");
21352                    pw.print(mRequiredVerifierPackage);
21353                    pw.print(" (uid=");
21354                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21355                            UserHandle.USER_SYSTEM));
21356                    pw.println(")");
21357                } else if (mRequiredVerifierPackage != null) {
21358                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21359                    pw.print(",");
21360                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21361                            UserHandle.USER_SYSTEM));
21362                }
21363            }
21364
21365            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21366                    packageName == null) {
21367                if (mIntentFilterVerifierComponent != null) {
21368                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21369                    if (!checkin) {
21370                        if (dumpState.onTitlePrinted())
21371                            pw.println();
21372                        pw.println("Intent Filter Verifier:");
21373                        pw.print("  Using: ");
21374                        pw.print(verifierPackageName);
21375                        pw.print(" (uid=");
21376                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21377                                UserHandle.USER_SYSTEM));
21378                        pw.println(")");
21379                    } else if (verifierPackageName != null) {
21380                        pw.print("ifv,"); pw.print(verifierPackageName);
21381                        pw.print(",");
21382                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21383                                UserHandle.USER_SYSTEM));
21384                    }
21385                } else {
21386                    pw.println();
21387                    pw.println("No Intent Filter Verifier available!");
21388                }
21389            }
21390
21391            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21392                boolean printedHeader = false;
21393                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21394                while (it.hasNext()) {
21395                    String libName = it.next();
21396                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21397                    if (versionedLib == null) {
21398                        continue;
21399                    }
21400                    final int versionCount = versionedLib.size();
21401                    for (int i = 0; i < versionCount; i++) {
21402                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21403                        if (!checkin) {
21404                            if (!printedHeader) {
21405                                if (dumpState.onTitlePrinted())
21406                                    pw.println();
21407                                pw.println("Libraries:");
21408                                printedHeader = true;
21409                            }
21410                            pw.print("  ");
21411                        } else {
21412                            pw.print("lib,");
21413                        }
21414                        pw.print(libEntry.info.getName());
21415                        if (libEntry.info.isStatic()) {
21416                            pw.print(" version=" + libEntry.info.getVersion());
21417                        }
21418                        if (!checkin) {
21419                            pw.print(" -> ");
21420                        }
21421                        if (libEntry.path != null) {
21422                            pw.print(" (jar) ");
21423                            pw.print(libEntry.path);
21424                        } else {
21425                            pw.print(" (apk) ");
21426                            pw.print(libEntry.apk);
21427                        }
21428                        pw.println();
21429                    }
21430                }
21431            }
21432
21433            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21434                if (dumpState.onTitlePrinted())
21435                    pw.println();
21436                if (!checkin) {
21437                    pw.println("Features:");
21438                }
21439
21440                synchronized (mAvailableFeatures) {
21441                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21442                        if (checkin) {
21443                            pw.print("feat,");
21444                            pw.print(feat.name);
21445                            pw.print(",");
21446                            pw.println(feat.version);
21447                        } else {
21448                            pw.print("  ");
21449                            pw.print(feat.name);
21450                            if (feat.version > 0) {
21451                                pw.print(" version=");
21452                                pw.print(feat.version);
21453                            }
21454                            pw.println();
21455                        }
21456                    }
21457                }
21458            }
21459
21460            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21461                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21462                        : "Activity Resolver Table:", "  ", packageName,
21463                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21464                    dumpState.setTitlePrinted(true);
21465                }
21466            }
21467            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21468                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21469                        : "Receiver Resolver Table:", "  ", packageName,
21470                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21471                    dumpState.setTitlePrinted(true);
21472                }
21473            }
21474            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21475                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21476                        : "Service Resolver Table:", "  ", packageName,
21477                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21478                    dumpState.setTitlePrinted(true);
21479                }
21480            }
21481            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21482                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21483                        : "Provider Resolver Table:", "  ", packageName,
21484                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21485                    dumpState.setTitlePrinted(true);
21486                }
21487            }
21488
21489            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21490                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21491                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21492                    int user = mSettings.mPreferredActivities.keyAt(i);
21493                    if (pir.dump(pw,
21494                            dumpState.getTitlePrinted()
21495                                ? "\nPreferred Activities User " + user + ":"
21496                                : "Preferred Activities User " + user + ":", "  ",
21497                            packageName, true, false)) {
21498                        dumpState.setTitlePrinted(true);
21499                    }
21500                }
21501            }
21502
21503            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21504                pw.flush();
21505                FileOutputStream fout = new FileOutputStream(fd);
21506                BufferedOutputStream str = new BufferedOutputStream(fout);
21507                XmlSerializer serializer = new FastXmlSerializer();
21508                try {
21509                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21510                    serializer.startDocument(null, true);
21511                    serializer.setFeature(
21512                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21513                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21514                    serializer.endDocument();
21515                    serializer.flush();
21516                } catch (IllegalArgumentException e) {
21517                    pw.println("Failed writing: " + e);
21518                } catch (IllegalStateException e) {
21519                    pw.println("Failed writing: " + e);
21520                } catch (IOException e) {
21521                    pw.println("Failed writing: " + e);
21522                }
21523            }
21524
21525            if (!checkin
21526                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21527                    && packageName == null) {
21528                pw.println();
21529                int count = mSettings.mPackages.size();
21530                if (count == 0) {
21531                    pw.println("No applications!");
21532                    pw.println();
21533                } else {
21534                    final String prefix = "  ";
21535                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21536                    if (allPackageSettings.size() == 0) {
21537                        pw.println("No domain preferred apps!");
21538                        pw.println();
21539                    } else {
21540                        pw.println("App verification status:");
21541                        pw.println();
21542                        count = 0;
21543                        for (PackageSetting ps : allPackageSettings) {
21544                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21545                            if (ivi == null || ivi.getPackageName() == null) continue;
21546                            pw.println(prefix + "Package: " + ivi.getPackageName());
21547                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21548                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21549                            pw.println();
21550                            count++;
21551                        }
21552                        if (count == 0) {
21553                            pw.println(prefix + "No app verification established.");
21554                            pw.println();
21555                        }
21556                        for (int userId : sUserManager.getUserIds()) {
21557                            pw.println("App linkages for user " + userId + ":");
21558                            pw.println();
21559                            count = 0;
21560                            for (PackageSetting ps : allPackageSettings) {
21561                                final long status = ps.getDomainVerificationStatusForUser(userId);
21562                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21563                                        && !DEBUG_DOMAIN_VERIFICATION) {
21564                                    continue;
21565                                }
21566                                pw.println(prefix + "Package: " + ps.name);
21567                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21568                                String statusStr = IntentFilterVerificationInfo.
21569                                        getStatusStringFromValue(status);
21570                                pw.println(prefix + "Status:  " + statusStr);
21571                                pw.println();
21572                                count++;
21573                            }
21574                            if (count == 0) {
21575                                pw.println(prefix + "No configured app linkages.");
21576                                pw.println();
21577                            }
21578                        }
21579                    }
21580                }
21581            }
21582
21583            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21584                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21585            }
21586
21587            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21588                boolean printedSomething = false;
21589                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21590                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21591                        continue;
21592                    }
21593                    if (!printedSomething) {
21594                        if (dumpState.onTitlePrinted())
21595                            pw.println();
21596                        pw.println("Registered ContentProviders:");
21597                        printedSomething = true;
21598                    }
21599                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21600                    pw.print("    "); pw.println(p.toString());
21601                }
21602                printedSomething = false;
21603                for (Map.Entry<String, PackageParser.Provider> entry :
21604                        mProvidersByAuthority.entrySet()) {
21605                    PackageParser.Provider p = entry.getValue();
21606                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21607                        continue;
21608                    }
21609                    if (!printedSomething) {
21610                        if (dumpState.onTitlePrinted())
21611                            pw.println();
21612                        pw.println("ContentProvider Authorities:");
21613                        printedSomething = true;
21614                    }
21615                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21616                    pw.print("    "); pw.println(p.toString());
21617                    if (p.info != null && p.info.applicationInfo != null) {
21618                        final String appInfo = p.info.applicationInfo.toString();
21619                        pw.print("      applicationInfo="); pw.println(appInfo);
21620                    }
21621                }
21622            }
21623
21624            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21625                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21626            }
21627
21628            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21629                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21630            }
21631
21632            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21633                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21634            }
21635
21636            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21637                if (dumpState.onTitlePrinted()) pw.println();
21638                pw.println("Package Changes:");
21639                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21640                final int K = mChangedPackages.size();
21641                for (int i = 0; i < K; i++) {
21642                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21643                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21644                    final int N = changes.size();
21645                    if (N == 0) {
21646                        pw.print("    "); pw.println("No packages changed");
21647                    } else {
21648                        for (int j = 0; j < N; j++) {
21649                            final String pkgName = changes.valueAt(j);
21650                            final int sequenceNumber = changes.keyAt(j);
21651                            pw.print("    ");
21652                            pw.print("seq=");
21653                            pw.print(sequenceNumber);
21654                            pw.print(", package=");
21655                            pw.println(pkgName);
21656                        }
21657                    }
21658                }
21659            }
21660
21661            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21662                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21663            }
21664
21665            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21666                // XXX should handle packageName != null by dumping only install data that
21667                // the given package is involved with.
21668                if (dumpState.onTitlePrinted()) pw.println();
21669
21670                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21671                ipw.println();
21672                ipw.println("Frozen packages:");
21673                ipw.increaseIndent();
21674                if (mFrozenPackages.size() == 0) {
21675                    ipw.println("(none)");
21676                } else {
21677                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21678                        ipw.println(mFrozenPackages.valueAt(i));
21679                    }
21680                }
21681                ipw.decreaseIndent();
21682            }
21683
21684            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21685                if (dumpState.onTitlePrinted()) pw.println();
21686
21687                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21688                ipw.println();
21689                ipw.println("Loaded volumes:");
21690                ipw.increaseIndent();
21691                if (mLoadedVolumes.size() == 0) {
21692                    ipw.println("(none)");
21693                } else {
21694                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21695                        ipw.println(mLoadedVolumes.valueAt(i));
21696                    }
21697                }
21698                ipw.decreaseIndent();
21699            }
21700
21701            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21702                if (dumpState.onTitlePrinted()) pw.println();
21703                dumpDexoptStateLPr(pw, packageName);
21704            }
21705
21706            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21707                if (dumpState.onTitlePrinted()) pw.println();
21708                dumpCompilerStatsLPr(pw, packageName);
21709            }
21710
21711            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21712                if (dumpState.onTitlePrinted()) pw.println();
21713                mSettings.dumpReadMessagesLPr(pw, dumpState);
21714
21715                pw.println();
21716                pw.println("Package warning messages:");
21717                BufferedReader in = null;
21718                String line = null;
21719                try {
21720                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21721                    while ((line = in.readLine()) != null) {
21722                        if (line.contains("ignored: updated version")) continue;
21723                        pw.println(line);
21724                    }
21725                } catch (IOException ignored) {
21726                } finally {
21727                    IoUtils.closeQuietly(in);
21728                }
21729            }
21730
21731            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21732                BufferedReader in = null;
21733                String line = null;
21734                try {
21735                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21736                    while ((line = in.readLine()) != null) {
21737                        if (line.contains("ignored: updated version")) continue;
21738                        pw.print("msg,");
21739                        pw.println(line);
21740                    }
21741                } catch (IOException ignored) {
21742                } finally {
21743                    IoUtils.closeQuietly(in);
21744                }
21745            }
21746        }
21747
21748        // PackageInstaller should be called outside of mPackages lock
21749        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21750            // XXX should handle packageName != null by dumping only install data that
21751            // the given package is involved with.
21752            if (dumpState.onTitlePrinted()) pw.println();
21753            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21754        }
21755    }
21756
21757    private void dumpProto(FileDescriptor fd) {
21758        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21759
21760        synchronized (mPackages) {
21761            final long requiredVerifierPackageToken =
21762                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21763            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21764            proto.write(
21765                    PackageServiceDumpProto.PackageShortProto.UID,
21766                    getPackageUid(
21767                            mRequiredVerifierPackage,
21768                            MATCH_DEBUG_TRIAGED_MISSING,
21769                            UserHandle.USER_SYSTEM));
21770            proto.end(requiredVerifierPackageToken);
21771
21772            if (mIntentFilterVerifierComponent != null) {
21773                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21774                final long verifierPackageToken =
21775                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21776                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21777                proto.write(
21778                        PackageServiceDumpProto.PackageShortProto.UID,
21779                        getPackageUid(
21780                                verifierPackageName,
21781                                MATCH_DEBUG_TRIAGED_MISSING,
21782                                UserHandle.USER_SYSTEM));
21783                proto.end(verifierPackageToken);
21784            }
21785
21786            dumpSharedLibrariesProto(proto);
21787            dumpFeaturesProto(proto);
21788            mSettings.dumpPackagesProto(proto);
21789            mSettings.dumpSharedUsersProto(proto);
21790            dumpMessagesProto(proto);
21791        }
21792        proto.flush();
21793    }
21794
21795    private void dumpMessagesProto(ProtoOutputStream proto) {
21796        BufferedReader in = null;
21797        String line = null;
21798        try {
21799            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21800            while ((line = in.readLine()) != null) {
21801                if (line.contains("ignored: updated version")) continue;
21802                proto.write(PackageServiceDumpProto.MESSAGES, line);
21803            }
21804        } catch (IOException ignored) {
21805        } finally {
21806            IoUtils.closeQuietly(in);
21807        }
21808    }
21809
21810    private void dumpFeaturesProto(ProtoOutputStream proto) {
21811        synchronized (mAvailableFeatures) {
21812            final int count = mAvailableFeatures.size();
21813            for (int i = 0; i < count; i++) {
21814                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21815            }
21816        }
21817    }
21818
21819    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21820        final int count = mSharedLibraries.size();
21821        for (int i = 0; i < count; i++) {
21822            final String libName = mSharedLibraries.keyAt(i);
21823            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21824            if (versionedLib == null) {
21825                continue;
21826            }
21827            final int versionCount = versionedLib.size();
21828            for (int j = 0; j < versionCount; j++) {
21829                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21830                final long sharedLibraryToken =
21831                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21832                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21833                final boolean isJar = (libEntry.path != null);
21834                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21835                if (isJar) {
21836                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21837                } else {
21838                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21839                }
21840                proto.end(sharedLibraryToken);
21841            }
21842        }
21843    }
21844
21845    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21846        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21847        ipw.println();
21848        ipw.println("Dexopt state:");
21849        ipw.increaseIndent();
21850        Collection<PackageParser.Package> packages = null;
21851        if (packageName != null) {
21852            PackageParser.Package targetPackage = mPackages.get(packageName);
21853            if (targetPackage != null) {
21854                packages = Collections.singletonList(targetPackage);
21855            } else {
21856                ipw.println("Unable to find package: " + packageName);
21857                return;
21858            }
21859        } else {
21860            packages = mPackages.values();
21861        }
21862
21863        for (PackageParser.Package pkg : packages) {
21864            ipw.println("[" + pkg.packageName + "]");
21865            ipw.increaseIndent();
21866            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21867                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21868            ipw.decreaseIndent();
21869        }
21870    }
21871
21872    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21873        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21874        ipw.println();
21875        ipw.println("Compiler stats:");
21876        ipw.increaseIndent();
21877        Collection<PackageParser.Package> packages = null;
21878        if (packageName != null) {
21879            PackageParser.Package targetPackage = mPackages.get(packageName);
21880            if (targetPackage != null) {
21881                packages = Collections.singletonList(targetPackage);
21882            } else {
21883                ipw.println("Unable to find package: " + packageName);
21884                return;
21885            }
21886        } else {
21887            packages = mPackages.values();
21888        }
21889
21890        for (PackageParser.Package pkg : packages) {
21891            ipw.println("[" + pkg.packageName + "]");
21892            ipw.increaseIndent();
21893
21894            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21895            if (stats == null) {
21896                ipw.println("(No recorded stats)");
21897            } else {
21898                stats.dump(ipw);
21899            }
21900            ipw.decreaseIndent();
21901        }
21902    }
21903
21904    private String dumpDomainString(String packageName) {
21905        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21906                .getList();
21907        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21908
21909        ArraySet<String> result = new ArraySet<>();
21910        if (iviList.size() > 0) {
21911            for (IntentFilterVerificationInfo ivi : iviList) {
21912                for (String host : ivi.getDomains()) {
21913                    result.add(host);
21914                }
21915            }
21916        }
21917        if (filters != null && filters.size() > 0) {
21918            for (IntentFilter filter : filters) {
21919                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21920                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21921                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21922                    result.addAll(filter.getHostsList());
21923                }
21924            }
21925        }
21926
21927        StringBuilder sb = new StringBuilder(result.size() * 16);
21928        for (String domain : result) {
21929            if (sb.length() > 0) sb.append(" ");
21930            sb.append(domain);
21931        }
21932        return sb.toString();
21933    }
21934
21935    // ------- apps on sdcard specific code -------
21936    static final boolean DEBUG_SD_INSTALL = false;
21937
21938    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21939
21940    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21941
21942    private boolean mMediaMounted = false;
21943
21944    static String getEncryptKey() {
21945        try {
21946            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21947                    SD_ENCRYPTION_KEYSTORE_NAME);
21948            if (sdEncKey == null) {
21949                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21950                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21951                if (sdEncKey == null) {
21952                    Slog.e(TAG, "Failed to create encryption keys");
21953                    return null;
21954                }
21955            }
21956            return sdEncKey;
21957        } catch (NoSuchAlgorithmException nsae) {
21958            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21959            return null;
21960        } catch (IOException ioe) {
21961            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21962            return null;
21963        }
21964    }
21965
21966    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21967            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21968        final int size = infos.size();
21969        final String[] packageNames = new String[size];
21970        final int[] packageUids = new int[size];
21971        for (int i = 0; i < size; i++) {
21972            final ApplicationInfo info = infos.get(i);
21973            packageNames[i] = info.packageName;
21974            packageUids[i] = info.uid;
21975        }
21976        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21977                finishedReceiver);
21978    }
21979
21980    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21981            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21982        sendResourcesChangedBroadcast(mediaStatus, replacing,
21983                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21984    }
21985
21986    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21987            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21988        int size = pkgList.length;
21989        if (size > 0) {
21990            // Send broadcasts here
21991            Bundle extras = new Bundle();
21992            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21993            if (uidArr != null) {
21994                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21995            }
21996            if (replacing) {
21997                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21998            }
21999            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22000                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22001            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22002        }
22003    }
22004
22005    private void loadPrivatePackages(final VolumeInfo vol) {
22006        mHandler.post(new Runnable() {
22007            @Override
22008            public void run() {
22009                loadPrivatePackagesInner(vol);
22010            }
22011        });
22012    }
22013
22014    private void loadPrivatePackagesInner(VolumeInfo vol) {
22015        final String volumeUuid = vol.fsUuid;
22016        if (TextUtils.isEmpty(volumeUuid)) {
22017            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22018            return;
22019        }
22020
22021        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22022        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22023        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22024
22025        final VersionInfo ver;
22026        final List<PackageSetting> packages;
22027        synchronized (mPackages) {
22028            ver = mSettings.findOrCreateVersion(volumeUuid);
22029            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22030        }
22031
22032        for (PackageSetting ps : packages) {
22033            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22034            synchronized (mInstallLock) {
22035                final PackageParser.Package pkg;
22036                try {
22037                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22038                    loaded.add(pkg.applicationInfo);
22039
22040                } catch (PackageManagerException e) {
22041                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22042                }
22043
22044                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22045                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22046                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22047                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22048                }
22049            }
22050        }
22051
22052        // Reconcile app data for all started/unlocked users
22053        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22054        final UserManager um = mContext.getSystemService(UserManager.class);
22055        UserManagerInternal umInternal = getUserManagerInternal();
22056        for (UserInfo user : um.getUsers()) {
22057            final int flags;
22058            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22059                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22060            } else if (umInternal.isUserRunning(user.id)) {
22061                flags = StorageManager.FLAG_STORAGE_DE;
22062            } else {
22063                continue;
22064            }
22065
22066            try {
22067                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22068                synchronized (mInstallLock) {
22069                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22070                }
22071            } catch (IllegalStateException e) {
22072                // Device was probably ejected, and we'll process that event momentarily
22073                Slog.w(TAG, "Failed to prepare storage: " + e);
22074            }
22075        }
22076
22077        synchronized (mPackages) {
22078            int updateFlags = UPDATE_PERMISSIONS_ALL;
22079            if (ver.sdkVersion != mSdkVersion) {
22080                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22081                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22082                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22083            }
22084            updatePermissionsLocked(null, null, volumeUuid, updateFlags);
22085
22086            // Yay, everything is now upgraded
22087            ver.forceCurrent();
22088
22089            mSettings.writeLPr();
22090        }
22091
22092        for (PackageFreezer freezer : freezers) {
22093            freezer.close();
22094        }
22095
22096        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22097        sendResourcesChangedBroadcast(true, false, loaded, null);
22098        mLoadedVolumes.add(vol.getId());
22099    }
22100
22101    private void unloadPrivatePackages(final VolumeInfo vol) {
22102        mHandler.post(new Runnable() {
22103            @Override
22104            public void run() {
22105                unloadPrivatePackagesInner(vol);
22106            }
22107        });
22108    }
22109
22110    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22111        final String volumeUuid = vol.fsUuid;
22112        if (TextUtils.isEmpty(volumeUuid)) {
22113            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22114            return;
22115        }
22116
22117        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22118        synchronized (mInstallLock) {
22119        synchronized (mPackages) {
22120            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22121            for (PackageSetting ps : packages) {
22122                if (ps.pkg == null) continue;
22123
22124                final ApplicationInfo info = ps.pkg.applicationInfo;
22125                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22126                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22127
22128                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22129                        "unloadPrivatePackagesInner")) {
22130                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22131                            false, null)) {
22132                        unloaded.add(info);
22133                    } else {
22134                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22135                    }
22136                }
22137
22138                // Try very hard to release any references to this package
22139                // so we don't risk the system server being killed due to
22140                // open FDs
22141                AttributeCache.instance().removePackage(ps.name);
22142            }
22143
22144            mSettings.writeLPr();
22145        }
22146        }
22147
22148        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22149        sendResourcesChangedBroadcast(false, false, unloaded, null);
22150        mLoadedVolumes.remove(vol.getId());
22151
22152        // Try very hard to release any references to this path so we don't risk
22153        // the system server being killed due to open FDs
22154        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22155
22156        for (int i = 0; i < 3; i++) {
22157            System.gc();
22158            System.runFinalization();
22159        }
22160    }
22161
22162    private void assertPackageKnown(String volumeUuid, String packageName)
22163            throws PackageManagerException {
22164        synchronized (mPackages) {
22165            // Normalize package name to handle renamed packages
22166            packageName = normalizePackageNameLPr(packageName);
22167
22168            final PackageSetting ps = mSettings.mPackages.get(packageName);
22169            if (ps == null) {
22170                throw new PackageManagerException("Package " + packageName + " is unknown");
22171            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22172                throw new PackageManagerException(
22173                        "Package " + packageName + " found on unknown volume " + volumeUuid
22174                                + "; expected volume " + ps.volumeUuid);
22175            }
22176        }
22177    }
22178
22179    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22180            throws PackageManagerException {
22181        synchronized (mPackages) {
22182            // Normalize package name to handle renamed packages
22183            packageName = normalizePackageNameLPr(packageName);
22184
22185            final PackageSetting ps = mSettings.mPackages.get(packageName);
22186            if (ps == null) {
22187                throw new PackageManagerException("Package " + packageName + " is unknown");
22188            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22189                throw new PackageManagerException(
22190                        "Package " + packageName + " found on unknown volume " + volumeUuid
22191                                + "; expected volume " + ps.volumeUuid);
22192            } else if (!ps.getInstalled(userId)) {
22193                throw new PackageManagerException(
22194                        "Package " + packageName + " not installed for user " + userId);
22195            }
22196        }
22197    }
22198
22199    private List<String> collectAbsoluteCodePaths() {
22200        synchronized (mPackages) {
22201            List<String> codePaths = new ArrayList<>();
22202            final int packageCount = mSettings.mPackages.size();
22203            for (int i = 0; i < packageCount; i++) {
22204                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22205                codePaths.add(ps.codePath.getAbsolutePath());
22206            }
22207            return codePaths;
22208        }
22209    }
22210
22211    /**
22212     * Examine all apps present on given mounted volume, and destroy apps that
22213     * aren't expected, either due to uninstallation or reinstallation on
22214     * another volume.
22215     */
22216    private void reconcileApps(String volumeUuid) {
22217        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22218        List<File> filesToDelete = null;
22219
22220        final File[] files = FileUtils.listFilesOrEmpty(
22221                Environment.getDataAppDirectory(volumeUuid));
22222        for (File file : files) {
22223            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22224                    && !PackageInstallerService.isStageName(file.getName());
22225            if (!isPackage) {
22226                // Ignore entries which are not packages
22227                continue;
22228            }
22229
22230            String absolutePath = file.getAbsolutePath();
22231
22232            boolean pathValid = false;
22233            final int absoluteCodePathCount = absoluteCodePaths.size();
22234            for (int i = 0; i < absoluteCodePathCount; i++) {
22235                String absoluteCodePath = absoluteCodePaths.get(i);
22236                if (absolutePath.startsWith(absoluteCodePath)) {
22237                    pathValid = true;
22238                    break;
22239                }
22240            }
22241
22242            if (!pathValid) {
22243                if (filesToDelete == null) {
22244                    filesToDelete = new ArrayList<>();
22245                }
22246                filesToDelete.add(file);
22247            }
22248        }
22249
22250        if (filesToDelete != null) {
22251            final int fileToDeleteCount = filesToDelete.size();
22252            for (int i = 0; i < fileToDeleteCount; i++) {
22253                File fileToDelete = filesToDelete.get(i);
22254                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22255                synchronized (mInstallLock) {
22256                    removeCodePathLI(fileToDelete);
22257                }
22258            }
22259        }
22260    }
22261
22262    /**
22263     * Reconcile all app data for the given user.
22264     * <p>
22265     * Verifies that directories exist and that ownership and labeling is
22266     * correct for all installed apps on all mounted volumes.
22267     */
22268    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22269        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22270        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22271            final String volumeUuid = vol.getFsUuid();
22272            synchronized (mInstallLock) {
22273                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22274            }
22275        }
22276    }
22277
22278    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22279            boolean migrateAppData) {
22280        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22281    }
22282
22283    /**
22284     * Reconcile all app data on given mounted volume.
22285     * <p>
22286     * Destroys app data that isn't expected, either due to uninstallation or
22287     * reinstallation on another volume.
22288     * <p>
22289     * Verifies that directories exist and that ownership and labeling is
22290     * correct for all installed apps.
22291     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22292     */
22293    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22294            boolean migrateAppData, boolean onlyCoreApps) {
22295        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22296                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22297        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22298
22299        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22300        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22301
22302        // First look for stale data that doesn't belong, and check if things
22303        // have changed since we did our last restorecon
22304        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22305            if (StorageManager.isFileEncryptedNativeOrEmulated()
22306                    && !StorageManager.isUserKeyUnlocked(userId)) {
22307                throw new RuntimeException(
22308                        "Yikes, someone asked us to reconcile CE storage while " + userId
22309                                + " was still locked; this would have caused massive data loss!");
22310            }
22311
22312            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22313            for (File file : files) {
22314                final String packageName = file.getName();
22315                try {
22316                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22317                } catch (PackageManagerException e) {
22318                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22319                    try {
22320                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22321                                StorageManager.FLAG_STORAGE_CE, 0);
22322                    } catch (InstallerException e2) {
22323                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22324                    }
22325                }
22326            }
22327        }
22328        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22329            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22330            for (File file : files) {
22331                final String packageName = file.getName();
22332                try {
22333                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22334                } catch (PackageManagerException e) {
22335                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22336                    try {
22337                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22338                                StorageManager.FLAG_STORAGE_DE, 0);
22339                    } catch (InstallerException e2) {
22340                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22341                    }
22342                }
22343            }
22344        }
22345
22346        // Ensure that data directories are ready to roll for all packages
22347        // installed for this volume and user
22348        final List<PackageSetting> packages;
22349        synchronized (mPackages) {
22350            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22351        }
22352        int preparedCount = 0;
22353        for (PackageSetting ps : packages) {
22354            final String packageName = ps.name;
22355            if (ps.pkg == null) {
22356                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22357                // TODO: might be due to legacy ASEC apps; we should circle back
22358                // and reconcile again once they're scanned
22359                continue;
22360            }
22361            // Skip non-core apps if requested
22362            if (onlyCoreApps && !ps.pkg.coreApp) {
22363                result.add(packageName);
22364                continue;
22365            }
22366
22367            if (ps.getInstalled(userId)) {
22368                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22369                preparedCount++;
22370            }
22371        }
22372
22373        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22374        return result;
22375    }
22376
22377    /**
22378     * Prepare app data for the given app just after it was installed or
22379     * upgraded. This method carefully only touches users that it's installed
22380     * for, and it forces a restorecon to handle any seinfo changes.
22381     * <p>
22382     * Verifies that directories exist and that ownership and labeling is
22383     * correct for all installed apps. If there is an ownership mismatch, it
22384     * will try recovering system apps by wiping data; third-party app data is
22385     * left intact.
22386     * <p>
22387     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22388     */
22389    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22390        final PackageSetting ps;
22391        synchronized (mPackages) {
22392            ps = mSettings.mPackages.get(pkg.packageName);
22393            mSettings.writeKernelMappingLPr(ps);
22394        }
22395
22396        final UserManager um = mContext.getSystemService(UserManager.class);
22397        UserManagerInternal umInternal = getUserManagerInternal();
22398        for (UserInfo user : um.getUsers()) {
22399            final int flags;
22400            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22401                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22402            } else if (umInternal.isUserRunning(user.id)) {
22403                flags = StorageManager.FLAG_STORAGE_DE;
22404            } else {
22405                continue;
22406            }
22407
22408            if (ps.getInstalled(user.id)) {
22409                // TODO: when user data is locked, mark that we're still dirty
22410                prepareAppDataLIF(pkg, user.id, flags);
22411            }
22412        }
22413    }
22414
22415    /**
22416     * Prepare app data for the given app.
22417     * <p>
22418     * Verifies that directories exist and that ownership and labeling is
22419     * correct for all installed apps. If there is an ownership mismatch, this
22420     * will try recovering system apps by wiping data; third-party app data is
22421     * left intact.
22422     */
22423    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22424        if (pkg == null) {
22425            Slog.wtf(TAG, "Package was null!", new Throwable());
22426            return;
22427        }
22428        prepareAppDataLeafLIF(pkg, userId, flags);
22429        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22430        for (int i = 0; i < childCount; i++) {
22431            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22432        }
22433    }
22434
22435    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22436            boolean maybeMigrateAppData) {
22437        prepareAppDataLIF(pkg, userId, flags);
22438
22439        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22440            // We may have just shuffled around app data directories, so
22441            // prepare them one more time
22442            prepareAppDataLIF(pkg, userId, flags);
22443        }
22444    }
22445
22446    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22447        if (DEBUG_APP_DATA) {
22448            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22449                    + Integer.toHexString(flags));
22450        }
22451
22452        final String volumeUuid = pkg.volumeUuid;
22453        final String packageName = pkg.packageName;
22454        final ApplicationInfo app = pkg.applicationInfo;
22455        final int appId = UserHandle.getAppId(app.uid);
22456
22457        Preconditions.checkNotNull(app.seInfo);
22458
22459        long ceDataInode = -1;
22460        try {
22461            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22462                    appId, app.seInfo, app.targetSdkVersion);
22463        } catch (InstallerException e) {
22464            if (app.isSystemApp()) {
22465                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22466                        + ", but trying to recover: " + e);
22467                destroyAppDataLeafLIF(pkg, userId, flags);
22468                try {
22469                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22470                            appId, app.seInfo, app.targetSdkVersion);
22471                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22472                } catch (InstallerException e2) {
22473                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22474                }
22475            } else {
22476                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22477            }
22478        }
22479
22480        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22481            // TODO: mark this structure as dirty so we persist it!
22482            synchronized (mPackages) {
22483                final PackageSetting ps = mSettings.mPackages.get(packageName);
22484                if (ps != null) {
22485                    ps.setCeDataInode(ceDataInode, userId);
22486                }
22487            }
22488        }
22489
22490        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22491    }
22492
22493    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22494        if (pkg == null) {
22495            Slog.wtf(TAG, "Package was null!", new Throwable());
22496            return;
22497        }
22498        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22499        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22500        for (int i = 0; i < childCount; i++) {
22501            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22502        }
22503    }
22504
22505    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22506        final String volumeUuid = pkg.volumeUuid;
22507        final String packageName = pkg.packageName;
22508        final ApplicationInfo app = pkg.applicationInfo;
22509
22510        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22511            // Create a native library symlink only if we have native libraries
22512            // and if the native libraries are 32 bit libraries. We do not provide
22513            // this symlink for 64 bit libraries.
22514            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22515                final String nativeLibPath = app.nativeLibraryDir;
22516                try {
22517                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22518                            nativeLibPath, userId);
22519                } catch (InstallerException e) {
22520                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22521                }
22522            }
22523        }
22524    }
22525
22526    /**
22527     * For system apps on non-FBE devices, this method migrates any existing
22528     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22529     * requested by the app.
22530     */
22531    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22532        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22533                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22534            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22535                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22536            try {
22537                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22538                        storageTarget);
22539            } catch (InstallerException e) {
22540                logCriticalInfo(Log.WARN,
22541                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22542            }
22543            return true;
22544        } else {
22545            return false;
22546        }
22547    }
22548
22549    public PackageFreezer freezePackage(String packageName, String killReason) {
22550        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22551    }
22552
22553    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22554        return new PackageFreezer(packageName, userId, killReason);
22555    }
22556
22557    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22558            String killReason) {
22559        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22560    }
22561
22562    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22563            String killReason) {
22564        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22565            return new PackageFreezer();
22566        } else {
22567            return freezePackage(packageName, userId, killReason);
22568        }
22569    }
22570
22571    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22572            String killReason) {
22573        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22574    }
22575
22576    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22577            String killReason) {
22578        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22579            return new PackageFreezer();
22580        } else {
22581            return freezePackage(packageName, userId, killReason);
22582        }
22583    }
22584
22585    /**
22586     * Class that freezes and kills the given package upon creation, and
22587     * unfreezes it upon closing. This is typically used when doing surgery on
22588     * app code/data to prevent the app from running while you're working.
22589     */
22590    private class PackageFreezer implements AutoCloseable {
22591        private final String mPackageName;
22592        private final PackageFreezer[] mChildren;
22593
22594        private final boolean mWeFroze;
22595
22596        private final AtomicBoolean mClosed = new AtomicBoolean();
22597        private final CloseGuard mCloseGuard = CloseGuard.get();
22598
22599        /**
22600         * Create and return a stub freezer that doesn't actually do anything,
22601         * typically used when someone requested
22602         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22603         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22604         */
22605        public PackageFreezer() {
22606            mPackageName = null;
22607            mChildren = null;
22608            mWeFroze = false;
22609            mCloseGuard.open("close");
22610        }
22611
22612        public PackageFreezer(String packageName, int userId, String killReason) {
22613            synchronized (mPackages) {
22614                mPackageName = packageName;
22615                mWeFroze = mFrozenPackages.add(mPackageName);
22616
22617                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22618                if (ps != null) {
22619                    killApplication(ps.name, ps.appId, userId, killReason);
22620                }
22621
22622                final PackageParser.Package p = mPackages.get(packageName);
22623                if (p != null && p.childPackages != null) {
22624                    final int N = p.childPackages.size();
22625                    mChildren = new PackageFreezer[N];
22626                    for (int i = 0; i < N; i++) {
22627                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22628                                userId, killReason);
22629                    }
22630                } else {
22631                    mChildren = null;
22632                }
22633            }
22634            mCloseGuard.open("close");
22635        }
22636
22637        @Override
22638        protected void finalize() throws Throwable {
22639            try {
22640                if (mCloseGuard != null) {
22641                    mCloseGuard.warnIfOpen();
22642                }
22643
22644                close();
22645            } finally {
22646                super.finalize();
22647            }
22648        }
22649
22650        @Override
22651        public void close() {
22652            mCloseGuard.close();
22653            if (mClosed.compareAndSet(false, true)) {
22654                synchronized (mPackages) {
22655                    if (mWeFroze) {
22656                        mFrozenPackages.remove(mPackageName);
22657                    }
22658
22659                    if (mChildren != null) {
22660                        for (PackageFreezer freezer : mChildren) {
22661                            freezer.close();
22662                        }
22663                    }
22664                }
22665            }
22666        }
22667    }
22668
22669    /**
22670     * Verify that given package is currently frozen.
22671     */
22672    private void checkPackageFrozen(String packageName) {
22673        synchronized (mPackages) {
22674            if (!mFrozenPackages.contains(packageName)) {
22675                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22676            }
22677        }
22678    }
22679
22680    @Override
22681    public int movePackage(final String packageName, final String volumeUuid) {
22682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22683
22684        final int callingUid = Binder.getCallingUid();
22685        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22686        final int moveId = mNextMoveId.getAndIncrement();
22687        mHandler.post(new Runnable() {
22688            @Override
22689            public void run() {
22690                try {
22691                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22692                } catch (PackageManagerException e) {
22693                    Slog.w(TAG, "Failed to move " + packageName, e);
22694                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22695                }
22696            }
22697        });
22698        return moveId;
22699    }
22700
22701    private void movePackageInternal(final String packageName, final String volumeUuid,
22702            final int moveId, final int callingUid, UserHandle user)
22703                    throws PackageManagerException {
22704        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22705        final PackageManager pm = mContext.getPackageManager();
22706
22707        final boolean currentAsec;
22708        final String currentVolumeUuid;
22709        final File codeFile;
22710        final String installerPackageName;
22711        final String packageAbiOverride;
22712        final int appId;
22713        final String seinfo;
22714        final String label;
22715        final int targetSdkVersion;
22716        final PackageFreezer freezer;
22717        final int[] installedUserIds;
22718
22719        // reader
22720        synchronized (mPackages) {
22721            final PackageParser.Package pkg = mPackages.get(packageName);
22722            final PackageSetting ps = mSettings.mPackages.get(packageName);
22723            if (pkg == null
22724                    || ps == null
22725                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22726                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22727            }
22728            if (pkg.applicationInfo.isSystemApp()) {
22729                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22730                        "Cannot move system application");
22731            }
22732
22733            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22734            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22735                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22736            if (isInternalStorage && !allow3rdPartyOnInternal) {
22737                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22738                        "3rd party apps are not allowed on internal storage");
22739            }
22740
22741            if (pkg.applicationInfo.isExternalAsec()) {
22742                currentAsec = true;
22743                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22744            } else if (pkg.applicationInfo.isForwardLocked()) {
22745                currentAsec = true;
22746                currentVolumeUuid = "forward_locked";
22747            } else {
22748                currentAsec = false;
22749                currentVolumeUuid = ps.volumeUuid;
22750
22751                final File probe = new File(pkg.codePath);
22752                final File probeOat = new File(probe, "oat");
22753                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22754                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22755                            "Move only supported for modern cluster style installs");
22756                }
22757            }
22758
22759            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22760                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22761                        "Package already moved to " + volumeUuid);
22762            }
22763            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22764                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22765                        "Device admin cannot be moved");
22766            }
22767
22768            if (mFrozenPackages.contains(packageName)) {
22769                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22770                        "Failed to move already frozen package");
22771            }
22772
22773            codeFile = new File(pkg.codePath);
22774            installerPackageName = ps.installerPackageName;
22775            packageAbiOverride = ps.cpuAbiOverrideString;
22776            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22777            seinfo = pkg.applicationInfo.seInfo;
22778            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22779            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22780            freezer = freezePackage(packageName, "movePackageInternal");
22781            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22782        }
22783
22784        final Bundle extras = new Bundle();
22785        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22786        extras.putString(Intent.EXTRA_TITLE, label);
22787        mMoveCallbacks.notifyCreated(moveId, extras);
22788
22789        int installFlags;
22790        final boolean moveCompleteApp;
22791        final File measurePath;
22792
22793        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22794            installFlags = INSTALL_INTERNAL;
22795            moveCompleteApp = !currentAsec;
22796            measurePath = Environment.getDataAppDirectory(volumeUuid);
22797        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22798            installFlags = INSTALL_EXTERNAL;
22799            moveCompleteApp = false;
22800            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22801        } else {
22802            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22803            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22804                    || !volume.isMountedWritable()) {
22805                freezer.close();
22806                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22807                        "Move location not mounted private volume");
22808            }
22809
22810            Preconditions.checkState(!currentAsec);
22811
22812            installFlags = INSTALL_INTERNAL;
22813            moveCompleteApp = true;
22814            measurePath = Environment.getDataAppDirectory(volumeUuid);
22815        }
22816
22817        // If we're moving app data around, we need all the users unlocked
22818        if (moveCompleteApp) {
22819            for (int userId : installedUserIds) {
22820                if (StorageManager.isFileEncryptedNativeOrEmulated()
22821                        && !StorageManager.isUserKeyUnlocked(userId)) {
22822                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22823                            "User " + userId + " must be unlocked");
22824                }
22825            }
22826        }
22827
22828        final PackageStats stats = new PackageStats(null, -1);
22829        synchronized (mInstaller) {
22830            for (int userId : installedUserIds) {
22831                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22832                    freezer.close();
22833                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22834                            "Failed to measure package size");
22835                }
22836            }
22837        }
22838
22839        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22840                + stats.dataSize);
22841
22842        final long startFreeBytes = measurePath.getUsableSpace();
22843        final long sizeBytes;
22844        if (moveCompleteApp) {
22845            sizeBytes = stats.codeSize + stats.dataSize;
22846        } else {
22847            sizeBytes = stats.codeSize;
22848        }
22849
22850        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22851            freezer.close();
22852            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22853                    "Not enough free space to move");
22854        }
22855
22856        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22857
22858        final CountDownLatch installedLatch = new CountDownLatch(1);
22859        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22860            @Override
22861            public void onUserActionRequired(Intent intent) throws RemoteException {
22862                throw new IllegalStateException();
22863            }
22864
22865            @Override
22866            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22867                    Bundle extras) throws RemoteException {
22868                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22869                        + PackageManager.installStatusToString(returnCode, msg));
22870
22871                installedLatch.countDown();
22872                freezer.close();
22873
22874                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22875                switch (status) {
22876                    case PackageInstaller.STATUS_SUCCESS:
22877                        mMoveCallbacks.notifyStatusChanged(moveId,
22878                                PackageManager.MOVE_SUCCEEDED);
22879                        break;
22880                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22881                        mMoveCallbacks.notifyStatusChanged(moveId,
22882                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22883                        break;
22884                    default:
22885                        mMoveCallbacks.notifyStatusChanged(moveId,
22886                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22887                        break;
22888                }
22889            }
22890        };
22891
22892        final MoveInfo move;
22893        if (moveCompleteApp) {
22894            // Kick off a thread to report progress estimates
22895            new Thread() {
22896                @Override
22897                public void run() {
22898                    while (true) {
22899                        try {
22900                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22901                                break;
22902                            }
22903                        } catch (InterruptedException ignored) {
22904                        }
22905
22906                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22907                        final int progress = 10 + (int) MathUtils.constrain(
22908                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22909                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22910                    }
22911                }
22912            }.start();
22913
22914            final String dataAppName = codeFile.getName();
22915            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22916                    dataAppName, appId, seinfo, targetSdkVersion);
22917        } else {
22918            move = null;
22919        }
22920
22921        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22922
22923        final Message msg = mHandler.obtainMessage(INIT_COPY);
22924        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22925        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22926                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22927                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22928                PackageManager.INSTALL_REASON_UNKNOWN);
22929        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22930        msg.obj = params;
22931
22932        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22933                System.identityHashCode(msg.obj));
22934        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22935                System.identityHashCode(msg.obj));
22936
22937        mHandler.sendMessage(msg);
22938    }
22939
22940    @Override
22941    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22942        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22943
22944        final int realMoveId = mNextMoveId.getAndIncrement();
22945        final Bundle extras = new Bundle();
22946        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22947        mMoveCallbacks.notifyCreated(realMoveId, extras);
22948
22949        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22950            @Override
22951            public void onCreated(int moveId, Bundle extras) {
22952                // Ignored
22953            }
22954
22955            @Override
22956            public void onStatusChanged(int moveId, int status, long estMillis) {
22957                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22958            }
22959        };
22960
22961        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22962        storage.setPrimaryStorageUuid(volumeUuid, callback);
22963        return realMoveId;
22964    }
22965
22966    @Override
22967    public int getMoveStatus(int moveId) {
22968        mContext.enforceCallingOrSelfPermission(
22969                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22970        return mMoveCallbacks.mLastStatus.get(moveId);
22971    }
22972
22973    @Override
22974    public void registerMoveCallback(IPackageMoveObserver callback) {
22975        mContext.enforceCallingOrSelfPermission(
22976                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22977        mMoveCallbacks.register(callback);
22978    }
22979
22980    @Override
22981    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22982        mContext.enforceCallingOrSelfPermission(
22983                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22984        mMoveCallbacks.unregister(callback);
22985    }
22986
22987    @Override
22988    public boolean setInstallLocation(int loc) {
22989        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22990                null);
22991        if (getInstallLocation() == loc) {
22992            return true;
22993        }
22994        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22995                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22996            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22997                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22998            return true;
22999        }
23000        return false;
23001   }
23002
23003    @Override
23004    public int getInstallLocation() {
23005        // allow instant app access
23006        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23007                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23008                PackageHelper.APP_INSTALL_AUTO);
23009    }
23010
23011    /** Called by UserManagerService */
23012    void cleanUpUser(UserManagerService userManager, int userHandle) {
23013        synchronized (mPackages) {
23014            mDirtyUsers.remove(userHandle);
23015            mUserNeedsBadging.delete(userHandle);
23016            mSettings.removeUserLPw(userHandle);
23017            mPendingBroadcasts.remove(userHandle);
23018            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23019            removeUnusedPackagesLPw(userManager, userHandle);
23020        }
23021    }
23022
23023    /**
23024     * We're removing userHandle and would like to remove any downloaded packages
23025     * that are no longer in use by any other user.
23026     * @param userHandle the user being removed
23027     */
23028    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23029        final boolean DEBUG_CLEAN_APKS = false;
23030        int [] users = userManager.getUserIds();
23031        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23032        while (psit.hasNext()) {
23033            PackageSetting ps = psit.next();
23034            if (ps.pkg == null) {
23035                continue;
23036            }
23037            final String packageName = ps.pkg.packageName;
23038            // Skip over if system app
23039            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23040                continue;
23041            }
23042            if (DEBUG_CLEAN_APKS) {
23043                Slog.i(TAG, "Checking package " + packageName);
23044            }
23045            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23046            if (keep) {
23047                if (DEBUG_CLEAN_APKS) {
23048                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23049                }
23050            } else {
23051                for (int i = 0; i < users.length; i++) {
23052                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23053                        keep = true;
23054                        if (DEBUG_CLEAN_APKS) {
23055                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23056                                    + users[i]);
23057                        }
23058                        break;
23059                    }
23060                }
23061            }
23062            if (!keep) {
23063                if (DEBUG_CLEAN_APKS) {
23064                    Slog.i(TAG, "  Removing package " + packageName);
23065                }
23066                mHandler.post(new Runnable() {
23067                    public void run() {
23068                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23069                                userHandle, 0);
23070                    } //end run
23071                });
23072            }
23073        }
23074    }
23075
23076    /** Called by UserManagerService */
23077    void createNewUser(int userId, String[] disallowedPackages) {
23078        synchronized (mInstallLock) {
23079            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23080        }
23081        synchronized (mPackages) {
23082            scheduleWritePackageRestrictionsLocked(userId);
23083            scheduleWritePackageListLocked(userId);
23084            applyFactoryDefaultBrowserLPw(userId);
23085            primeDomainVerificationsLPw(userId);
23086        }
23087    }
23088
23089    void onNewUserCreated(final int userId) {
23090        synchronized(mPackages) {
23091            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23092            // If permission review for legacy apps is required, we represent
23093            // dagerous permissions for such apps as always granted runtime
23094            // permissions to keep per user flag state whether review is needed.
23095            // Hence, if a new user is added we have to propagate dangerous
23096            // permission grants for these legacy apps.
23097            if (mPermissionReviewRequired) {
23098                updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23099                        | UPDATE_PERMISSIONS_REPLACE_ALL);
23100            }
23101        }
23102    }
23103
23104    @Override
23105    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23106        mContext.enforceCallingOrSelfPermission(
23107                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23108                "Only package verification agents can read the verifier device identity");
23109
23110        synchronized (mPackages) {
23111            return mSettings.getVerifierDeviceIdentityLPw();
23112        }
23113    }
23114
23115    @Override
23116    public void setPermissionEnforced(String permission, boolean enforced) {
23117        // TODO: Now that we no longer change GID for storage, this should to away.
23118        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23119                "setPermissionEnforced");
23120        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23121            synchronized (mPackages) {
23122                if (mSettings.mReadExternalStorageEnforced == null
23123                        || mSettings.mReadExternalStorageEnforced != enforced) {
23124                    mSettings.mReadExternalStorageEnforced =
23125                            enforced ? Boolean.TRUE : Boolean.FALSE;
23126                    mSettings.writeLPr();
23127                }
23128            }
23129            // kill any non-foreground processes so we restart them and
23130            // grant/revoke the GID.
23131            final IActivityManager am = ActivityManager.getService();
23132            if (am != null) {
23133                final long token = Binder.clearCallingIdentity();
23134                try {
23135                    am.killProcessesBelowForeground("setPermissionEnforcement");
23136                } catch (RemoteException e) {
23137                } finally {
23138                    Binder.restoreCallingIdentity(token);
23139                }
23140            }
23141        } else {
23142            throw new IllegalArgumentException("No selective enforcement for " + permission);
23143        }
23144    }
23145
23146    @Override
23147    @Deprecated
23148    public boolean isPermissionEnforced(String permission) {
23149        // allow instant applications
23150        return true;
23151    }
23152
23153    @Override
23154    public boolean isStorageLow() {
23155        // allow instant applications
23156        final long token = Binder.clearCallingIdentity();
23157        try {
23158            final DeviceStorageMonitorInternal
23159                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23160            if (dsm != null) {
23161                return dsm.isMemoryLow();
23162            } else {
23163                return false;
23164            }
23165        } finally {
23166            Binder.restoreCallingIdentity(token);
23167        }
23168    }
23169
23170    @Override
23171    public IPackageInstaller getPackageInstaller() {
23172        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23173            return null;
23174        }
23175        return mInstallerService;
23176    }
23177
23178    private boolean userNeedsBadging(int userId) {
23179        int index = mUserNeedsBadging.indexOfKey(userId);
23180        if (index < 0) {
23181            final UserInfo userInfo;
23182            final long token = Binder.clearCallingIdentity();
23183            try {
23184                userInfo = sUserManager.getUserInfo(userId);
23185            } finally {
23186                Binder.restoreCallingIdentity(token);
23187            }
23188            final boolean b;
23189            if (userInfo != null && userInfo.isManagedProfile()) {
23190                b = true;
23191            } else {
23192                b = false;
23193            }
23194            mUserNeedsBadging.put(userId, b);
23195            return b;
23196        }
23197        return mUserNeedsBadging.valueAt(index);
23198    }
23199
23200    @Override
23201    public KeySet getKeySetByAlias(String packageName, String alias) {
23202        if (packageName == null || alias == null) {
23203            return null;
23204        }
23205        synchronized(mPackages) {
23206            final PackageParser.Package pkg = mPackages.get(packageName);
23207            if (pkg == null) {
23208                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23209                throw new IllegalArgumentException("Unknown package: " + packageName);
23210            }
23211            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23212            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23213                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23214                throw new IllegalArgumentException("Unknown package: " + packageName);
23215            }
23216            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23217            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23218        }
23219    }
23220
23221    @Override
23222    public KeySet getSigningKeySet(String packageName) {
23223        if (packageName == null) {
23224            return null;
23225        }
23226        synchronized(mPackages) {
23227            final int callingUid = Binder.getCallingUid();
23228            final int callingUserId = UserHandle.getUserId(callingUid);
23229            final PackageParser.Package pkg = mPackages.get(packageName);
23230            if (pkg == null) {
23231                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23232                throw new IllegalArgumentException("Unknown package: " + packageName);
23233            }
23234            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23235            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23236                // filter and pretend the package doesn't exist
23237                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23238                        + ", uid:" + callingUid);
23239                throw new IllegalArgumentException("Unknown package: " + packageName);
23240            }
23241            if (pkg.applicationInfo.uid != callingUid
23242                    && Process.SYSTEM_UID != callingUid) {
23243                throw new SecurityException("May not access signing KeySet of other apps.");
23244            }
23245            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23246            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23247        }
23248    }
23249
23250    @Override
23251    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23252        final int callingUid = Binder.getCallingUid();
23253        if (getInstantAppPackageName(callingUid) != null) {
23254            return false;
23255        }
23256        if (packageName == null || ks == null) {
23257            return false;
23258        }
23259        synchronized(mPackages) {
23260            final PackageParser.Package pkg = mPackages.get(packageName);
23261            if (pkg == null
23262                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23263                            UserHandle.getUserId(callingUid))) {
23264                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23265                throw new IllegalArgumentException("Unknown package: " + packageName);
23266            }
23267            IBinder ksh = ks.getToken();
23268            if (ksh instanceof KeySetHandle) {
23269                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23270                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23271            }
23272            return false;
23273        }
23274    }
23275
23276    @Override
23277    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23278        final int callingUid = Binder.getCallingUid();
23279        if (getInstantAppPackageName(callingUid) != null) {
23280            return false;
23281        }
23282        if (packageName == null || ks == null) {
23283            return false;
23284        }
23285        synchronized(mPackages) {
23286            final PackageParser.Package pkg = mPackages.get(packageName);
23287            if (pkg == null
23288                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23289                            UserHandle.getUserId(callingUid))) {
23290                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23291                throw new IllegalArgumentException("Unknown package: " + packageName);
23292            }
23293            IBinder ksh = ks.getToken();
23294            if (ksh instanceof KeySetHandle) {
23295                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23296                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23297            }
23298            return false;
23299        }
23300    }
23301
23302    private void deletePackageIfUnusedLPr(final String packageName) {
23303        PackageSetting ps = mSettings.mPackages.get(packageName);
23304        if (ps == null) {
23305            return;
23306        }
23307        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23308            // TODO Implement atomic delete if package is unused
23309            // It is currently possible that the package will be deleted even if it is installed
23310            // after this method returns.
23311            mHandler.post(new Runnable() {
23312                public void run() {
23313                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23314                            0, PackageManager.DELETE_ALL_USERS);
23315                }
23316            });
23317        }
23318    }
23319
23320    /**
23321     * Check and throw if the given before/after packages would be considered a
23322     * downgrade.
23323     */
23324    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23325            throws PackageManagerException {
23326        if (after.versionCode < before.mVersionCode) {
23327            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23328                    "Update version code " + after.versionCode + " is older than current "
23329                    + before.mVersionCode);
23330        } else if (after.versionCode == before.mVersionCode) {
23331            if (after.baseRevisionCode < before.baseRevisionCode) {
23332                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23333                        "Update base revision code " + after.baseRevisionCode
23334                        + " is older than current " + before.baseRevisionCode);
23335            }
23336
23337            if (!ArrayUtils.isEmpty(after.splitNames)) {
23338                for (int i = 0; i < after.splitNames.length; i++) {
23339                    final String splitName = after.splitNames[i];
23340                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23341                    if (j != -1) {
23342                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23343                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23344                                    "Update split " + splitName + " revision code "
23345                                    + after.splitRevisionCodes[i] + " is older than current "
23346                                    + before.splitRevisionCodes[j]);
23347                        }
23348                    }
23349                }
23350            }
23351        }
23352    }
23353
23354    private static class MoveCallbacks extends Handler {
23355        private static final int MSG_CREATED = 1;
23356        private static final int MSG_STATUS_CHANGED = 2;
23357
23358        private final RemoteCallbackList<IPackageMoveObserver>
23359                mCallbacks = new RemoteCallbackList<>();
23360
23361        private final SparseIntArray mLastStatus = new SparseIntArray();
23362
23363        public MoveCallbacks(Looper looper) {
23364            super(looper);
23365        }
23366
23367        public void register(IPackageMoveObserver callback) {
23368            mCallbacks.register(callback);
23369        }
23370
23371        public void unregister(IPackageMoveObserver callback) {
23372            mCallbacks.unregister(callback);
23373        }
23374
23375        @Override
23376        public void handleMessage(Message msg) {
23377            final SomeArgs args = (SomeArgs) msg.obj;
23378            final int n = mCallbacks.beginBroadcast();
23379            for (int i = 0; i < n; i++) {
23380                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23381                try {
23382                    invokeCallback(callback, msg.what, args);
23383                } catch (RemoteException ignored) {
23384                }
23385            }
23386            mCallbacks.finishBroadcast();
23387            args.recycle();
23388        }
23389
23390        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23391                throws RemoteException {
23392            switch (what) {
23393                case MSG_CREATED: {
23394                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23395                    break;
23396                }
23397                case MSG_STATUS_CHANGED: {
23398                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23399                    break;
23400                }
23401            }
23402        }
23403
23404        private void notifyCreated(int moveId, Bundle extras) {
23405            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23406
23407            final SomeArgs args = SomeArgs.obtain();
23408            args.argi1 = moveId;
23409            args.arg2 = extras;
23410            obtainMessage(MSG_CREATED, args).sendToTarget();
23411        }
23412
23413        private void notifyStatusChanged(int moveId, int status) {
23414            notifyStatusChanged(moveId, status, -1);
23415        }
23416
23417        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23418            Slog.v(TAG, "Move " + moveId + " status " + status);
23419
23420            final SomeArgs args = SomeArgs.obtain();
23421            args.argi1 = moveId;
23422            args.argi2 = status;
23423            args.arg3 = estMillis;
23424            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23425
23426            synchronized (mLastStatus) {
23427                mLastStatus.put(moveId, status);
23428            }
23429        }
23430    }
23431
23432    private final static class OnPermissionChangeListeners extends Handler {
23433        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23434
23435        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23436                new RemoteCallbackList<>();
23437
23438        public OnPermissionChangeListeners(Looper looper) {
23439            super(looper);
23440        }
23441
23442        @Override
23443        public void handleMessage(Message msg) {
23444            switch (msg.what) {
23445                case MSG_ON_PERMISSIONS_CHANGED: {
23446                    final int uid = msg.arg1;
23447                    handleOnPermissionsChanged(uid);
23448                } break;
23449            }
23450        }
23451
23452        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23453            mPermissionListeners.register(listener);
23454
23455        }
23456
23457        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23458            mPermissionListeners.unregister(listener);
23459        }
23460
23461        public void onPermissionsChanged(int uid) {
23462            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23463                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23464            }
23465        }
23466
23467        private void handleOnPermissionsChanged(int uid) {
23468            final int count = mPermissionListeners.beginBroadcast();
23469            try {
23470                for (int i = 0; i < count; i++) {
23471                    IOnPermissionsChangeListener callback = mPermissionListeners
23472                            .getBroadcastItem(i);
23473                    try {
23474                        callback.onPermissionsChanged(uid);
23475                    } catch (RemoteException e) {
23476                        Log.e(TAG, "Permission listener is dead", e);
23477                    }
23478                }
23479            } finally {
23480                mPermissionListeners.finishBroadcast();
23481            }
23482        }
23483    }
23484
23485    private class PackageManagerNative extends IPackageManagerNative.Stub {
23486        @Override
23487        public String[] getNamesForUids(int[] uids) throws RemoteException {
23488            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23489            // massage results so they can be parsed by the native binder
23490            for (int i = results.length - 1; i >= 0; --i) {
23491                if (results[i] == null) {
23492                    results[i] = "";
23493                }
23494            }
23495            return results;
23496        }
23497
23498        // NB: this differentiates between preloads and sideloads
23499        @Override
23500        public String getInstallerForPackage(String packageName) throws RemoteException {
23501            final String installerName = getInstallerPackageName(packageName);
23502            if (!TextUtils.isEmpty(installerName)) {
23503                return installerName;
23504            }
23505            // differentiate between preload and sideload
23506            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23507            ApplicationInfo appInfo = getApplicationInfo(packageName,
23508                                    /*flags*/ 0,
23509                                    /*userId*/ callingUser);
23510            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23511                return "preload";
23512            }
23513            return "";
23514        }
23515
23516        @Override
23517        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23518            try {
23519                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23520                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23521                if (pInfo != null) {
23522                    return pInfo.versionCode;
23523                }
23524            } catch (Exception e) {
23525            }
23526            return 0;
23527        }
23528    }
23529
23530    private class PackageManagerInternalImpl extends PackageManagerInternal {
23531        @Override
23532        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23533                int flagValues, int userId) {
23534            PackageManagerService.this.updatePermissionFlags(
23535                    permName, packageName, flagMask, flagValues, userId);
23536        }
23537
23538        @Override
23539        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23540            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23541        }
23542
23543        @Override
23544        public boolean isInstantApp(String packageName, int userId) {
23545            return PackageManagerService.this.isInstantApp(packageName, userId);
23546        }
23547
23548        @Override
23549        public String getInstantAppPackageName(int uid) {
23550            return PackageManagerService.this.getInstantAppPackageName(uid);
23551        }
23552
23553        @Override
23554        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23555            synchronized (mPackages) {
23556                return PackageManagerService.this.filterAppAccessLPr(
23557                        (PackageSetting) pkg.mExtras, callingUid, userId);
23558            }
23559        }
23560
23561        @Override
23562        public PackageParser.Package getPackage(String packageName) {
23563            synchronized (mPackages) {
23564                packageName = resolveInternalPackageNameLPr(
23565                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23566                return mPackages.get(packageName);
23567            }
23568        }
23569
23570        @Override
23571        public PackageParser.Package getDisabledPackage(String packageName) {
23572            synchronized (mPackages) {
23573                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23574                return (ps != null) ? ps.pkg : null;
23575            }
23576        }
23577
23578        @Override
23579        public String getKnownPackageName(int knownPackage, int userId) {
23580            switch(knownPackage) {
23581                case PackageManagerInternal.PACKAGE_BROWSER:
23582                    return getDefaultBrowserPackageName(userId);
23583                case PackageManagerInternal.PACKAGE_INSTALLER:
23584                    return mRequiredInstallerPackage;
23585                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23586                    return mSetupWizardPackage;
23587                case PackageManagerInternal.PACKAGE_SYSTEM:
23588                    return "android";
23589                case PackageManagerInternal.PACKAGE_VERIFIER:
23590                    return mRequiredVerifierPackage;
23591            }
23592            return null;
23593        }
23594
23595        @Override
23596        public boolean isResolveActivityComponent(ComponentInfo component) {
23597            return mResolveActivity.packageName.equals(component.packageName)
23598                    && mResolveActivity.name.equals(component.name);
23599        }
23600
23601        @Override
23602        public void setLocationPackagesProvider(PackagesProvider provider) {
23603            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23604        }
23605
23606        @Override
23607        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23608            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23609        }
23610
23611        @Override
23612        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23613            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23614        }
23615
23616        @Override
23617        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23618            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23619        }
23620
23621        @Override
23622        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23623            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23624        }
23625
23626        @Override
23627        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23628            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23629        }
23630
23631        @Override
23632        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23633            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23634        }
23635
23636        @Override
23637        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23638            synchronized (mPackages) {
23639                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23640            }
23641            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23642        }
23643
23644        @Override
23645        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23646            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23647                    packageName, userId);
23648        }
23649
23650        @Override
23651        public void setKeepUninstalledPackages(final List<String> packageList) {
23652            Preconditions.checkNotNull(packageList);
23653            List<String> removedFromList = null;
23654            synchronized (mPackages) {
23655                if (mKeepUninstalledPackages != null) {
23656                    final int packagesCount = mKeepUninstalledPackages.size();
23657                    for (int i = 0; i < packagesCount; i++) {
23658                        String oldPackage = mKeepUninstalledPackages.get(i);
23659                        if (packageList != null && packageList.contains(oldPackage)) {
23660                            continue;
23661                        }
23662                        if (removedFromList == null) {
23663                            removedFromList = new ArrayList<>();
23664                        }
23665                        removedFromList.add(oldPackage);
23666                    }
23667                }
23668                mKeepUninstalledPackages = new ArrayList<>(packageList);
23669                if (removedFromList != null) {
23670                    final int removedCount = removedFromList.size();
23671                    for (int i = 0; i < removedCount; i++) {
23672                        deletePackageIfUnusedLPr(removedFromList.get(i));
23673                    }
23674                }
23675            }
23676        }
23677
23678        @Override
23679        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23680            synchronized (mPackages) {
23681                // If we do not support permission review, done.
23682                if (!mPermissionReviewRequired) {
23683                    return false;
23684                }
23685
23686                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23687                if (packageSetting == null) {
23688                    return false;
23689                }
23690
23691                // Permission review applies only to apps not supporting the new permission model.
23692                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23693                    return false;
23694                }
23695
23696                // Legacy apps have the permission and get user consent on launch.
23697                PermissionsState permissionsState = packageSetting.getPermissionsState();
23698                return permissionsState.isPermissionReviewRequired(userId);
23699            }
23700        }
23701
23702        @Override
23703        public PackageInfo getPackageInfo(
23704                String packageName, int flags, int filterCallingUid, int userId) {
23705            return PackageManagerService.this
23706                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23707                            flags, filterCallingUid, userId);
23708        }
23709
23710        @Override
23711        public ApplicationInfo getApplicationInfo(
23712                String packageName, int flags, int filterCallingUid, int userId) {
23713            return PackageManagerService.this
23714                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23715        }
23716
23717        @Override
23718        public ActivityInfo getActivityInfo(
23719                ComponentName component, int flags, int filterCallingUid, int userId) {
23720            return PackageManagerService.this
23721                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23722        }
23723
23724        @Override
23725        public List<ResolveInfo> queryIntentActivities(
23726                Intent intent, int flags, int filterCallingUid, int userId) {
23727            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23728            return PackageManagerService.this
23729                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23730                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23731        }
23732
23733        @Override
23734        public List<ResolveInfo> queryIntentServices(
23735                Intent intent, int flags, int callingUid, int userId) {
23736            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23737            return PackageManagerService.this
23738                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23739                            false);
23740        }
23741
23742        @Override
23743        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23744                int userId) {
23745            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23746        }
23747
23748        @Override
23749        public void setDeviceAndProfileOwnerPackages(
23750                int deviceOwnerUserId, String deviceOwnerPackage,
23751                SparseArray<String> profileOwnerPackages) {
23752            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23753                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23754        }
23755
23756        @Override
23757        public boolean isPackageDataProtected(int userId, String packageName) {
23758            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23759        }
23760
23761        @Override
23762        public boolean isPackageEphemeral(int userId, String packageName) {
23763            synchronized (mPackages) {
23764                final PackageSetting ps = mSettings.mPackages.get(packageName);
23765                return ps != null ? ps.getInstantApp(userId) : false;
23766            }
23767        }
23768
23769        @Override
23770        public boolean wasPackageEverLaunched(String packageName, int userId) {
23771            synchronized (mPackages) {
23772                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23773            }
23774        }
23775
23776        @Override
23777        public void grantRuntimePermission(String packageName, String permName, int userId,
23778                boolean overridePolicy) {
23779            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23780                    permName, packageName, overridePolicy, getCallingUid(), userId,
23781                    mPermissionCallback);
23782        }
23783
23784        @Override
23785        public void revokeRuntimePermission(String packageName, String permName, int userId,
23786                boolean overridePolicy) {
23787            mPermissionManager.revokeRuntimePermission(
23788                    permName, packageName, overridePolicy, getCallingUid(), userId,
23789                    mPermissionCallback);
23790        }
23791
23792        @Override
23793        public String getNameForUid(int uid) {
23794            return PackageManagerService.this.getNameForUid(uid);
23795        }
23796
23797        @Override
23798        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23799                Intent origIntent, String resolvedType, String callingPackage,
23800                Bundle verificationBundle, int userId) {
23801            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23802                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23803                    userId);
23804        }
23805
23806        @Override
23807        public void grantEphemeralAccess(int userId, Intent intent,
23808                int targetAppId, int ephemeralAppId) {
23809            synchronized (mPackages) {
23810                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23811                        targetAppId, ephemeralAppId);
23812            }
23813        }
23814
23815        @Override
23816        public boolean isInstantAppInstallerComponent(ComponentName component) {
23817            synchronized (mPackages) {
23818                return mInstantAppInstallerActivity != null
23819                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23820            }
23821        }
23822
23823        @Override
23824        public void pruneInstantApps() {
23825            mInstantAppRegistry.pruneInstantApps();
23826        }
23827
23828        @Override
23829        public String getSetupWizardPackageName() {
23830            return mSetupWizardPackage;
23831        }
23832
23833        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23834            if (policy != null) {
23835                mExternalSourcesPolicy = policy;
23836            }
23837        }
23838
23839        @Override
23840        public boolean isPackagePersistent(String packageName) {
23841            synchronized (mPackages) {
23842                PackageParser.Package pkg = mPackages.get(packageName);
23843                return pkg != null
23844                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23845                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23846                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23847                        : false;
23848            }
23849        }
23850
23851        @Override
23852        public List<PackageInfo> getOverlayPackages(int userId) {
23853            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23854            synchronized (mPackages) {
23855                for (PackageParser.Package p : mPackages.values()) {
23856                    if (p.mOverlayTarget != null) {
23857                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23858                        if (pkg != null) {
23859                            overlayPackages.add(pkg);
23860                        }
23861                    }
23862                }
23863            }
23864            return overlayPackages;
23865        }
23866
23867        @Override
23868        public List<String> getTargetPackageNames(int userId) {
23869            List<String> targetPackages = new ArrayList<>();
23870            synchronized (mPackages) {
23871                for (PackageParser.Package p : mPackages.values()) {
23872                    if (p.mOverlayTarget == null) {
23873                        targetPackages.add(p.packageName);
23874                    }
23875                }
23876            }
23877            return targetPackages;
23878        }
23879
23880        @Override
23881        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23882                @Nullable List<String> overlayPackageNames) {
23883            synchronized (mPackages) {
23884                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23885                    Slog.e(TAG, "failed to find package " + targetPackageName);
23886                    return false;
23887                }
23888                ArrayList<String> overlayPaths = null;
23889                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23890                    final int N = overlayPackageNames.size();
23891                    overlayPaths = new ArrayList<>(N);
23892                    for (int i = 0; i < N; i++) {
23893                        final String packageName = overlayPackageNames.get(i);
23894                        final PackageParser.Package pkg = mPackages.get(packageName);
23895                        if (pkg == null) {
23896                            Slog.e(TAG, "failed to find package " + packageName);
23897                            return false;
23898                        }
23899                        overlayPaths.add(pkg.baseCodePath);
23900                    }
23901                }
23902
23903                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23904                ps.setOverlayPaths(overlayPaths, userId);
23905                return true;
23906            }
23907        }
23908
23909        @Override
23910        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23911                int flags, int userId, boolean resolveForStart) {
23912            return resolveIntentInternal(
23913                    intent, resolvedType, flags, userId, resolveForStart);
23914        }
23915
23916        @Override
23917        public ResolveInfo resolveService(Intent intent, String resolvedType,
23918                int flags, int userId, int callingUid) {
23919            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23920        }
23921
23922        @Override
23923        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23924            return PackageManagerService.this.resolveContentProviderInternal(
23925                    name, flags, userId);
23926        }
23927
23928        @Override
23929        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23930            synchronized (mPackages) {
23931                mIsolatedOwners.put(isolatedUid, ownerUid);
23932            }
23933        }
23934
23935        @Override
23936        public void removeIsolatedUid(int isolatedUid) {
23937            synchronized (mPackages) {
23938                mIsolatedOwners.delete(isolatedUid);
23939            }
23940        }
23941
23942        @Override
23943        public int getUidTargetSdkVersion(int uid) {
23944            synchronized (mPackages) {
23945                return getUidTargetSdkVersionLockedLPr(uid);
23946            }
23947        }
23948
23949        @Override
23950        public boolean canAccessInstantApps(int callingUid, int userId) {
23951            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23952        }
23953
23954        @Override
23955        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23956            synchronized (mPackages) {
23957                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23958            }
23959        }
23960
23961        @Override
23962        public void notifyPackageUse(String packageName, int reason) {
23963            synchronized (mPackages) {
23964                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23965            }
23966        }
23967    }
23968
23969    @Override
23970    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23971        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23972        synchronized (mPackages) {
23973            final long identity = Binder.clearCallingIdentity();
23974            try {
23975                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23976                        packageNames, userId);
23977            } finally {
23978                Binder.restoreCallingIdentity(identity);
23979            }
23980        }
23981    }
23982
23983    @Override
23984    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23985        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23986        synchronized (mPackages) {
23987            final long identity = Binder.clearCallingIdentity();
23988            try {
23989                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23990                        packageNames, userId);
23991            } finally {
23992                Binder.restoreCallingIdentity(identity);
23993            }
23994        }
23995    }
23996
23997    private static void enforceSystemOrPhoneCaller(String tag) {
23998        int callingUid = Binder.getCallingUid();
23999        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24000            throw new SecurityException(
24001                    "Cannot call " + tag + " from UID " + callingUid);
24002        }
24003    }
24004
24005    boolean isHistoricalPackageUsageAvailable() {
24006        return mPackageUsage.isHistoricalPackageUsageAvailable();
24007    }
24008
24009    /**
24010     * Return a <b>copy</b> of the collection of packages known to the package manager.
24011     * @return A copy of the values of mPackages.
24012     */
24013    Collection<PackageParser.Package> getPackages() {
24014        synchronized (mPackages) {
24015            return new ArrayList<>(mPackages.values());
24016        }
24017    }
24018
24019    /**
24020     * Logs process start information (including base APK hash) to the security log.
24021     * @hide
24022     */
24023    @Override
24024    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24025            String apkFile, int pid) {
24026        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24027            return;
24028        }
24029        if (!SecurityLog.isLoggingEnabled()) {
24030            return;
24031        }
24032        Bundle data = new Bundle();
24033        data.putLong("startTimestamp", System.currentTimeMillis());
24034        data.putString("processName", processName);
24035        data.putInt("uid", uid);
24036        data.putString("seinfo", seinfo);
24037        data.putString("apkFile", apkFile);
24038        data.putInt("pid", pid);
24039        Message msg = mProcessLoggingHandler.obtainMessage(
24040                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24041        msg.setData(data);
24042        mProcessLoggingHandler.sendMessage(msg);
24043    }
24044
24045    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24046        return mCompilerStats.getPackageStats(pkgName);
24047    }
24048
24049    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24050        return getOrCreateCompilerPackageStats(pkg.packageName);
24051    }
24052
24053    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24054        return mCompilerStats.getOrCreatePackageStats(pkgName);
24055    }
24056
24057    public void deleteCompilerPackageStats(String pkgName) {
24058        mCompilerStats.deletePackageStats(pkgName);
24059    }
24060
24061    @Override
24062    public int getInstallReason(String packageName, int userId) {
24063        final int callingUid = Binder.getCallingUid();
24064        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24065                true /* requireFullPermission */, false /* checkShell */,
24066                "get install reason");
24067        synchronized (mPackages) {
24068            final PackageSetting ps = mSettings.mPackages.get(packageName);
24069            if (filterAppAccessLPr(ps, callingUid, userId)) {
24070                return PackageManager.INSTALL_REASON_UNKNOWN;
24071            }
24072            if (ps != null) {
24073                return ps.getInstallReason(userId);
24074            }
24075        }
24076        return PackageManager.INSTALL_REASON_UNKNOWN;
24077    }
24078
24079    @Override
24080    public boolean canRequestPackageInstalls(String packageName, int userId) {
24081        return canRequestPackageInstallsInternal(packageName, 0, userId,
24082                true /* throwIfPermNotDeclared*/);
24083    }
24084
24085    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24086            boolean throwIfPermNotDeclared) {
24087        int callingUid = Binder.getCallingUid();
24088        int uid = getPackageUid(packageName, 0, userId);
24089        if (callingUid != uid && callingUid != Process.ROOT_UID
24090                && callingUid != Process.SYSTEM_UID) {
24091            throw new SecurityException(
24092                    "Caller uid " + callingUid + " does not own package " + packageName);
24093        }
24094        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24095        if (info == null) {
24096            return false;
24097        }
24098        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24099            return false;
24100        }
24101        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24102        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24103        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24104            if (throwIfPermNotDeclared) {
24105                throw new SecurityException("Need to declare " + appOpPermission
24106                        + " to call this api");
24107            } else {
24108                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24109                return false;
24110            }
24111        }
24112        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24113            return false;
24114        }
24115        if (mExternalSourcesPolicy != null) {
24116            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24117            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24118                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24119            }
24120        }
24121        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24122    }
24123
24124    @Override
24125    public ComponentName getInstantAppResolverSettingsComponent() {
24126        return mInstantAppResolverSettingsComponent;
24127    }
24128
24129    @Override
24130    public ComponentName getInstantAppInstallerComponent() {
24131        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24132            return null;
24133        }
24134        return mInstantAppInstallerActivity == null
24135                ? null : mInstantAppInstallerActivity.getComponentName();
24136    }
24137
24138    @Override
24139    public String getInstantAppAndroidId(String packageName, int userId) {
24140        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24141                "getInstantAppAndroidId");
24142        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24143                true /* requireFullPermission */, false /* checkShell */,
24144                "getInstantAppAndroidId");
24145        // Make sure the target is an Instant App.
24146        if (!isInstantApp(packageName, userId)) {
24147            return null;
24148        }
24149        synchronized (mPackages) {
24150            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24151        }
24152    }
24153
24154    boolean canHaveOatDir(String packageName) {
24155        synchronized (mPackages) {
24156            PackageParser.Package p = mPackages.get(packageName);
24157            if (p == null) {
24158                return false;
24159            }
24160            return p.canHaveOatDir();
24161        }
24162    }
24163
24164    private String getOatDir(PackageParser.Package pkg) {
24165        if (!pkg.canHaveOatDir()) {
24166            return null;
24167        }
24168        File codePath = new File(pkg.codePath);
24169        if (codePath.isDirectory()) {
24170            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24171        }
24172        return null;
24173    }
24174
24175    void deleteOatArtifactsOfPackage(String packageName) {
24176        final String[] instructionSets;
24177        final List<String> codePaths;
24178        final String oatDir;
24179        final PackageParser.Package pkg;
24180        synchronized (mPackages) {
24181            pkg = mPackages.get(packageName);
24182        }
24183        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24184        codePaths = pkg.getAllCodePaths();
24185        oatDir = getOatDir(pkg);
24186
24187        for (String codePath : codePaths) {
24188            for (String isa : instructionSets) {
24189                try {
24190                    mInstaller.deleteOdex(codePath, isa, oatDir);
24191                } catch (InstallerException e) {
24192                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24193                }
24194            }
24195        }
24196    }
24197
24198    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24199        Set<String> unusedPackages = new HashSet<>();
24200        long currentTimeInMillis = System.currentTimeMillis();
24201        synchronized (mPackages) {
24202            for (PackageParser.Package pkg : mPackages.values()) {
24203                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24204                if (ps == null) {
24205                    continue;
24206                }
24207                PackageDexUsage.PackageUseInfo packageUseInfo =
24208                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24209                if (PackageManagerServiceUtils
24210                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24211                                downgradeTimeThresholdMillis, packageUseInfo,
24212                                pkg.getLatestPackageUseTimeInMills(),
24213                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24214                    unusedPackages.add(pkg.packageName);
24215                }
24216            }
24217        }
24218        return unusedPackages;
24219    }
24220}
24221
24222interface PackageSender {
24223    void sendPackageBroadcast(final String action, final String pkg,
24224        final Bundle extras, final int flags, final String targetPkg,
24225        final IIntentReceiver finishedReceiver, final int[] userIds);
24226    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24227        boolean includeStopped, int appId, int... userIds);
24228}
24229