PackageManagerService.java revision d6759d46f96fe2c8955751b0fe8037d6c8a75464
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    // Mapping from permission names to info about them.
942    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
943            new ArrayMap<String, PackageParser.PermissionGroup>();
944
945    // Packages whose data we have transfered into another package, thus
946    // should no longer exist.
947    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
948
949    // Broadcast actions that are only available to the system.
950    @GuardedBy("mProtectedBroadcasts")
951    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
952
953    /** List of packages waiting for verification. */
954    final SparseArray<PackageVerificationState> mPendingVerification
955            = new SparseArray<PackageVerificationState>();
956
957    final PackageInstallerService mInstallerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mEphemeralAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final EphemeralResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    // TODO remove this and go through mPermissonManager directly
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008    private final PermissionManagerInternal mPermissionManager;
1009
1010    // List of packages names to keep cached, even if they are uninstalled for all users
1011    private List<String> mKeepUninstalledPackages;
1012
1013    private UserManagerInternal mUserManagerInternal;
1014
1015    private DeviceIdleController.LocalService mDeviceIdleController;
1016
1017    private File mCacheDir;
1018
1019    private ArraySet<String> mPrivappPermissionsViolations;
1020
1021    private Future<?> mPrepareAppDataFuture;
1022
1023    private static class IFVerificationParams {
1024        PackageParser.Package pkg;
1025        boolean replacing;
1026        int userId;
1027        int verifierUid;
1028
1029        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1030                int _userId, int _verifierUid) {
1031            pkg = _pkg;
1032            replacing = _replacing;
1033            userId = _userId;
1034            replacing = _replacing;
1035            verifierUid = _verifierUid;
1036        }
1037    }
1038
1039    private interface IntentFilterVerifier<T extends IntentFilter> {
1040        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1041                                               T filter, String packageName);
1042        void startVerifications(int userId);
1043        void receiveVerificationResponse(int verificationId);
1044    }
1045
1046    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1047        private Context mContext;
1048        private ComponentName mIntentFilterVerifierComponent;
1049        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1050
1051        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1052            mContext = context;
1053            mIntentFilterVerifierComponent = verifierComponent;
1054        }
1055
1056        private String getDefaultScheme() {
1057            return IntentFilter.SCHEME_HTTPS;
1058        }
1059
1060        @Override
1061        public void startVerifications(int userId) {
1062            // Launch verifications requests
1063            int count = mCurrentIntentFilterVerifications.size();
1064            for (int n=0; n<count; n++) {
1065                int verificationId = mCurrentIntentFilterVerifications.get(n);
1066                final IntentFilterVerificationState ivs =
1067                        mIntentFilterVerificationStates.get(verificationId);
1068
1069                String packageName = ivs.getPackageName();
1070
1071                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1072                final int filterCount = filters.size();
1073                ArraySet<String> domainsSet = new ArraySet<>();
1074                for (int m=0; m<filterCount; m++) {
1075                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1076                    domainsSet.addAll(filter.getHostsList());
1077                }
1078                synchronized (mPackages) {
1079                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1080                            packageName, domainsSet) != null) {
1081                        scheduleWriteSettingsLocked();
1082                    }
1083                }
1084                sendVerificationRequest(verificationId, ivs);
1085            }
1086            mCurrentIntentFilterVerifications.clear();
1087        }
1088
1089        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1090            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1093                    verificationId);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1096                    getDefaultScheme());
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1099                    ivs.getHostsString());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1102                    ivs.getPackageName());
1103            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1104            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1105
1106            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1107            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1108                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1109                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1110
1111            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Sending IntentFilter verification broadcast");
1114        }
1115
1116        public void receiveVerificationResponse(int verificationId) {
1117            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1118
1119            final boolean verified = ivs.isVerified();
1120
1121            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1122            final int count = filters.size();
1123            if (DEBUG_DOMAIN_VERIFICATION) {
1124                Slog.i(TAG, "Received verification response " + verificationId
1125                        + " for " + count + " filters, verified=" + verified);
1126            }
1127            for (int n=0; n<count; n++) {
1128                PackageParser.ActivityIntentInfo filter = filters.get(n);
1129                filter.setVerified(verified);
1130
1131                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1132                        + " verified with result:" + verified + " and hosts:"
1133                        + ivs.getHostsString());
1134            }
1135
1136            mIntentFilterVerificationStates.remove(verificationId);
1137
1138            final String packageName = ivs.getPackageName();
1139            IntentFilterVerificationInfo ivi = null;
1140
1141            synchronized (mPackages) {
1142                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1143            }
1144            if (ivi == null) {
1145                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1146                        + verificationId + " packageName:" + packageName);
1147                return;
1148            }
1149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1150                    "Updating IntentFilterVerificationInfo for package " + packageName
1151                            +" verificationId:" + verificationId);
1152
1153            synchronized (mPackages) {
1154                if (verified) {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1156                } else {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1158                }
1159                scheduleWriteSettingsLocked();
1160
1161                final int userId = ivs.getUserId();
1162                if (userId != UserHandle.USER_ALL) {
1163                    final int userStatus =
1164                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1165
1166                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1167                    boolean needUpdate = false;
1168
1169                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1170                    // already been set by the User thru the Disambiguation dialog
1171                    switch (userStatus) {
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                            } else {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1177                            }
1178                            needUpdate = true;
1179                            break;
1180
1181                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1182                            if (verified) {
1183                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1184                                needUpdate = true;
1185                            }
1186                            break;
1187
1188                        default:
1189                            // Nothing to do
1190                    }
1191
1192                    if (needUpdate) {
1193                        mSettings.updateIntentFilterVerificationStatusLPw(
1194                                packageName, updatedStatus, userId);
1195                        scheduleWritePackageRestrictionsLocked(userId);
1196                    }
1197                }
1198            }
1199        }
1200
1201        @Override
1202        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1203                    ActivityIntentInfo filter, String packageName) {
1204            if (!hasValidDomains(filter)) {
1205                return false;
1206            }
1207            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1208            if (ivs == null) {
1209                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1210                        packageName);
1211            }
1212            if (DEBUG_DOMAIN_VERIFICATION) {
1213                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1214            }
1215            ivs.addFilter(filter);
1216            return true;
1217        }
1218
1219        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1220                int userId, int verificationId, String packageName) {
1221            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1222                    verifierUid, userId, packageName);
1223            ivs.setPendingState();
1224            synchronized (mPackages) {
1225                mIntentFilterVerificationStates.append(verificationId, ivs);
1226                mCurrentIntentFilterVerifications.add(verificationId);
1227            }
1228            return ivs;
1229        }
1230    }
1231
1232    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1233        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1234                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1235                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1236    }
1237
1238    // Set of pending broadcasts for aggregating enable/disable of components.
1239    static class PendingPackageBroadcasts {
1240        // for each user id, a map of <package name -> components within that package>
1241        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1242
1243        public PendingPackageBroadcasts() {
1244            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1245        }
1246
1247        public ArrayList<String> get(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1249            return packages.get(packageName);
1250        }
1251
1252        public void put(int userId, String packageName, ArrayList<String> components) {
1253            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1254            packages.put(packageName, components);
1255        }
1256
1257        public void remove(int userId, String packageName) {
1258            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1259            if (packages != null) {
1260                packages.remove(packageName);
1261            }
1262        }
1263
1264        public void remove(int userId) {
1265            mUidMap.remove(userId);
1266        }
1267
1268        public int userIdCount() {
1269            return mUidMap.size();
1270        }
1271
1272        public int userIdAt(int n) {
1273            return mUidMap.keyAt(n);
1274        }
1275
1276        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1277            return mUidMap.get(userId);
1278        }
1279
1280        public int size() {
1281            // total number of pending broadcast entries across all userIds
1282            int num = 0;
1283            for (int i = 0; i< mUidMap.size(); i++) {
1284                num += mUidMap.valueAt(i).size();
1285            }
1286            return num;
1287        }
1288
1289        public void clear() {
1290            mUidMap.clear();
1291        }
1292
1293        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1294            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1295            if (map == null) {
1296                map = new ArrayMap<String, ArrayList<String>>();
1297                mUidMap.put(userId, map);
1298            }
1299            return map;
1300        }
1301    }
1302    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1303
1304    // Service Connection to remote media container service to copy
1305    // package uri's from external media onto secure containers
1306    // or internal storage.
1307    private IMediaContainerService mContainerService = null;
1308
1309    static final int SEND_PENDING_BROADCAST = 1;
1310    static final int MCS_BOUND = 3;
1311    static final int END_COPY = 4;
1312    static final int INIT_COPY = 5;
1313    static final int MCS_UNBIND = 6;
1314    static final int START_CLEANING_PACKAGE = 7;
1315    static final int FIND_INSTALL_LOC = 8;
1316    static final int POST_INSTALL = 9;
1317    static final int MCS_RECONNECT = 10;
1318    static final int MCS_GIVE_UP = 11;
1319    static final int WRITE_SETTINGS = 13;
1320    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321    static final int PACKAGE_VERIFIED = 15;
1322    static final int CHECK_PENDING_VERIFICATION = 16;
1323    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324    static final int INTENT_FILTER_VERIFIED = 18;
1325    static final int WRITE_PACKAGE_LIST = 19;
1326    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1327
1328    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1329
1330    // Delay time in millisecs
1331    static final int BROADCAST_DELAY = 10 * 1000;
1332
1333    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1334            2 * 60 * 60 * 1000L; /* two hours */
1335
1336    static UserManagerService sUserManager;
1337
1338    // Stores a list of users whose package restrictions file needs to be updated
1339    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1340
1341    final private DefaultContainerConnection mDefContainerConn =
1342            new DefaultContainerConnection();
1343    class DefaultContainerConnection implements ServiceConnection {
1344        public void onServiceConnected(ComponentName name, IBinder service) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1346            final IMediaContainerService imcs = IMediaContainerService.Stub
1347                    .asInterface(Binder.allowBlocking(service));
1348            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1349        }
1350
1351        public void onServiceDisconnected(ComponentName name) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1353        }
1354    }
1355
1356    // Recordkeeping of restore-after-install operations that are currently in flight
1357    // between the Package Manager and the Backup Manager
1358    static class PostInstallData {
1359        public InstallArgs args;
1360        public PackageInstalledInfo res;
1361
1362        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1363            args = _a;
1364            res = _r;
1365        }
1366    }
1367
1368    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1369    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1370
1371    // XML tags for backup/restore of various bits of state
1372    private static final String TAG_PREFERRED_BACKUP = "pa";
1373    private static final String TAG_DEFAULT_APPS = "da";
1374    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1375
1376    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1377    private static final String TAG_ALL_GRANTS = "rt-grants";
1378    private static final String TAG_GRANT = "grant";
1379    private static final String ATTR_PACKAGE_NAME = "pkg";
1380
1381    private static final String TAG_PERMISSION = "perm";
1382    private static final String ATTR_PERMISSION_NAME = "name";
1383    private static final String ATTR_IS_GRANTED = "g";
1384    private static final String ATTR_USER_SET = "set";
1385    private static final String ATTR_USER_FIXED = "fixed";
1386    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1387
1388    // System/policy permission grants are not backed up
1389    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_POLICY_FIXED
1391            | FLAG_PERMISSION_SYSTEM_FIXED
1392            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1393
1394    // And we back up these user-adjusted states
1395    private static final int USER_RUNTIME_GRANT_MASK =
1396            FLAG_PERMISSION_USER_SET
1397            | FLAG_PERMISSION_USER_FIXED
1398            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1399
1400    final @Nullable String mRequiredVerifierPackage;
1401    final @NonNull String mRequiredInstallerPackage;
1402    final @NonNull String mRequiredUninstallerPackage;
1403    final @Nullable String mSetupWizardPackage;
1404    final @Nullable String mStorageManagerPackage;
1405    final @NonNull String mServicesSystemSharedLibraryPackageName;
1406    final @NonNull String mSharedSystemSharedLibraryPackageName;
1407
1408    final boolean mPermissionReviewRequired;
1409
1410    private final PackageUsage mPackageUsage = new PackageUsage();
1411    private final CompilerStats mCompilerStats = new CompilerStats();
1412
1413    class PackageHandler extends Handler {
1414        private boolean mBound = false;
1415        final ArrayList<HandlerParams> mPendingInstalls =
1416            new ArrayList<HandlerParams>();
1417
1418        private boolean connectToService() {
1419            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1420                    " DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case INIT_COPY: {
1456                    HandlerParams params = (HandlerParams) msg.obj;
1457                    int idx = mPendingInstalls.size();
1458                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1459                    // If a bind was already initiated we dont really
1460                    // need to do anything. The pending install
1461                    // will be processed later on.
1462                    if (!mBound) {
1463                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                System.identityHashCode(mHandler));
1465                        // If this is the only one pending we might
1466                        // have to bind to the service again.
1467                        if (!connectToService()) {
1468                            Slog.e(TAG, "Failed to bind to media container service");
1469                            params.serviceError();
1470                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                    System.identityHashCode(mHandler));
1472                            if (params.traceMethod != null) {
1473                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1474                                        params.traceCookie);
1475                            }
1476                            return;
1477                        } else {
1478                            // Once we bind to the service, the first
1479                            // pending request will be processed.
1480                            mPendingInstalls.add(idx, params);
1481                        }
1482                    } else {
1483                        mPendingInstalls.add(idx, params);
1484                        // Already bound to the service. Just make
1485                        // sure we trigger off processing the first request.
1486                        if (idx == 0) {
1487                            mHandler.sendEmptyMessage(MCS_BOUND);
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_BOUND: {
1493                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1494                    if (msg.obj != null) {
1495                        mContainerService = (IMediaContainerService) msg.obj;
1496                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1497                                System.identityHashCode(mHandler));
1498                    }
1499                    if (mContainerService == null) {
1500                        if (!mBound) {
1501                            // Something seriously wrong since we are not bound and we are not
1502                            // waiting for connection. Bail out.
1503                            Slog.e(TAG, "Cannot bind to media container service");
1504                            for (HandlerParams params : mPendingInstalls) {
1505                                // Indicate service bind error
1506                                params.serviceError();
1507                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                        System.identityHashCode(params));
1509                                if (params.traceMethod != null) {
1510                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1511                                            params.traceMethod, params.traceCookie);
1512                                }
1513                                return;
1514                            }
1515                            mPendingInstalls.clear();
1516                        } else {
1517                            Slog.w(TAG, "Waiting to connect to media container service");
1518                        }
1519                    } else if (mPendingInstalls.size() > 0) {
1520                        HandlerParams params = mPendingInstalls.get(0);
1521                        if (params != null) {
1522                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523                                    System.identityHashCode(params));
1524                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1525                            if (params.startCopy()) {
1526                                // We are done...  look for more work or to
1527                                // go idle.
1528                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1529                                        "Checking for more work or unbind...");
1530                                // Delete pending install
1531                                if (mPendingInstalls.size() > 0) {
1532                                    mPendingInstalls.remove(0);
1533                                }
1534                                if (mPendingInstalls.size() == 0) {
1535                                    if (mBound) {
1536                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                                "Posting delayed MCS_UNBIND");
1538                                        removeMessages(MCS_UNBIND);
1539                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1540                                        // Unbind after a little delay, to avoid
1541                                        // continual thrashing.
1542                                        sendMessageDelayed(ubmsg, 10000);
1543                                    }
1544                                } else {
1545                                    // There are more pending requests in queue.
1546                                    // Just post MCS_BOUND message to trigger processing
1547                                    // of next pending install.
1548                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                            "Posting MCS_BOUND for next work");
1550                                    mHandler.sendEmptyMessage(MCS_BOUND);
1551                                }
1552                            }
1553                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1554                        }
1555                    } else {
1556                        // Should never happen ideally.
1557                        Slog.w(TAG, "Empty queue");
1558                    }
1559                    break;
1560                }
1561                case MCS_RECONNECT: {
1562                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1563                    if (mPendingInstalls.size() > 0) {
1564                        if (mBound) {
1565                            disconnectService();
1566                        }
1567                        if (!connectToService()) {
1568                            Slog.e(TAG, "Failed to bind to media container service");
1569                            for (HandlerParams params : mPendingInstalls) {
1570                                // Indicate service bind error
1571                                params.serviceError();
1572                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573                                        System.identityHashCode(params));
1574                            }
1575                            mPendingInstalls.clear();
1576                        }
1577                    }
1578                    break;
1579                }
1580                case MCS_UNBIND: {
1581                    // If there is no actual work left, then time to unbind.
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1583
1584                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1585                        if (mBound) {
1586                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1587
1588                            disconnectService();
1589                        }
1590                    } else if (mPendingInstalls.size() > 0) {
1591                        // There are more pending requests in queue.
1592                        // Just post MCS_BOUND message to trigger processing
1593                        // of next pending install.
1594                        mHandler.sendEmptyMessage(MCS_BOUND);
1595                    }
1596
1597                    break;
1598                }
1599                case MCS_GIVE_UP: {
1600                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1601                    HandlerParams params = mPendingInstalls.remove(0);
1602                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1603                            System.identityHashCode(params));
1604                    break;
1605                }
1606                case SEND_PENDING_BROADCAST: {
1607                    String packages[];
1608                    ArrayList<String> components[];
1609                    int size = 0;
1610                    int uids[];
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        if (mPendingBroadcasts == null) {
1614                            return;
1615                        }
1616                        size = mPendingBroadcasts.size();
1617                        if (size <= 0) {
1618                            // Nothing to be done. Just return
1619                            return;
1620                        }
1621                        packages = new String[size];
1622                        components = new ArrayList[size];
1623                        uids = new int[size];
1624                        int i = 0;  // filling out the above arrays
1625
1626                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1627                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1628                            Iterator<Map.Entry<String, ArrayList<String>>> it
1629                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1630                                            .entrySet().iterator();
1631                            while (it.hasNext() && i < size) {
1632                                Map.Entry<String, ArrayList<String>> ent = it.next();
1633                                packages[i] = ent.getKey();
1634                                components[i] = ent.getValue();
1635                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1636                                uids[i] = (ps != null)
1637                                        ? UserHandle.getUid(packageUserId, ps.appId)
1638                                        : -1;
1639                                i++;
1640                            }
1641                        }
1642                        size = i;
1643                        mPendingBroadcasts.clear();
1644                    }
1645                    // Send broadcasts
1646                    for (int i = 0; i < size; i++) {
1647                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1648                    }
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1650                    break;
1651                }
1652                case START_CLEANING_PACKAGE: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    final String packageName = (String)msg.obj;
1655                    final int userId = msg.arg1;
1656                    final boolean andCode = msg.arg2 != 0;
1657                    synchronized (mPackages) {
1658                        if (userId == UserHandle.USER_ALL) {
1659                            int[] users = sUserManager.getUserIds();
1660                            for (int user : users) {
1661                                mSettings.addPackageToCleanLPw(
1662                                        new PackageCleanItem(user, packageName, andCode));
1663                            }
1664                        } else {
1665                            mSettings.addPackageToCleanLPw(
1666                                    new PackageCleanItem(userId, packageName, andCode));
1667                        }
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                    startCleaningPackages();
1671                } break;
1672                case POST_INSTALL: {
1673                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1674
1675                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1676                    final boolean didRestore = (msg.arg2 != 0);
1677                    mRunningInstalls.delete(msg.arg1);
1678
1679                    if (data != null) {
1680                        InstallArgs args = data.args;
1681                        PackageInstalledInfo parentRes = data.res;
1682
1683                        final boolean grantPermissions = (args.installFlags
1684                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1685                        final boolean killApp = (args.installFlags
1686                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1687                        final boolean virtualPreload = ((args.installFlags
1688                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1689                        final String[] grantedPermissions = args.installGrantPermissions;
1690
1691                        // Handle the parent package
1692                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1693                                virtualPreload, grantedPermissions, didRestore,
1694                                args.installerPackageName, args.observer);
1695
1696                        // Handle the child packages
1697                        final int childCount = (parentRes.addedChildPackages != null)
1698                                ? parentRes.addedChildPackages.size() : 0;
1699                        for (int i = 0; i < childCount; i++) {
1700                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1701                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1702                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1703                                    args.installerPackageName, args.observer);
1704                        }
1705
1706                        // Log tracing if needed
1707                        if (args.traceMethod != null) {
1708                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1709                                    args.traceCookie);
1710                        }
1711                    } else {
1712                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1713                    }
1714
1715                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1716                } break;
1717                case WRITE_SETTINGS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_SETTINGS);
1721                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1722                        mSettings.writeLPr();
1723                        mDirtyUsers.clear();
1724                    }
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1726                } break;
1727                case WRITE_PACKAGE_RESTRICTIONS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1731                        for (int userId : mDirtyUsers) {
1732                            mSettings.writePackageRestrictionsLPr(userId);
1733                        }
1734                        mDirtyUsers.clear();
1735                    }
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1737                } break;
1738                case WRITE_PACKAGE_LIST: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_PACKAGE_LIST);
1742                        mSettings.writePackageListLPr(msg.arg1);
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case CHECK_PENDING_VERIFICATION: {
1747                    final int verificationId = msg.arg1;
1748                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1749
1750                    if ((state != null) && !state.timeoutExtended()) {
1751                        final InstallArgs args = state.getInstallArgs();
1752                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1753
1754                        Slog.i(TAG, "Verification timed out for " + originUri);
1755                        mPendingVerification.remove(verificationId);
1756
1757                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758
1759                        final UserHandle user = args.getUser();
1760                        if (getDefaultVerificationResponse(user)
1761                                == PackageManager.VERIFICATION_ALLOW) {
1762                            Slog.i(TAG, "Continuing with installation of " + originUri);
1763                            state.setVerifierResponse(Binder.getCallingUid(),
1764                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1765                            broadcastPackageVerified(verificationId, originUri,
1766                                    PackageManager.VERIFICATION_ALLOW, user);
1767                            try {
1768                                ret = args.copyApk(mContainerService, true);
1769                            } catch (RemoteException e) {
1770                                Slog.e(TAG, "Could not contact the ContainerService");
1771                            }
1772                        } else {
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_REJECT, user);
1775                        }
1776
1777                        Trace.asyncTraceEnd(
1778                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1779
1780                        processPendingInstall(args, ret);
1781                        mHandler.sendEmptyMessage(MCS_UNBIND);
1782                    }
1783                    break;
1784                }
1785                case PACKAGE_VERIFIED: {
1786                    final int verificationId = msg.arg1;
1787
1788                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1789                    if (state == null) {
1790                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1791                        break;
1792                    }
1793
1794                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1795
1796                    state.setVerifierResponse(response.callerUid, response.code);
1797
1798                    if (state.isVerificationComplete()) {
1799                        mPendingVerification.remove(verificationId);
1800
1801                        final InstallArgs args = state.getInstallArgs();
1802                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1803
1804                        int ret;
1805                        if (state.isInstallAllowed()) {
1806                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1807                            broadcastPackageVerified(verificationId, originUri,
1808                                    response.code, state.getInstallArgs().getUser());
1809                            try {
1810                                ret = args.copyApk(mContainerService, true);
1811                            } catch (RemoteException e) {
1812                                Slog.e(TAG, "Could not contact the ContainerService");
1813                            }
1814                        } else {
1815                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1816                        }
1817
1818                        Trace.asyncTraceEnd(
1819                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1820
1821                        processPendingInstall(args, ret);
1822                        mHandler.sendEmptyMessage(MCS_UNBIND);
1823                    }
1824
1825                    break;
1826                }
1827                case START_INTENT_FILTER_VERIFICATIONS: {
1828                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1829                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1830                            params.replacing, params.pkg);
1831                    break;
1832                }
1833                case INTENT_FILTER_VERIFIED: {
1834                    final int verificationId = msg.arg1;
1835
1836                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1837                            verificationId);
1838                    if (state == null) {
1839                        Slog.w(TAG, "Invalid IntentFilter verification token "
1840                                + verificationId + " received");
1841                        break;
1842                    }
1843
1844                    final int userId = state.getUserId();
1845
1846                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                            "Processing IntentFilter verification with token:"
1848                            + verificationId + " and userId:" + userId);
1849
1850                    final IntentFilterVerificationResponse response =
1851                            (IntentFilterVerificationResponse) msg.obj;
1852
1853                    state.setVerifierResponse(response.callerUid, response.code);
1854
1855                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                            "IntentFilter verification with token:" + verificationId
1857                            + " and userId:" + userId
1858                            + " is settings verifier response with response code:"
1859                            + response.code);
1860
1861                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1862                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1863                                + response.getFailedDomainsString());
1864                    }
1865
1866                    if (state.isVerificationComplete()) {
1867                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1868                    } else {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                                "IntentFilter verification with token:" + verificationId
1871                                + " was not said to be complete");
1872                    }
1873
1874                    break;
1875                }
1876                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1877                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1878                            mInstantAppResolverConnection,
1879                            (InstantAppRequest) msg.obj,
1880                            mInstantAppInstallerActivity,
1881                            mHandler);
1882                }
1883            }
1884        }
1885    }
1886
1887    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1888        @Override
1889        public void onGidsChanged(int appId, int userId) {
1890            mHandler.post(new Runnable() {
1891                @Override
1892                public void run() {
1893                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1894                }
1895            });
1896        }
1897        @Override
1898        public void onPermissionGranted(int uid, int userId) {
1899            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1900
1901            // Not critical; if this is lost, the application has to request again.
1902            synchronized (mPackages) {
1903                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1904            }
1905        }
1906        @Override
1907        public void onInstallPermissionGranted() {
1908            synchronized (mPackages) {
1909                scheduleWriteSettingsLocked();
1910            }
1911        }
1912        @Override
1913        public void onPermissionRevoked(int uid, int userId) {
1914            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1915
1916            synchronized (mPackages) {
1917                // Critical; after this call the application should never have the permission
1918                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1919            }
1920
1921            final int appId = UserHandle.getAppId(uid);
1922            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1923        }
1924        @Override
1925        public void onInstallPermissionRevoked() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionUpdated(int userId) {
1932            synchronized (mPackages) {
1933                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1934            }
1935        }
1936        @Override
1937        public void onInstallPermissionUpdated() {
1938            synchronized (mPackages) {
1939                scheduleWriteSettingsLocked();
1940            }
1941        }
1942        @Override
1943        public void onPermissionRemoved() {
1944            synchronized (mPackages) {
1945                mSettings.writeLPr();
1946            }
1947        }
1948    };
1949
1950    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1951            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1952            boolean launchedForRestore, String installerPackage,
1953            IPackageInstallObserver2 installObserver) {
1954        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1955            // Send the removed broadcasts
1956            if (res.removedInfo != null) {
1957                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1958            }
1959
1960            // Now that we successfully installed the package, grant runtime
1961            // permissions if requested before broadcasting the install. Also
1962            // for legacy apps in permission review mode we clear the permission
1963            // review flag which is used to emulate runtime permissions for
1964            // legacy apps.
1965            if (grantPermissions) {
1966                final int callingUid = Binder.getCallingUid();
1967                mPermissionManager.grantRequestedRuntimePermissions(
1968                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1969                        mPermissionCallback);
1970            }
1971
1972            final boolean update = res.removedInfo != null
1973                    && res.removedInfo.removedPackage != null;
1974            final String installerPackageName =
1975                    res.installerPackageName != null
1976                            ? res.installerPackageName
1977                            : res.removedInfo != null
1978                                    ? res.removedInfo.installerPackageName
1979                                    : null;
1980
1981            // If this is the first time we have child packages for a disabled privileged
1982            // app that had no children, we grant requested runtime permissions to the new
1983            // children if the parent on the system image had them already granted.
1984            if (res.pkg.parentPackage != null) {
1985                final int callingUid = Binder.getCallingUid();
1986                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1987                        res.pkg, callingUid, mPermissionCallback);
1988            }
1989
1990            synchronized (mPackages) {
1991                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1992            }
1993
1994            final String packageName = res.pkg.applicationInfo.packageName;
1995
1996            // Determine the set of users who are adding this package for
1997            // the first time vs. those who are seeing an update.
1998            int[] firstUsers = EMPTY_INT_ARRAY;
1999            int[] updateUsers = EMPTY_INT_ARRAY;
2000            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2001            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2002            for (int newUser : res.newUsers) {
2003                if (ps.getInstantApp(newUser)) {
2004                    continue;
2005                }
2006                if (allNewUsers) {
2007                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2008                    continue;
2009                }
2010                boolean isNew = true;
2011                for (int origUser : res.origUsers) {
2012                    if (origUser == newUser) {
2013                        isNew = false;
2014                        break;
2015                    }
2016                }
2017                if (isNew) {
2018                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2019                } else {
2020                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2021                }
2022            }
2023
2024            // Send installed broadcasts if the package is not a static shared lib.
2025            if (res.pkg.staticSharedLibName == null) {
2026                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2027
2028                // Send added for users that see the package for the first time
2029                // sendPackageAddedForNewUsers also deals with system apps
2030                int appId = UserHandle.getAppId(res.uid);
2031                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2032                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2033                        virtualPreload /*startReceiver*/, appId, firstUsers);
2034
2035                // Send added for users that don't see the package for the first time
2036                Bundle extras = new Bundle(1);
2037                extras.putInt(Intent.EXTRA_UID, res.uid);
2038                if (update) {
2039                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2040                }
2041                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2042                        extras, 0 /*flags*/,
2043                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2044                if (installerPackageName != null) {
2045                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2046                            extras, 0 /*flags*/,
2047                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2048                }
2049
2050                // Send replaced for users that don't see the package for the first time
2051                if (update) {
2052                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2053                            packageName, extras, 0 /*flags*/,
2054                            null /*targetPackage*/, null /*finishedReceiver*/,
2055                            updateUsers);
2056                    if (installerPackageName != null) {
2057                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2058                                extras, 0 /*flags*/,
2059                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2060                    }
2061                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2062                            null /*package*/, null /*extras*/, 0 /*flags*/,
2063                            packageName /*targetPackage*/,
2064                            null /*finishedReceiver*/, updateUsers);
2065                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2066                    // First-install and we did a restore, so we're responsible for the
2067                    // first-launch broadcast.
2068                    if (DEBUG_BACKUP) {
2069                        Slog.i(TAG, "Post-restore of " + packageName
2070                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2071                    }
2072                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2073                }
2074
2075                // Send broadcast package appeared if forward locked/external for all users
2076                // treat asec-hosted packages like removable media on upgrade
2077                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2078                    if (DEBUG_INSTALL) {
2079                        Slog.i(TAG, "upgrading pkg " + res.pkg
2080                                + " is ASEC-hosted -> AVAILABLE");
2081                    }
2082                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2083                    ArrayList<String> pkgList = new ArrayList<>(1);
2084                    pkgList.add(packageName);
2085                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2086                }
2087            }
2088
2089            // Work that needs to happen on first install within each user
2090            if (firstUsers != null && firstUsers.length > 0) {
2091                synchronized (mPackages) {
2092                    for (int userId : firstUsers) {
2093                        // If this app is a browser and it's newly-installed for some
2094                        // users, clear any default-browser state in those users. The
2095                        // app's nature doesn't depend on the user, so we can just check
2096                        // its browser nature in any user and generalize.
2097                        if (packageIsBrowser(packageName, userId)) {
2098                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2099                        }
2100
2101                        // We may also need to apply pending (restored) runtime
2102                        // permission grants within these users.
2103                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2104                    }
2105                }
2106            }
2107
2108            // Log current value of "unknown sources" setting
2109            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2110                    getUnknownSourcesSettings());
2111
2112            // Remove the replaced package's older resources safely now
2113            // We delete after a gc for applications  on sdcard.
2114            if (res.removedInfo != null && res.removedInfo.args != null) {
2115                Runtime.getRuntime().gc();
2116                synchronized (mInstallLock) {
2117                    res.removedInfo.args.doPostDeleteLI(true);
2118                }
2119            } else {
2120                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2121                // and not block here.
2122                VMRuntime.getRuntime().requestConcurrentGC();
2123            }
2124
2125            // Notify DexManager that the package was installed for new users.
2126            // The updated users should already be indexed and the package code paths
2127            // should not change.
2128            // Don't notify the manager for ephemeral apps as they are not expected to
2129            // survive long enough to benefit of background optimizations.
2130            for (int userId : firstUsers) {
2131                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2132                // There's a race currently where some install events may interleave with an uninstall.
2133                // This can lead to package info being null (b/36642664).
2134                if (info != null) {
2135                    mDexManager.notifyPackageInstalled(info, userId);
2136                }
2137            }
2138        }
2139
2140        // If someone is watching installs - notify them
2141        if (installObserver != null) {
2142            try {
2143                Bundle extras = extrasForInstallResult(res);
2144                installObserver.onPackageInstalled(res.name, res.returnCode,
2145                        res.returnMsg, extras);
2146            } catch (RemoteException e) {
2147                Slog.i(TAG, "Observer no longer exists.");
2148            }
2149        }
2150    }
2151
2152    private StorageEventListener mStorageListener = new StorageEventListener() {
2153        @Override
2154        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2155            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2156                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2157                    final String volumeUuid = vol.getFsUuid();
2158
2159                    // Clean up any users or apps that were removed or recreated
2160                    // while this volume was missing
2161                    sUserManager.reconcileUsers(volumeUuid);
2162                    reconcileApps(volumeUuid);
2163
2164                    // Clean up any install sessions that expired or were
2165                    // cancelled while this volume was missing
2166                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2167
2168                    loadPrivatePackages(vol);
2169
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    unloadPrivatePackages(vol);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2205        Bundle extras = null;
2206        switch (res.returnCode) {
2207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2208                extras = new Bundle();
2209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2210                        res.origPermission);
2211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2212                        res.origPackage);
2213                break;
2214            }
2215            case PackageManager.INSTALL_SUCCEEDED: {
2216                extras = new Bundle();
2217                extras.putBoolean(Intent.EXTRA_REPLACING,
2218                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2219                break;
2220            }
2221        }
2222        return extras;
2223    }
2224
2225    void scheduleWriteSettingsLocked() {
2226        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2227            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2228        }
2229    }
2230
2231    void scheduleWritePackageListLocked(int userId) {
2232        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2233            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2234            msg.arg1 = userId;
2235            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2236        }
2237    }
2238
2239    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2240        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2241        scheduleWritePackageRestrictionsLocked(userId);
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(int userId) {
2245        final int[] userIds = (userId == UserHandle.USER_ALL)
2246                ? sUserManager.getUserIds() : new int[]{userId};
2247        for (int nextUserId : userIds) {
2248            if (!sUserManager.exists(nextUserId)) return;
2249            mDirtyUsers.add(nextUserId);
2250            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2251                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2252            }
2253        }
2254    }
2255
2256    public static PackageManagerService main(Context context, Installer installer,
2257            boolean factoryTest, boolean onlyCore) {
2258        // Self-check for initial settings.
2259        PackageManagerServiceCompilerMapping.checkProperties();
2260
2261        PackageManagerService m = new PackageManagerService(context, installer,
2262                factoryTest, onlyCore);
2263        m.enableSystemUserPackages();
2264        ServiceManager.addService("package", m);
2265        final PackageManagerNative pmn = m.new PackageManagerNative();
2266        ServiceManager.addService("package_native", pmn);
2267        return m;
2268    }
2269
2270    private void enableSystemUserPackages() {
2271        if (!UserManager.isSplitSystemUser()) {
2272            return;
2273        }
2274        // For system user, enable apps based on the following conditions:
2275        // - app is whitelisted or belong to one of these groups:
2276        //   -- system app which has no launcher icons
2277        //   -- system app which has INTERACT_ACROSS_USERS permission
2278        //   -- system IME app
2279        // - app is not in the blacklist
2280        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2281        Set<String> enableApps = new ArraySet<>();
2282        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2283                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2284                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2285        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2286        enableApps.addAll(wlApps);
2287        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2288                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2289        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2290        enableApps.removeAll(blApps);
2291        Log.i(TAG, "Applications installed for system user: " + enableApps);
2292        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2293                UserHandle.SYSTEM);
2294        final int allAppsSize = allAps.size();
2295        synchronized (mPackages) {
2296            for (int i = 0; i < allAppsSize; i++) {
2297                String pName = allAps.get(i);
2298                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2299                // Should not happen, but we shouldn't be failing if it does
2300                if (pkgSetting == null) {
2301                    continue;
2302                }
2303                boolean install = enableApps.contains(pName);
2304                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2305                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2306                            + " for system user");
2307                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2308                }
2309            }
2310            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2311        }
2312    }
2313
2314    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2315        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2316                Context.DISPLAY_SERVICE);
2317        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2318    }
2319
2320    /**
2321     * Requests that files preopted on a secondary system partition be copied to the data partition
2322     * if possible.  Note that the actual copying of the files is accomplished by init for security
2323     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2324     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2325     */
2326    private static void requestCopyPreoptedFiles() {
2327        final int WAIT_TIME_MS = 100;
2328        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2329        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2330            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2331            // We will wait for up to 100 seconds.
2332            final long timeStart = SystemClock.uptimeMillis();
2333            final long timeEnd = timeStart + 100 * 1000;
2334            long timeNow = timeStart;
2335            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2336                try {
2337                    Thread.sleep(WAIT_TIME_MS);
2338                } catch (InterruptedException e) {
2339                    // Do nothing
2340                }
2341                timeNow = SystemClock.uptimeMillis();
2342                if (timeNow > timeEnd) {
2343                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2344                    Slog.wtf(TAG, "cppreopt did not finish!");
2345                    break;
2346                }
2347            }
2348
2349            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2350        }
2351    }
2352
2353    public PackageManagerService(Context context, Installer installer,
2354            boolean factoryTest, boolean onlyCore) {
2355        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2356        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2357        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2358                SystemClock.uptimeMillis());
2359
2360        if (mSdkVersion <= 0) {
2361            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2362        }
2363
2364        mContext = context;
2365
2366        mPermissionReviewRequired = context.getResources().getBoolean(
2367                R.bool.config_permissionReviewRequired);
2368
2369        mFactoryTest = factoryTest;
2370        mOnlyCore = onlyCore;
2371        mMetrics = new DisplayMetrics();
2372        mInstaller = installer;
2373
2374        // Create sub-components that provide services / data. Order here is important.
2375        synchronized (mInstallLock) {
2376        synchronized (mPackages) {
2377            // Expose private service for system components to use.
2378            LocalServices.addService(
2379                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2380            sUserManager = new UserManagerService(context, this,
2381                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2382            mPermissionManager = PermissionManagerService.create(context,
2383                    new DefaultPermissionGrantedCallback() {
2384                        @Override
2385                        public void onDefaultRuntimePermissionsGranted(int userId) {
2386                            synchronized(mPackages) {
2387                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2388                            }
2389                        }
2390                    }, mPackages /*externalLock*/);
2391            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2392            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2393        }
2394        }
2395        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407
2408        String separateProcesses = SystemProperties.get("debug.separate_processes");
2409        if (separateProcesses != null && separateProcesses.length() > 0) {
2410            if ("*".equals(separateProcesses)) {
2411                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412                mSeparateProcesses = null;
2413                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2414            } else {
2415                mDefParseFlags = 0;
2416                mSeparateProcesses = separateProcesses.split(",");
2417                Slog.w(TAG, "Running with debug.separate_processes: "
2418                        + separateProcesses);
2419            }
2420        } else {
2421            mDefParseFlags = 0;
2422            mSeparateProcesses = null;
2423        }
2424
2425        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2426                "*dexopt*");
2427        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2428        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2429
2430        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2431                FgThread.get().getLooper());
2432
2433        getDefaultDisplayMetrics(context, mMetrics);
2434
2435        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2436        SystemConfig systemConfig = SystemConfig.getInstance();
2437        mGlobalGids = systemConfig.getGlobalGids();
2438        mSystemPermissions = systemConfig.getSystemPermissions();
2439        mAvailableFeatures = systemConfig.getAvailableFeatures();
2440        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2441
2442        mProtectedPackages = new ProtectedPackages(mContext);
2443
2444        synchronized (mInstallLock) {
2445        // writer
2446        synchronized (mPackages) {
2447            mHandlerThread = new ServiceThread(TAG,
2448                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2449            mHandlerThread.start();
2450            mHandler = new PackageHandler(mHandlerThread.getLooper());
2451            mProcessLoggingHandler = new ProcessLoggingHandler();
2452            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2453            mInstantAppRegistry = new InstantAppRegistry(this);
2454
2455            File dataDir = Environment.getDataDirectory();
2456            mAppInstallDir = new File(dataDir, "app");
2457            mAppLib32InstallDir = new File(dataDir, "app-lib");
2458            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2459
2460            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2461            final int builtInLibCount = libConfig.size();
2462            for (int i = 0; i < builtInLibCount; i++) {
2463                String name = libConfig.keyAt(i);
2464                String path = libConfig.valueAt(i);
2465                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2466                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2467            }
2468
2469            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2470
2471            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2472            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475            // Clean up orphaned packages for which the code path doesn't exist
2476            // and they are an update to a system app - caused by bug/32321269
2477            final int packageSettingCount = mSettings.mPackages.size();
2478            for (int i = packageSettingCount - 1; i >= 0; i--) {
2479                PackageSetting ps = mSettings.mPackages.valueAt(i);
2480                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2481                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2482                    mSettings.mPackages.removeAt(i);
2483                    mSettings.enableSystemPackageLPw(ps.name);
2484                }
2485            }
2486
2487            if (mFirstBoot) {
2488                requestCopyPreoptedFiles();
2489            }
2490
2491            String customResolverActivity = Resources.getSystem().getString(
2492                    R.string.config_customResolverActivity);
2493            if (TextUtils.isEmpty(customResolverActivity)) {
2494                customResolverActivity = null;
2495            } else {
2496                mCustomResolverComponentName = ComponentName.unflattenFromString(
2497                        customResolverActivity);
2498            }
2499
2500            long startTime = SystemClock.uptimeMillis();
2501
2502            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2503                    startTime);
2504
2505            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2506            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2507
2508            if (bootClassPath == null) {
2509                Slog.w(TAG, "No BOOTCLASSPATH found!");
2510            }
2511
2512            if (systemServerClassPath == null) {
2513                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2514            }
2515
2516            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2517
2518            final VersionInfo ver = mSettings.getInternalVersion();
2519            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2520            if (mIsUpgrade) {
2521                logCriticalInfo(Log.INFO,
2522                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2523            }
2524
2525            // when upgrading from pre-M, promote system app permissions from install to runtime
2526            mPromoteSystemApps =
2527                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2528
2529            // When upgrading from pre-N, we need to handle package extraction like first boot,
2530            // as there is no profiling data available.
2531            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2532
2533            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2534
2535            // save off the names of pre-existing system packages prior to scanning; we don't
2536            // want to automatically grant runtime permissions for new system apps
2537            if (mPromoteSystemApps) {
2538                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2539                while (pkgSettingIter.hasNext()) {
2540                    PackageSetting ps = pkgSettingIter.next();
2541                    if (isSystemApp(ps)) {
2542                        mExistingSystemPackages.add(ps.name);
2543                    }
2544                }
2545            }
2546
2547            mCacheDir = preparePackageParserCache(mIsUpgrade);
2548
2549            // Set flag to monitor and not change apk file paths when
2550            // scanning install directories.
2551            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2552
2553            if (mIsUpgrade || mFirstBoot) {
2554                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2555            }
2556
2557            // Collect vendor overlay packages. (Do this before scanning any apps.)
2558            // For security and version matching reason, only consider
2559            // overlay packages if they reside in the right directory.
2560            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2561                    | PackageParser.PARSE_IS_SYSTEM
2562                    | PackageParser.PARSE_IS_SYSTEM_DIR
2563                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2564
2565            mParallelPackageParserCallback.findStaticOverlayPackages();
2566
2567            // Find base frameworks (resource packages without code).
2568            scanDirTracedLI(frameworkDir, mDefParseFlags
2569                    | PackageParser.PARSE_IS_SYSTEM
2570                    | PackageParser.PARSE_IS_SYSTEM_DIR
2571                    | PackageParser.PARSE_IS_PRIVILEGED,
2572                    scanFlags | SCAN_NO_DEX, 0);
2573
2574            // Collected privileged system packages.
2575            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2576            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2577                    | PackageParser.PARSE_IS_SYSTEM
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR
2579                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2580
2581            // Collect ordinary system packages.
2582            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2583            scanDirTracedLI(systemAppDir, mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2586
2587            // Collect all vendor packages.
2588            File vendorAppDir = new File("/vendor/app");
2589            try {
2590                vendorAppDir = vendorAppDir.getCanonicalFile();
2591            } catch (IOException e) {
2592                // failed to look up canonical path, continue with original one
2593            }
2594            scanDirTracedLI(vendorAppDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2597
2598            // Collect all OEM packages.
2599            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2600            scanDirTracedLI(oemAppDir, mDefParseFlags
2601                    | PackageParser.PARSE_IS_SYSTEM
2602                    | PackageParser.PARSE_IS_SYSTEM_DIR
2603                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2604
2605            // Prune any system packages that no longer exist.
2606            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2607            // Stub packages must either be replaced with full versions in the /data
2608            // partition or be disabled.
2609            final List<String> stubSystemApps = new ArrayList<>();
2610            if (!mOnlyCore) {
2611                // do this first before mucking with mPackages for the "expecting better" case
2612                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2613                while (pkgIterator.hasNext()) {
2614                    final PackageParser.Package pkg = pkgIterator.next();
2615                    if (pkg.isStub) {
2616                        stubSystemApps.add(pkg.packageName);
2617                    }
2618                }
2619
2620                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2621                while (psit.hasNext()) {
2622                    PackageSetting ps = psit.next();
2623
2624                    /*
2625                     * If this is not a system app, it can't be a
2626                     * disable system app.
2627                     */
2628                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2629                        continue;
2630                    }
2631
2632                    /*
2633                     * If the package is scanned, it's not erased.
2634                     */
2635                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2636                    if (scannedPkg != null) {
2637                        /*
2638                         * If the system app is both scanned and in the
2639                         * disabled packages list, then it must have been
2640                         * added via OTA. Remove it from the currently
2641                         * scanned package so the previously user-installed
2642                         * application can be scanned.
2643                         */
2644                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2645                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2646                                    + ps.name + "; removing system app.  Last known codePath="
2647                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2648                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2649                                    + scannedPkg.mVersionCode);
2650                            removePackageLI(scannedPkg, true);
2651                            mExpectingBetter.put(ps.name, ps.codePath);
2652                        }
2653
2654                        continue;
2655                    }
2656
2657                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                        psit.remove();
2659                        logCriticalInfo(Log.WARN, "System package " + ps.name
2660                                + " no longer exists; it's data will be wiped");
2661                        // Actual deletion of code and data will be handled by later
2662                        // reconciliation step
2663                    } else {
2664                        // we still have a disabled system package, but, it still might have
2665                        // been removed. check the code path still exists and check there's
2666                        // still a package. the latter can happen if an OTA keeps the same
2667                        // code path, but, changes the package name.
2668                        final PackageSetting disabledPs =
2669                                mSettings.getDisabledSystemPkgLPr(ps.name);
2670                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2671                                || disabledPs.pkg == null) {
2672                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2673                        }
2674                    }
2675                }
2676            }
2677
2678            //look for any incomplete package installations
2679            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2680            for (int i = 0; i < deletePkgsList.size(); i++) {
2681                // Actual deletion of code and data will be handled by later
2682                // reconciliation step
2683                final String packageName = deletePkgsList.get(i).name;
2684                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2685                synchronized (mPackages) {
2686                    mSettings.removePackageLPw(packageName);
2687                }
2688            }
2689
2690            //delete tmp files
2691            deleteTempPackageFiles();
2692
2693            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2694
2695            // Remove any shared userIDs that have no associated packages
2696            mSettings.pruneSharedUsersLPw();
2697            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2698            final int systemPackagesCount = mPackages.size();
2699            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2700                    + " ms, packageCount: " + systemPackagesCount
2701                    + " , timePerPackage: "
2702                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2703                    + " , cached: " + cachedSystemApps);
2704            if (mIsUpgrade && systemPackagesCount > 0) {
2705                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2706                        ((int) systemScanTime) / systemPackagesCount);
2707            }
2708            if (!mOnlyCore) {
2709                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2710                        SystemClock.uptimeMillis());
2711                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2714                        | PackageParser.PARSE_FORWARD_LOCK,
2715                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2716
2717                // Remove disable package settings for updated system apps that were
2718                // removed via an OTA. If the update is no longer present, remove the
2719                // app completely. Otherwise, revoke their system privileges.
2720                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2721                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2722                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2723
2724                    final String msg;
2725                    if (deletedPkg == null) {
2726                        // should have found an update, but, we didn't; remove everything
2727                        msg = "Updated system package " + deletedAppName
2728                                + " no longer exists; removing its data";
2729                        // Actual deletion of code and data will be handled by later
2730                        // reconciliation step
2731                    } else {
2732                        // found an update; revoke system privileges
2733                        msg = "Updated system package + " + deletedAppName
2734                                + " no longer exists; revoking system privileges";
2735
2736                        // Don't do anything if a stub is removed from the system image. If
2737                        // we were to remove the uncompressed version from the /data partition,
2738                        // this is where it'd be done.
2739
2740                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2741                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2742                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2743                    }
2744                    logCriticalInfo(Log.WARN, msg);
2745                }
2746
2747                /*
2748                 * Make sure all system apps that we expected to appear on
2749                 * the userdata partition actually showed up. If they never
2750                 * appeared, crawl back and revive the system version.
2751                 */
2752                for (int i = 0; i < mExpectingBetter.size(); i++) {
2753                    final String packageName = mExpectingBetter.keyAt(i);
2754                    if (!mPackages.containsKey(packageName)) {
2755                        final File scanFile = mExpectingBetter.valueAt(i);
2756
2757                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2758                                + " but never showed up; reverting to system");
2759
2760                        int reparseFlags = mDefParseFlags;
2761                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2764                                    | PackageParser.PARSE_IS_PRIVILEGED;
2765                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2769                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2770                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2771                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2774                                    | PackageParser.PARSE_IS_OEM;
2775                        } else {
2776                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2777                            continue;
2778                        }
2779
2780                        mSettings.enableSystemPackageLPw(packageName);
2781
2782                        try {
2783                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2784                        } catch (PackageManagerException e) {
2785                            Slog.e(TAG, "Failed to parse original system package: "
2786                                    + e.getMessage());
2787                        }
2788                    }
2789                }
2790
2791                // Uncompress and install any stubbed system applications.
2792                // This must be done last to ensure all stubs are replaced or disabled.
2793                decompressSystemApplications(stubSystemApps, scanFlags);
2794
2795                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2796                                - cachedSystemApps;
2797
2798                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2799                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2800                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2801                        + " ms, packageCount: " + dataPackagesCount
2802                        + " , timePerPackage: "
2803                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2804                        + " , cached: " + cachedNonSystemApps);
2805                if (mIsUpgrade && dataPackagesCount > 0) {
2806                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2807                            ((int) dataScanTime) / dataPackagesCount);
2808                }
2809            }
2810            mExpectingBetter.clear();
2811
2812            // Resolve the storage manager.
2813            mStorageManagerPackage = getStorageManagerPackageName();
2814
2815            // Resolve protected action filters. Only the setup wizard is allowed to
2816            // have a high priority filter for these actions.
2817            mSetupWizardPackage = getSetupWizardPackageName();
2818            if (mProtectedFilters.size() > 0) {
2819                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2820                    Slog.i(TAG, "No setup wizard;"
2821                        + " All protected intents capped to priority 0");
2822                }
2823                for (ActivityIntentInfo filter : mProtectedFilters) {
2824                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2825                        if (DEBUG_FILTERS) {
2826                            Slog.i(TAG, "Found setup wizard;"
2827                                + " allow priority " + filter.getPriority() + ";"
2828                                + " package: " + filter.activity.info.packageName
2829                                + " activity: " + filter.activity.className
2830                                + " priority: " + filter.getPriority());
2831                        }
2832                        // skip setup wizard; allow it to keep the high priority filter
2833                        continue;
2834                    }
2835                    if (DEBUG_FILTERS) {
2836                        Slog.i(TAG, "Protected action; cap priority to 0;"
2837                                + " package: " + filter.activity.info.packageName
2838                                + " activity: " + filter.activity.className
2839                                + " origPrio: " + filter.getPriority());
2840                    }
2841                    filter.setPriority(0);
2842                }
2843            }
2844            mDeferProtectedFilters = false;
2845            mProtectedFilters.clear();
2846
2847            // Now that we know all of the shared libraries, update all clients to have
2848            // the correct library paths.
2849            updateAllSharedLibrariesLPw(null);
2850
2851            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2852                // NOTE: We ignore potential failures here during a system scan (like
2853                // the rest of the commands above) because there's precious little we
2854                // can do about it. A settings error is reported, though.
2855                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2856            }
2857
2858            // Now that we know all the packages we are keeping,
2859            // read and update their last usage times.
2860            mPackageUsage.read(mPackages);
2861            mCompilerStats.read();
2862
2863            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2864                    SystemClock.uptimeMillis());
2865            Slog.i(TAG, "Time to scan packages: "
2866                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2867                    + " seconds");
2868
2869            // If the platform SDK has changed since the last time we booted,
2870            // we need to re-grant app permission to catch any new ones that
2871            // appear.  This is really a hack, and means that apps can in some
2872            // cases get permissions that the user didn't initially explicitly
2873            // allow...  it would be nice to have some better way to handle
2874            // this situation.
2875            int updateFlags = UPDATE_PERMISSIONS_ALL;
2876            if (ver.sdkVersion != mSdkVersion) {
2877                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2878                        + mSdkVersion + "; regranting permissions for internal storage");
2879                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2880            }
2881            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2882            ver.sdkVersion = mSdkVersion;
2883
2884            // If this is the first boot or an update from pre-M, and it is a normal
2885            // boot, then we need to initialize the default preferred apps across
2886            // all defined users.
2887            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2888                for (UserInfo user : sUserManager.getUsers(true)) {
2889                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2890                    applyFactoryDefaultBrowserLPw(user.id);
2891                    primeDomainVerificationsLPw(user.id);
2892                }
2893            }
2894
2895            // Prepare storage for system user really early during boot,
2896            // since core system apps like SettingsProvider and SystemUI
2897            // can't wait for user to start
2898            final int storageFlags;
2899            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2900                storageFlags = StorageManager.FLAG_STORAGE_DE;
2901            } else {
2902                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2903            }
2904            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2905                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2906                    true /* onlyCoreApps */);
2907            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2908                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2909                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2910                traceLog.traceBegin("AppDataFixup");
2911                try {
2912                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2913                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2914                } catch (InstallerException e) {
2915                    Slog.w(TAG, "Trouble fixing GIDs", e);
2916                }
2917                traceLog.traceEnd();
2918
2919                traceLog.traceBegin("AppDataPrepare");
2920                if (deferPackages == null || deferPackages.isEmpty()) {
2921                    return;
2922                }
2923                int count = 0;
2924                for (String pkgName : deferPackages) {
2925                    PackageParser.Package pkg = null;
2926                    synchronized (mPackages) {
2927                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2928                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2929                            pkg = ps.pkg;
2930                        }
2931                    }
2932                    if (pkg != null) {
2933                        synchronized (mInstallLock) {
2934                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2935                                    true /* maybeMigrateAppData */);
2936                        }
2937                        count++;
2938                    }
2939                }
2940                traceLog.traceEnd();
2941                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2942            }, "prepareAppData");
2943
2944            // If this is first boot after an OTA, and a normal boot, then
2945            // we need to clear code cache directories.
2946            // Note that we do *not* clear the application profiles. These remain valid
2947            // across OTAs and are used to drive profile verification (post OTA) and
2948            // profile compilation (without waiting to collect a fresh set of profiles).
2949            if (mIsUpgrade && !onlyCore) {
2950                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2951                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2952                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2953                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2954                        // No apps are running this early, so no need to freeze
2955                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2956                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2957                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2958                    }
2959                }
2960                ver.fingerprint = Build.FINGERPRINT;
2961            }
2962
2963            checkDefaultBrowser();
2964
2965            // clear only after permissions and other defaults have been updated
2966            mExistingSystemPackages.clear();
2967            mPromoteSystemApps = false;
2968
2969            // All the changes are done during package scanning.
2970            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2971
2972            // can downgrade to reader
2973            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2974            mSettings.writeLPr();
2975            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2976            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2977                    SystemClock.uptimeMillis());
2978
2979            if (!mOnlyCore) {
2980                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2981                mRequiredInstallerPackage = getRequiredInstallerLPr();
2982                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2983                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2984                if (mIntentFilterVerifierComponent != null) {
2985                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2986                            mIntentFilterVerifierComponent);
2987                } else {
2988                    mIntentFilterVerifier = null;
2989                }
2990                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2991                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2992                        SharedLibraryInfo.VERSION_UNDEFINED);
2993                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2994                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2995                        SharedLibraryInfo.VERSION_UNDEFINED);
2996            } else {
2997                mRequiredVerifierPackage = null;
2998                mRequiredInstallerPackage = null;
2999                mRequiredUninstallerPackage = null;
3000                mIntentFilterVerifierComponent = null;
3001                mIntentFilterVerifier = null;
3002                mServicesSystemSharedLibraryPackageName = null;
3003                mSharedSystemSharedLibraryPackageName = null;
3004            }
3005
3006            mInstallerService = new PackageInstallerService(context, this);
3007            final Pair<ComponentName, String> instantAppResolverComponent =
3008                    getInstantAppResolverLPr();
3009            if (instantAppResolverComponent != null) {
3010                if (DEBUG_EPHEMERAL) {
3011                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3012                }
3013                mInstantAppResolverConnection = new EphemeralResolverConnection(
3014                        mContext, instantAppResolverComponent.first,
3015                        instantAppResolverComponent.second);
3016                mInstantAppResolverSettingsComponent =
3017                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3018            } else {
3019                mInstantAppResolverConnection = null;
3020                mInstantAppResolverSettingsComponent = null;
3021            }
3022            updateInstantAppInstallerLocked(null);
3023
3024            // Read and update the usage of dex files.
3025            // Do this at the end of PM init so that all the packages have their
3026            // data directory reconciled.
3027            // At this point we know the code paths of the packages, so we can validate
3028            // the disk file and build the internal cache.
3029            // The usage file is expected to be small so loading and verifying it
3030            // should take a fairly small time compare to the other activities (e.g. package
3031            // scanning).
3032            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3033            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3034            for (int userId : currentUserIds) {
3035                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3036            }
3037            mDexManager.load(userPackages);
3038            if (mIsUpgrade) {
3039                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3040                        (int) (SystemClock.uptimeMillis() - startTime));
3041            }
3042        } // synchronized (mPackages)
3043        } // synchronized (mInstallLock)
3044
3045        // Now after opening every single application zip, make sure they
3046        // are all flushed.  Not really needed, but keeps things nice and
3047        // tidy.
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3049        Runtime.getRuntime().gc();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3053        FallbackCategoryProvider.loadFallbacks();
3054        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3055
3056        // The initial scanning above does many calls into installd while
3057        // holding the mPackages lock, but we're mostly interested in yelling
3058        // once we have a booted system.
3059        mInstaller.setWarnIfHeld(mPackages);
3060
3061        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3062    }
3063
3064    /**
3065     * Uncompress and install stub applications.
3066     * <p>In order to save space on the system partition, some applications are shipped in a
3067     * compressed form. In addition the compressed bits for the full application, the
3068     * system image contains a tiny stub comprised of only the Android manifest.
3069     * <p>During the first boot, attempt to uncompress and install the full application. If
3070     * the application can't be installed for any reason, disable the stub and prevent
3071     * uncompressing the full application during future boots.
3072     * <p>In order to forcefully attempt an installation of a full application, go to app
3073     * settings and enable the application.
3074     */
3075    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3076        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3077            final String pkgName = stubSystemApps.get(i);
3078            // skip if the system package is already disabled
3079            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3080                stubSystemApps.remove(i);
3081                continue;
3082            }
3083            // skip if the package isn't installed (?!); this should never happen
3084            final PackageParser.Package pkg = mPackages.get(pkgName);
3085            if (pkg == null) {
3086                stubSystemApps.remove(i);
3087                continue;
3088            }
3089            // skip if the package has been disabled by the user
3090            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3091            if (ps != null) {
3092                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3093                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3094                    stubSystemApps.remove(i);
3095                    continue;
3096                }
3097            }
3098
3099            if (DEBUG_COMPRESSION) {
3100                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3101            }
3102
3103            // uncompress the binary to its eventual destination on /data
3104            final File scanFile = decompressPackage(pkg);
3105            if (scanFile == null) {
3106                continue;
3107            }
3108
3109            // install the package to replace the stub on /system
3110            try {
3111                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3112                removePackageLI(pkg, true /*chatty*/);
3113                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3114                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3115                        UserHandle.USER_SYSTEM, "android");
3116                stubSystemApps.remove(i);
3117                continue;
3118            } catch (PackageManagerException e) {
3119                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3120            }
3121
3122            // any failed attempt to install the package will be cleaned up later
3123        }
3124
3125        // disable any stub still left; these failed to install the full application
3126        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3127            final String pkgName = stubSystemApps.get(i);
3128            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3129            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3130                    UserHandle.USER_SYSTEM, "android");
3131            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3132        }
3133    }
3134
3135    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3136        if (DEBUG_COMPRESSION) {
3137            Slog.i(TAG, "Decompress file"
3138                    + "; src: " + srcFile.getAbsolutePath()
3139                    + ", dst: " + dstFile.getAbsolutePath());
3140        }
3141        try (
3142                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3143                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3144        ) {
3145            Streams.copy(fileIn, fileOut);
3146            Os.chmod(dstFile.getAbsolutePath(), 0644);
3147            return PackageManager.INSTALL_SUCCEEDED;
3148        } catch (IOException e) {
3149            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3150                    + "; src: " + srcFile.getAbsolutePath()
3151                    + ", dst: " + dstFile.getAbsolutePath());
3152        }
3153        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3154    }
3155
3156    private File[] getCompressedFiles(String codePath) {
3157        final File stubCodePath = new File(codePath);
3158        final String stubName = stubCodePath.getName();
3159
3160        // The layout of a compressed package on a given partition is as follows :
3161        //
3162        // Compressed artifacts:
3163        //
3164        // /partition/ModuleName/foo.gz
3165        // /partation/ModuleName/bar.gz
3166        //
3167        // Stub artifact:
3168        //
3169        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3170        //
3171        // In other words, stub is on the same partition as the compressed artifacts
3172        // and in a directory that's suffixed with "-Stub".
3173        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3174        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3175            return null;
3176        }
3177
3178        final File stubParentDir = stubCodePath.getParentFile();
3179        if (stubParentDir == null) {
3180            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3181            return null;
3182        }
3183
3184        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3185        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3186            @Override
3187            public boolean accept(File dir, String name) {
3188                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3189            }
3190        });
3191
3192        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3193            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3194        }
3195
3196        return files;
3197    }
3198
3199    private boolean compressedFileExists(String codePath) {
3200        final File[] compressedFiles = getCompressedFiles(codePath);
3201        return compressedFiles != null && compressedFiles.length > 0;
3202    }
3203
3204    /**
3205     * Decompresses the given package on the system image onto
3206     * the /data partition.
3207     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3208     */
3209    private File decompressPackage(PackageParser.Package pkg) {
3210        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3211        if (compressedFiles == null || compressedFiles.length == 0) {
3212            if (DEBUG_COMPRESSION) {
3213                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3214            }
3215            return null;
3216        }
3217        final File dstCodePath =
3218                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3219        int ret = PackageManager.INSTALL_SUCCEEDED;
3220        try {
3221            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3222            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3223            for (File srcFile : compressedFiles) {
3224                final String srcFileName = srcFile.getName();
3225                final String dstFileName = srcFileName.substring(
3226                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3227                final File dstFile = new File(dstCodePath, dstFileName);
3228                ret = decompressFile(srcFile, dstFile);
3229                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3230                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3231                            + "; pkg: " + pkg.packageName
3232                            + ", file: " + dstFileName);
3233                    break;
3234                }
3235            }
3236        } catch (ErrnoException e) {
3237            logCriticalInfo(Log.ERROR, "Failed to decompress"
3238                    + "; pkg: " + pkg.packageName
3239                    + ", err: " + e.errno);
3240        }
3241        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3242            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3243            NativeLibraryHelper.Handle handle = null;
3244            try {
3245                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3246                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3247                        null /*abiOverride*/);
3248            } catch (IOException e) {
3249                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3250                        + "; pkg: " + pkg.packageName);
3251                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3252            } finally {
3253                IoUtils.closeQuietly(handle);
3254            }
3255        }
3256        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3257            if (dstCodePath == null || !dstCodePath.exists()) {
3258                return null;
3259            }
3260            removeCodePathLI(dstCodePath);
3261            return null;
3262        }
3263
3264        // If we have a profile for a compressed APK, copy it to the reference location.
3265        // Since the package is the stub one, remove the stub suffix to get the normal package and
3266        // APK name.
3267        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3268        if (profileFile.exists()) {
3269            try {
3270                // We could also do this lazily before calling dexopt in
3271                // PackageDexOptimizer to prevent this happening on first boot. The issue
3272                // is that we don't have a good way to say "do this only once".
3273                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3274                        pkg.applicationInfo.uid, pkg.packageName)) {
3275                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3276                }
3277            } catch (Exception e) {
3278                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3279            }
3280        }
3281        return dstCodePath;
3282    }
3283
3284    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3285        // we're only interested in updating the installer appliction when 1) it's not
3286        // already set or 2) the modified package is the installer
3287        if (mInstantAppInstallerActivity != null
3288                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3289                        .equals(modifiedPackage)) {
3290            return;
3291        }
3292        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3293    }
3294
3295    private static File preparePackageParserCache(boolean isUpgrade) {
3296        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3297            return null;
3298        }
3299
3300        // Disable package parsing on eng builds to allow for faster incremental development.
3301        if (Build.IS_ENG) {
3302            return null;
3303        }
3304
3305        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3306            Slog.i(TAG, "Disabling package parser cache due to system property.");
3307            return null;
3308        }
3309
3310        // The base directory for the package parser cache lives under /data/system/.
3311        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3312                "package_cache");
3313        if (cacheBaseDir == null) {
3314            return null;
3315        }
3316
3317        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3318        // This also serves to "GC" unused entries when the package cache version changes (which
3319        // can only happen during upgrades).
3320        if (isUpgrade) {
3321            FileUtils.deleteContents(cacheBaseDir);
3322        }
3323
3324
3325        // Return the versioned package cache directory. This is something like
3326        // "/data/system/package_cache/1"
3327        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3328
3329        // The following is a workaround to aid development on non-numbered userdebug
3330        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3331        // the system partition is newer.
3332        //
3333        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3334        // that starts with "eng." to signify that this is an engineering build and not
3335        // destined for release.
3336        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3337            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3338
3339            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3340            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3341            // in general and should not be used for production changes. In this specific case,
3342            // we know that they will work.
3343            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3344            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3345                FileUtils.deleteContents(cacheBaseDir);
3346                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3347            }
3348        }
3349
3350        return cacheDir;
3351    }
3352
3353    @Override
3354    public boolean isFirstBoot() {
3355        // allow instant applications
3356        return mFirstBoot;
3357    }
3358
3359    @Override
3360    public boolean isOnlyCoreApps() {
3361        // allow instant applications
3362        return mOnlyCore;
3363    }
3364
3365    @Override
3366    public boolean isUpgrade() {
3367        // allow instant applications
3368        // The system property allows testing ota flow when upgraded to the same image.
3369        return mIsUpgrade || SystemProperties.getBoolean(
3370                "persist.pm.mock-upgrade", false /* default */);
3371    }
3372
3373    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3374        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3375
3376        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3377                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3378                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3379        if (matches.size() == 1) {
3380            return matches.get(0).getComponentInfo().packageName;
3381        } else if (matches.size() == 0) {
3382            Log.e(TAG, "There should probably be a verifier, but, none were found");
3383            return null;
3384        }
3385        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3386    }
3387
3388    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3389        synchronized (mPackages) {
3390            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3391            if (libraryEntry == null) {
3392                throw new IllegalStateException("Missing required shared library:" + name);
3393            }
3394            return libraryEntry.apk;
3395        }
3396    }
3397
3398    private @NonNull String getRequiredInstallerLPr() {
3399        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3400        intent.addCategory(Intent.CATEGORY_DEFAULT);
3401        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3402
3403        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3404                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3405                UserHandle.USER_SYSTEM);
3406        if (matches.size() == 1) {
3407            ResolveInfo resolveInfo = matches.get(0);
3408            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3409                throw new RuntimeException("The installer must be a privileged app");
3410            }
3411            return matches.get(0).getComponentInfo().packageName;
3412        } else {
3413            throw new RuntimeException("There must be exactly one installer; found " + matches);
3414        }
3415    }
3416
3417    private @NonNull String getRequiredUninstallerLPr() {
3418        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3419        intent.addCategory(Intent.CATEGORY_DEFAULT);
3420        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3421
3422        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3423                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3424                UserHandle.USER_SYSTEM);
3425        if (resolveInfo == null ||
3426                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3427            throw new RuntimeException("There must be exactly one uninstaller; found "
3428                    + resolveInfo);
3429        }
3430        return resolveInfo.getComponentInfo().packageName;
3431    }
3432
3433    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3434        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3435
3436        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3437                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3438                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3439        ResolveInfo best = null;
3440        final int N = matches.size();
3441        for (int i = 0; i < N; i++) {
3442            final ResolveInfo cur = matches.get(i);
3443            final String packageName = cur.getComponentInfo().packageName;
3444            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3445                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3446                continue;
3447            }
3448
3449            if (best == null || cur.priority > best.priority) {
3450                best = cur;
3451            }
3452        }
3453
3454        if (best != null) {
3455            return best.getComponentInfo().getComponentName();
3456        }
3457        Slog.w(TAG, "Intent filter verifier not found");
3458        return null;
3459    }
3460
3461    @Override
3462    public @Nullable ComponentName getInstantAppResolverComponent() {
3463        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3464            return null;
3465        }
3466        synchronized (mPackages) {
3467            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3468            if (instantAppResolver == null) {
3469                return null;
3470            }
3471            return instantAppResolver.first;
3472        }
3473    }
3474
3475    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3476        final String[] packageArray =
3477                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3478        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3481            }
3482            return null;
3483        }
3484
3485        final int callingUid = Binder.getCallingUid();
3486        final int resolveFlags =
3487                MATCH_DIRECT_BOOT_AWARE
3488                | MATCH_DIRECT_BOOT_UNAWARE
3489                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3490        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3491        final Intent resolverIntent = new Intent(actionName);
3492        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3493                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3494        // temporarily look for the old action
3495        if (resolvers.size() == 0) {
3496            if (DEBUG_EPHEMERAL) {
3497                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3498            }
3499            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3500            resolverIntent.setAction(actionName);
3501            resolvers = queryIntentServicesInternal(resolverIntent, null,
3502                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3503        }
3504        final int N = resolvers.size();
3505        if (N == 0) {
3506            if (DEBUG_EPHEMERAL) {
3507                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3508            }
3509            return null;
3510        }
3511
3512        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3513        for (int i = 0; i < N; i++) {
3514            final ResolveInfo info = resolvers.get(i);
3515
3516            if (info.serviceInfo == null) {
3517                continue;
3518            }
3519
3520            final String packageName = info.serviceInfo.packageName;
3521            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3522                if (DEBUG_EPHEMERAL) {
3523                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3524                            + " pkg: " + packageName + ", info:" + info);
3525                }
3526                continue;
3527            }
3528
3529            if (DEBUG_EPHEMERAL) {
3530                Slog.v(TAG, "Ephemeral resolver found;"
3531                        + " pkg: " + packageName + ", info:" + info);
3532            }
3533            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3534        }
3535        if (DEBUG_EPHEMERAL) {
3536            Slog.v(TAG, "Ephemeral resolver NOT found");
3537        }
3538        return null;
3539    }
3540
3541    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3542        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3543        intent.addCategory(Intent.CATEGORY_DEFAULT);
3544        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3545
3546        final int resolveFlags =
3547                MATCH_DIRECT_BOOT_AWARE
3548                | MATCH_DIRECT_BOOT_UNAWARE
3549                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3550        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3551                resolveFlags, UserHandle.USER_SYSTEM);
3552        // temporarily look for the old action
3553        if (matches.isEmpty()) {
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3556            }
3557            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3558            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3559                    resolveFlags, UserHandle.USER_SYSTEM);
3560        }
3561        Iterator<ResolveInfo> iter = matches.iterator();
3562        while (iter.hasNext()) {
3563            final ResolveInfo rInfo = iter.next();
3564            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3565            if (ps != null) {
3566                final PermissionsState permissionsState = ps.getPermissionsState();
3567                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3568                    continue;
3569                }
3570            }
3571            iter.remove();
3572        }
3573        if (matches.size() == 0) {
3574            return null;
3575        } else if (matches.size() == 1) {
3576            return (ActivityInfo) matches.get(0).getComponentInfo();
3577        } else {
3578            throw new RuntimeException(
3579                    "There must be at most one ephemeral installer; found " + matches);
3580        }
3581    }
3582
3583    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3584            @NonNull ComponentName resolver) {
3585        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3586                .addCategory(Intent.CATEGORY_DEFAULT)
3587                .setPackage(resolver.getPackageName());
3588        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3589        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3590                UserHandle.USER_SYSTEM);
3591        // temporarily look for the old action
3592        if (matches.isEmpty()) {
3593            if (DEBUG_EPHEMERAL) {
3594                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3595            }
3596            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3597            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3598                    UserHandle.USER_SYSTEM);
3599        }
3600        if (matches.isEmpty()) {
3601            return null;
3602        }
3603        return matches.get(0).getComponentInfo().getComponentName();
3604    }
3605
3606    private void primeDomainVerificationsLPw(int userId) {
3607        if (DEBUG_DOMAIN_VERIFICATION) {
3608            Slog.d(TAG, "Priming domain verifications in user " + userId);
3609        }
3610
3611        SystemConfig systemConfig = SystemConfig.getInstance();
3612        ArraySet<String> packages = systemConfig.getLinkedApps();
3613
3614        for (String packageName : packages) {
3615            PackageParser.Package pkg = mPackages.get(packageName);
3616            if (pkg != null) {
3617                if (!pkg.isSystemApp()) {
3618                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3619                    continue;
3620                }
3621
3622                ArraySet<String> domains = null;
3623                for (PackageParser.Activity a : pkg.activities) {
3624                    for (ActivityIntentInfo filter : a.intents) {
3625                        if (hasValidDomains(filter)) {
3626                            if (domains == null) {
3627                                domains = new ArraySet<String>();
3628                            }
3629                            domains.addAll(filter.getHostsList());
3630                        }
3631                    }
3632                }
3633
3634                if (domains != null && domains.size() > 0) {
3635                    if (DEBUG_DOMAIN_VERIFICATION) {
3636                        Slog.v(TAG, "      + " + packageName);
3637                    }
3638                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3639                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3640                    // and then 'always' in the per-user state actually used for intent resolution.
3641                    final IntentFilterVerificationInfo ivi;
3642                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3643                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3644                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3645                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3646                } else {
3647                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3648                            + "' does not handle web links");
3649                }
3650            } else {
3651                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3652            }
3653        }
3654
3655        scheduleWritePackageRestrictionsLocked(userId);
3656        scheduleWriteSettingsLocked();
3657    }
3658
3659    private void applyFactoryDefaultBrowserLPw(int userId) {
3660        // The default browser app's package name is stored in a string resource,
3661        // with a product-specific overlay used for vendor customization.
3662        String browserPkg = mContext.getResources().getString(
3663                com.android.internal.R.string.default_browser);
3664        if (!TextUtils.isEmpty(browserPkg)) {
3665            // non-empty string => required to be a known package
3666            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3667            if (ps == null) {
3668                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3669                browserPkg = null;
3670            } else {
3671                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3672            }
3673        }
3674
3675        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3676        // default.  If there's more than one, just leave everything alone.
3677        if (browserPkg == null) {
3678            calculateDefaultBrowserLPw(userId);
3679        }
3680    }
3681
3682    private void calculateDefaultBrowserLPw(int userId) {
3683        List<String> allBrowsers = resolveAllBrowserApps(userId);
3684        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3685        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3686    }
3687
3688    private List<String> resolveAllBrowserApps(int userId) {
3689        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3690        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3691                PackageManager.MATCH_ALL, userId);
3692
3693        final int count = list.size();
3694        List<String> result = new ArrayList<String>(count);
3695        for (int i=0; i<count; i++) {
3696            ResolveInfo info = list.get(i);
3697            if (info.activityInfo == null
3698                    || !info.handleAllWebDataURI
3699                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3700                    || result.contains(info.activityInfo.packageName)) {
3701                continue;
3702            }
3703            result.add(info.activityInfo.packageName);
3704        }
3705
3706        return result;
3707    }
3708
3709    private boolean packageIsBrowser(String packageName, int userId) {
3710        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3711                PackageManager.MATCH_ALL, userId);
3712        final int N = list.size();
3713        for (int i = 0; i < N; i++) {
3714            ResolveInfo info = list.get(i);
3715            if (packageName.equals(info.activityInfo.packageName)) {
3716                return true;
3717            }
3718        }
3719        return false;
3720    }
3721
3722    private void checkDefaultBrowser() {
3723        final int myUserId = UserHandle.myUserId();
3724        final String packageName = getDefaultBrowserPackageName(myUserId);
3725        if (packageName != null) {
3726            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3727            if (info == null) {
3728                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3729                synchronized (mPackages) {
3730                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3731                }
3732            }
3733        }
3734    }
3735
3736    @Override
3737    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3738            throws RemoteException {
3739        try {
3740            return super.onTransact(code, data, reply, flags);
3741        } catch (RuntimeException e) {
3742            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3743                Slog.wtf(TAG, "Package Manager Crash", e);
3744            }
3745            throw e;
3746        }
3747    }
3748
3749    static int[] appendInts(int[] cur, int[] add) {
3750        if (add == null) return cur;
3751        if (cur == null) return add;
3752        final int N = add.length;
3753        for (int i=0; i<N; i++) {
3754            cur = appendInt(cur, add[i]);
3755        }
3756        return cur;
3757    }
3758
3759    /**
3760     * Returns whether or not a full application can see an instant application.
3761     * <p>
3762     * Currently, there are three cases in which this can occur:
3763     * <ol>
3764     * <li>The calling application is a "special" process. The special
3765     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3766     *     and {@code 0}</li>
3767     * <li>The calling application has the permission
3768     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3769     * <li>The calling application is the default launcher on the
3770     *     system partition.</li>
3771     * </ol>
3772     */
3773    private boolean canViewInstantApps(int callingUid, int userId) {
3774        if (callingUid == Process.SYSTEM_UID
3775                || callingUid == Process.SHELL_UID
3776                || callingUid == Process.ROOT_UID) {
3777            return true;
3778        }
3779        if (mContext.checkCallingOrSelfPermission(
3780                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3781            return true;
3782        }
3783        if (mContext.checkCallingOrSelfPermission(
3784                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3785            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3786            if (homeComponent != null
3787                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3788                return true;
3789            }
3790        }
3791        return false;
3792    }
3793
3794    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3795        if (!sUserManager.exists(userId)) return null;
3796        if (ps == null) {
3797            return null;
3798        }
3799        PackageParser.Package p = ps.pkg;
3800        if (p == null) {
3801            return null;
3802        }
3803        final int callingUid = Binder.getCallingUid();
3804        // Filter out ephemeral app metadata:
3805        //   * The system/shell/root can see metadata for any app
3806        //   * An installed app can see metadata for 1) other installed apps
3807        //     and 2) ephemeral apps that have explicitly interacted with it
3808        //   * Ephemeral apps can only see their own data and exposed installed apps
3809        //   * Holding a signature permission allows seeing instant apps
3810        if (filterAppAccessLPr(ps, callingUid, userId)) {
3811            return null;
3812        }
3813
3814        final PermissionsState permissionsState = ps.getPermissionsState();
3815
3816        // Compute GIDs only if requested
3817        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3818                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3819        // Compute granted permissions only if package has requested permissions
3820        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3821                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3822        final PackageUserState state = ps.readUserState(userId);
3823
3824        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3825                && ps.isSystem()) {
3826            flags |= MATCH_ANY_USER;
3827        }
3828
3829        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3830                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3831
3832        if (packageInfo == null) {
3833            return null;
3834        }
3835
3836        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3837                resolveExternalPackageNameLPr(p);
3838
3839        return packageInfo;
3840    }
3841
3842    @Override
3843    public void checkPackageStartable(String packageName, int userId) {
3844        final int callingUid = Binder.getCallingUid();
3845        if (getInstantAppPackageName(callingUid) != null) {
3846            throw new SecurityException("Instant applications don't have access to this method");
3847        }
3848        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3849        synchronized (mPackages) {
3850            final PackageSetting ps = mSettings.mPackages.get(packageName);
3851            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3852                throw new SecurityException("Package " + packageName + " was not found!");
3853            }
3854
3855            if (!ps.getInstalled(userId)) {
3856                throw new SecurityException(
3857                        "Package " + packageName + " was not installed for user " + userId + "!");
3858            }
3859
3860            if (mSafeMode && !ps.isSystem()) {
3861                throw new SecurityException("Package " + packageName + " not a system app!");
3862            }
3863
3864            if (mFrozenPackages.contains(packageName)) {
3865                throw new SecurityException("Package " + packageName + " is currently frozen!");
3866            }
3867
3868            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3869                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3870            }
3871        }
3872    }
3873
3874    @Override
3875    public boolean isPackageAvailable(String packageName, int userId) {
3876        if (!sUserManager.exists(userId)) return false;
3877        final int callingUid = Binder.getCallingUid();
3878        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3879                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3880        synchronized (mPackages) {
3881            PackageParser.Package p = mPackages.get(packageName);
3882            if (p != null) {
3883                final PackageSetting ps = (PackageSetting) p.mExtras;
3884                if (filterAppAccessLPr(ps, callingUid, userId)) {
3885                    return false;
3886                }
3887                if (ps != null) {
3888                    final PackageUserState state = ps.readUserState(userId);
3889                    if (state != null) {
3890                        return PackageParser.isAvailable(state);
3891                    }
3892                }
3893            }
3894        }
3895        return false;
3896    }
3897
3898    @Override
3899    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3900        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3901                flags, Binder.getCallingUid(), userId);
3902    }
3903
3904    @Override
3905    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3906            int flags, int userId) {
3907        return getPackageInfoInternal(versionedPackage.getPackageName(),
3908                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3909    }
3910
3911    /**
3912     * Important: The provided filterCallingUid is used exclusively to filter out packages
3913     * that can be seen based on user state. It's typically the original caller uid prior
3914     * to clearing. Because it can only be provided by trusted code, it's value can be
3915     * trusted and will be used as-is; unlike userId which will be validated by this method.
3916     */
3917    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3918            int flags, int filterCallingUid, int userId) {
3919        if (!sUserManager.exists(userId)) return null;
3920        flags = updateFlagsForPackage(flags, userId, packageName);
3921        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3922                false /* requireFullPermission */, false /* checkShell */, "get package info");
3923
3924        // reader
3925        synchronized (mPackages) {
3926            // Normalize package name to handle renamed packages and static libs
3927            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3928
3929            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3930            if (matchFactoryOnly) {
3931                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3932                if (ps != null) {
3933                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3934                        return null;
3935                    }
3936                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3937                        return null;
3938                    }
3939                    return generatePackageInfo(ps, flags, userId);
3940                }
3941            }
3942
3943            PackageParser.Package p = mPackages.get(packageName);
3944            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3945                return null;
3946            }
3947            if (DEBUG_PACKAGE_INFO)
3948                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3949            if (p != null) {
3950                final PackageSetting ps = (PackageSetting) p.mExtras;
3951                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3952                    return null;
3953                }
3954                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3955                    return null;
3956                }
3957                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3958            }
3959            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3960                final PackageSetting ps = mSettings.mPackages.get(packageName);
3961                if (ps == null) return null;
3962                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3963                    return null;
3964                }
3965                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3966                    return null;
3967                }
3968                return generatePackageInfo(ps, flags, userId);
3969            }
3970        }
3971        return null;
3972    }
3973
3974    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3975        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3976            return true;
3977        }
3978        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3979            return true;
3980        }
3981        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3982            return true;
3983        }
3984        return false;
3985    }
3986
3987    private boolean isComponentVisibleToInstantApp(
3988            @Nullable ComponentName component, @ComponentType int type) {
3989        if (type == TYPE_ACTIVITY) {
3990            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3991            return activity != null
3992                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3993                    : false;
3994        } else if (type == TYPE_RECEIVER) {
3995            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3996            return activity != null
3997                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3998                    : false;
3999        } else if (type == TYPE_SERVICE) {
4000            final PackageParser.Service service = mServices.mServices.get(component);
4001            return service != null
4002                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4003                    : false;
4004        } else if (type == TYPE_PROVIDER) {
4005            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4006            return provider != null
4007                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4008                    : false;
4009        } else if (type == TYPE_UNKNOWN) {
4010            return isComponentVisibleToInstantApp(component);
4011        }
4012        return false;
4013    }
4014
4015    /**
4016     * Returns whether or not access to the application should be filtered.
4017     * <p>
4018     * Access may be limited based upon whether the calling or target applications
4019     * are instant applications.
4020     *
4021     * @see #canAccessInstantApps(int)
4022     */
4023    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4024            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4025        // if we're in an isolated process, get the real calling UID
4026        if (Process.isIsolated(callingUid)) {
4027            callingUid = mIsolatedOwners.get(callingUid);
4028        }
4029        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4030        final boolean callerIsInstantApp = instantAppPkgName != null;
4031        if (ps == null) {
4032            if (callerIsInstantApp) {
4033                // pretend the application exists, but, needs to be filtered
4034                return true;
4035            }
4036            return false;
4037        }
4038        // if the target and caller are the same application, don't filter
4039        if (isCallerSameApp(ps.name, callingUid)) {
4040            return false;
4041        }
4042        if (callerIsInstantApp) {
4043            // request for a specific component; if it hasn't been explicitly exposed, filter
4044            if (component != null) {
4045                return !isComponentVisibleToInstantApp(component, componentType);
4046            }
4047            // request for application; if no components have been explicitly exposed, filter
4048            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4049        }
4050        if (ps.getInstantApp(userId)) {
4051            // caller can see all components of all instant applications, don't filter
4052            if (canViewInstantApps(callingUid, userId)) {
4053                return false;
4054            }
4055            // request for a specific instant application component, filter
4056            if (component != null) {
4057                return true;
4058            }
4059            // request for an instant application; if the caller hasn't been granted access, filter
4060            return !mInstantAppRegistry.isInstantAccessGranted(
4061                    userId, UserHandle.getAppId(callingUid), ps.appId);
4062        }
4063        return false;
4064    }
4065
4066    /**
4067     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4068     */
4069    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4070        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4071    }
4072
4073    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4074            int flags) {
4075        // Callers can access only the libs they depend on, otherwise they need to explicitly
4076        // ask for the shared libraries given the caller is allowed to access all static libs.
4077        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4078            // System/shell/root get to see all static libs
4079            final int appId = UserHandle.getAppId(uid);
4080            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4081                    || appId == Process.ROOT_UID) {
4082                return false;
4083            }
4084        }
4085
4086        // No package means no static lib as it is always on internal storage
4087        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4088            return false;
4089        }
4090
4091        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4092                ps.pkg.staticSharedLibVersion);
4093        if (libEntry == null) {
4094            return false;
4095        }
4096
4097        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4098        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4099        if (uidPackageNames == null) {
4100            return true;
4101        }
4102
4103        for (String uidPackageName : uidPackageNames) {
4104            if (ps.name.equals(uidPackageName)) {
4105                return false;
4106            }
4107            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4108            if (uidPs != null) {
4109                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4110                        libEntry.info.getName());
4111                if (index < 0) {
4112                    continue;
4113                }
4114                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4115                    return false;
4116                }
4117            }
4118        }
4119        return true;
4120    }
4121
4122    @Override
4123    public String[] currentToCanonicalPackageNames(String[] names) {
4124        final int callingUid = Binder.getCallingUid();
4125        if (getInstantAppPackageName(callingUid) != null) {
4126            return names;
4127        }
4128        final String[] out = new String[names.length];
4129        // reader
4130        synchronized (mPackages) {
4131            final int callingUserId = UserHandle.getUserId(callingUid);
4132            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4133            for (int i=names.length-1; i>=0; i--) {
4134                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4135                boolean translateName = false;
4136                if (ps != null && ps.realName != null) {
4137                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4138                    translateName = !targetIsInstantApp
4139                            || canViewInstantApps
4140                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4141                                    UserHandle.getAppId(callingUid), ps.appId);
4142                }
4143                out[i] = translateName ? ps.realName : names[i];
4144            }
4145        }
4146        return out;
4147    }
4148
4149    @Override
4150    public String[] canonicalToCurrentPackageNames(String[] names) {
4151        final int callingUid = Binder.getCallingUid();
4152        if (getInstantAppPackageName(callingUid) != null) {
4153            return names;
4154        }
4155        final String[] out = new String[names.length];
4156        // reader
4157        synchronized (mPackages) {
4158            final int callingUserId = UserHandle.getUserId(callingUid);
4159            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4160            for (int i=names.length-1; i>=0; i--) {
4161                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4162                boolean translateName = false;
4163                if (cur != null) {
4164                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4165                    final boolean targetIsInstantApp =
4166                            ps != null && ps.getInstantApp(callingUserId);
4167                    translateName = !targetIsInstantApp
4168                            || canViewInstantApps
4169                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4170                                    UserHandle.getAppId(callingUid), ps.appId);
4171                }
4172                out[i] = translateName ? cur : names[i];
4173            }
4174        }
4175        return out;
4176    }
4177
4178    @Override
4179    public int getPackageUid(String packageName, int flags, int userId) {
4180        if (!sUserManager.exists(userId)) return -1;
4181        final int callingUid = Binder.getCallingUid();
4182        flags = updateFlagsForPackage(flags, userId, packageName);
4183        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4184                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4185
4186        // reader
4187        synchronized (mPackages) {
4188            final PackageParser.Package p = mPackages.get(packageName);
4189            if (p != null && p.isMatch(flags)) {
4190                PackageSetting ps = (PackageSetting) p.mExtras;
4191                if (filterAppAccessLPr(ps, callingUid, userId)) {
4192                    return -1;
4193                }
4194                return UserHandle.getUid(userId, p.applicationInfo.uid);
4195            }
4196            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4197                final PackageSetting ps = mSettings.mPackages.get(packageName);
4198                if (ps != null && ps.isMatch(flags)
4199                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4200                    return UserHandle.getUid(userId, ps.appId);
4201                }
4202            }
4203        }
4204
4205        return -1;
4206    }
4207
4208    @Override
4209    public int[] getPackageGids(String packageName, int flags, int userId) {
4210        if (!sUserManager.exists(userId)) return null;
4211        final int callingUid = Binder.getCallingUid();
4212        flags = updateFlagsForPackage(flags, userId, packageName);
4213        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4214                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4215
4216        // reader
4217        synchronized (mPackages) {
4218            final PackageParser.Package p = mPackages.get(packageName);
4219            if (p != null && p.isMatch(flags)) {
4220                PackageSetting ps = (PackageSetting) p.mExtras;
4221                if (filterAppAccessLPr(ps, callingUid, userId)) {
4222                    return null;
4223                }
4224                // TODO: Shouldn't this be checking for package installed state for userId and
4225                // return null?
4226                return ps.getPermissionsState().computeGids(userId);
4227            }
4228            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4229                final PackageSetting ps = mSettings.mPackages.get(packageName);
4230                if (ps != null && ps.isMatch(flags)
4231                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4232                    return ps.getPermissionsState().computeGids(userId);
4233                }
4234            }
4235        }
4236
4237        return null;
4238    }
4239
4240    @Override
4241    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4242        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4243    }
4244
4245    @Override
4246    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4247            int flags) {
4248        // TODO Move this to PermissionManager when mPermissionGroups is moved there
4249        synchronized (mPackages) {
4250            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4251                // This is thrown as NameNotFoundException
4252                return null;
4253            }
4254        }
4255        return new ParceledListSlice<>(
4256                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()));
4257    }
4258
4259    @Override
4260    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4261        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4262            return null;
4263        }
4264        // reader
4265        synchronized (mPackages) {
4266            return PackageParser.generatePermissionGroupInfo(
4267                    mPermissionGroups.get(name), flags);
4268        }
4269    }
4270
4271    @Override
4272    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4273        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4274            return ParceledListSlice.emptyList();
4275        }
4276        // reader
4277        synchronized (mPackages) {
4278            final int N = mPermissionGroups.size();
4279            ArrayList<PermissionGroupInfo> out
4280                    = new ArrayList<PermissionGroupInfo>(N);
4281            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4282                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4283            }
4284            return new ParceledListSlice<>(out);
4285        }
4286    }
4287
4288    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4289            int filterCallingUid, int userId) {
4290        if (!sUserManager.exists(userId)) return null;
4291        PackageSetting ps = mSettings.mPackages.get(packageName);
4292        if (ps != null) {
4293            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4294                return null;
4295            }
4296            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4297                return null;
4298            }
4299            if (ps.pkg == null) {
4300                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4301                if (pInfo != null) {
4302                    return pInfo.applicationInfo;
4303                }
4304                return null;
4305            }
4306            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4307                    ps.readUserState(userId), userId);
4308            if (ai != null) {
4309                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4310            }
4311            return ai;
4312        }
4313        return null;
4314    }
4315
4316    @Override
4317    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4318        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4319    }
4320
4321    /**
4322     * Important: The provided filterCallingUid is used exclusively to filter out applications
4323     * that can be seen based on user state. It's typically the original caller uid prior
4324     * to clearing. Because it can only be provided by trusted code, it's value can be
4325     * trusted and will be used as-is; unlike userId which will be validated by this method.
4326     */
4327    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4328            int filterCallingUid, int userId) {
4329        if (!sUserManager.exists(userId)) return null;
4330        flags = updateFlagsForApplication(flags, userId, packageName);
4331        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4332                false /* requireFullPermission */, false /* checkShell */, "get application info");
4333
4334        // writer
4335        synchronized (mPackages) {
4336            // Normalize package name to handle renamed packages and static libs
4337            packageName = resolveInternalPackageNameLPr(packageName,
4338                    PackageManager.VERSION_CODE_HIGHEST);
4339
4340            PackageParser.Package p = mPackages.get(packageName);
4341            if (DEBUG_PACKAGE_INFO) Log.v(
4342                    TAG, "getApplicationInfo " + packageName
4343                    + ": " + p);
4344            if (p != null) {
4345                PackageSetting ps = mSettings.mPackages.get(packageName);
4346                if (ps == null) return null;
4347                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4348                    return null;
4349                }
4350                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4351                    return null;
4352                }
4353                // Note: isEnabledLP() does not apply here - always return info
4354                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4355                        p, flags, ps.readUserState(userId), userId);
4356                if (ai != null) {
4357                    ai.packageName = resolveExternalPackageNameLPr(p);
4358                }
4359                return ai;
4360            }
4361            if ("android".equals(packageName)||"system".equals(packageName)) {
4362                return mAndroidApplication;
4363            }
4364            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4365                // Already generates the external package name
4366                return generateApplicationInfoFromSettingsLPw(packageName,
4367                        flags, filterCallingUid, userId);
4368            }
4369        }
4370        return null;
4371    }
4372
4373    private String normalizePackageNameLPr(String packageName) {
4374        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4375        return normalizedPackageName != null ? normalizedPackageName : packageName;
4376    }
4377
4378    @Override
4379    public void deletePreloadsFileCache() {
4380        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4381            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4382        }
4383        File dir = Environment.getDataPreloadsFileCacheDirectory();
4384        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4385        FileUtils.deleteContents(dir);
4386    }
4387
4388    @Override
4389    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4390            final int storageFlags, final IPackageDataObserver observer) {
4391        mContext.enforceCallingOrSelfPermission(
4392                android.Manifest.permission.CLEAR_APP_CACHE, null);
4393        mHandler.post(() -> {
4394            boolean success = false;
4395            try {
4396                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4397                success = true;
4398            } catch (IOException e) {
4399                Slog.w(TAG, e);
4400            }
4401            if (observer != null) {
4402                try {
4403                    observer.onRemoveCompleted(null, success);
4404                } catch (RemoteException e) {
4405                    Slog.w(TAG, e);
4406                }
4407            }
4408        });
4409    }
4410
4411    @Override
4412    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4413            final int storageFlags, final IntentSender pi) {
4414        mContext.enforceCallingOrSelfPermission(
4415                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4416        mHandler.post(() -> {
4417            boolean success = false;
4418            try {
4419                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4420                success = true;
4421            } catch (IOException e) {
4422                Slog.w(TAG, e);
4423            }
4424            if (pi != null) {
4425                try {
4426                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4427                } catch (SendIntentException e) {
4428                    Slog.w(TAG, e);
4429                }
4430            }
4431        });
4432    }
4433
4434    /**
4435     * Blocking call to clear various types of cached data across the system
4436     * until the requested bytes are available.
4437     */
4438    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4439        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4440        final File file = storage.findPathForUuid(volumeUuid);
4441        if (file.getUsableSpace() >= bytes) return;
4442
4443        if (ENABLE_FREE_CACHE_V2) {
4444            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4445                    volumeUuid);
4446            final boolean aggressive = (storageFlags
4447                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4448            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4449
4450            // 1. Pre-flight to determine if we have any chance to succeed
4451            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4452            if (internalVolume && (aggressive || SystemProperties
4453                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4454                deletePreloadsFileCache();
4455                if (file.getUsableSpace() >= bytes) return;
4456            }
4457
4458            // 3. Consider parsed APK data (aggressive only)
4459            if (internalVolume && aggressive) {
4460                FileUtils.deleteContents(mCacheDir);
4461                if (file.getUsableSpace() >= bytes) return;
4462            }
4463
4464            // 4. Consider cached app data (above quotas)
4465            try {
4466                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4467                        Installer.FLAG_FREE_CACHE_V2);
4468            } catch (InstallerException ignored) {
4469            }
4470            if (file.getUsableSpace() >= bytes) return;
4471
4472            // 5. Consider shared libraries with refcount=0 and age>min cache period
4473            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4474                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4475                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4476                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4477                return;
4478            }
4479
4480            // 6. Consider dexopt output (aggressive only)
4481            // TODO: Implement
4482
4483            // 7. Consider installed instant apps unused longer than min cache period
4484            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4485                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4486                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4487                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4488                return;
4489            }
4490
4491            // 8. Consider cached app data (below quotas)
4492            try {
4493                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4494                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4495            } catch (InstallerException ignored) {
4496            }
4497            if (file.getUsableSpace() >= bytes) return;
4498
4499            // 9. Consider DropBox entries
4500            // TODO: Implement
4501
4502            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4503            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4504                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4505                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4506                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4507                return;
4508            }
4509        } else {
4510            try {
4511                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4512            } catch (InstallerException ignored) {
4513            }
4514            if (file.getUsableSpace() >= bytes) return;
4515        }
4516
4517        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4518    }
4519
4520    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4521            throws IOException {
4522        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4523        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4524
4525        List<VersionedPackage> packagesToDelete = null;
4526        final long now = System.currentTimeMillis();
4527
4528        synchronized (mPackages) {
4529            final int[] allUsers = sUserManager.getUserIds();
4530            final int libCount = mSharedLibraries.size();
4531            for (int i = 0; i < libCount; i++) {
4532                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4533                if (versionedLib == null) {
4534                    continue;
4535                }
4536                final int versionCount = versionedLib.size();
4537                for (int j = 0; j < versionCount; j++) {
4538                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4539                    // Skip packages that are not static shared libs.
4540                    if (!libInfo.isStatic()) {
4541                        break;
4542                    }
4543                    // Important: We skip static shared libs used for some user since
4544                    // in such a case we need to keep the APK on the device. The check for
4545                    // a lib being used for any user is performed by the uninstall call.
4546                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4547                    // Resolve the package name - we use synthetic package names internally
4548                    final String internalPackageName = resolveInternalPackageNameLPr(
4549                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4550                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4551                    // Skip unused static shared libs cached less than the min period
4552                    // to prevent pruning a lib needed by a subsequently installed package.
4553                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4554                        continue;
4555                    }
4556                    if (packagesToDelete == null) {
4557                        packagesToDelete = new ArrayList<>();
4558                    }
4559                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4560                            declaringPackage.getVersionCode()));
4561                }
4562            }
4563        }
4564
4565        if (packagesToDelete != null) {
4566            final int packageCount = packagesToDelete.size();
4567            for (int i = 0; i < packageCount; i++) {
4568                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4569                // Delete the package synchronously (will fail of the lib used for any user).
4570                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4571                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4572                                == PackageManager.DELETE_SUCCEEDED) {
4573                    if (volume.getUsableSpace() >= neededSpace) {
4574                        return true;
4575                    }
4576                }
4577            }
4578        }
4579
4580        return false;
4581    }
4582
4583    /**
4584     * Update given flags based on encryption status of current user.
4585     */
4586    private int updateFlags(int flags, int userId) {
4587        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4588                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4589            // Caller expressed an explicit opinion about what encryption
4590            // aware/unaware components they want to see, so fall through and
4591            // give them what they want
4592        } else {
4593            // Caller expressed no opinion, so match based on user state
4594            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4595                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4596            } else {
4597                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4598            }
4599        }
4600        return flags;
4601    }
4602
4603    private UserManagerInternal getUserManagerInternal() {
4604        if (mUserManagerInternal == null) {
4605            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4606        }
4607        return mUserManagerInternal;
4608    }
4609
4610    private DeviceIdleController.LocalService getDeviceIdleController() {
4611        if (mDeviceIdleController == null) {
4612            mDeviceIdleController =
4613                    LocalServices.getService(DeviceIdleController.LocalService.class);
4614        }
4615        return mDeviceIdleController;
4616    }
4617
4618    /**
4619     * Update given flags when being used to request {@link PackageInfo}.
4620     */
4621    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4622        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4623        boolean triaged = true;
4624        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4625                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4626            // Caller is asking for component details, so they'd better be
4627            // asking for specific encryption matching behavior, or be triaged
4628            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4629                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4630                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4631                triaged = false;
4632            }
4633        }
4634        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4635                | PackageManager.MATCH_SYSTEM_ONLY
4636                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4637            triaged = false;
4638        }
4639        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4640            mPermissionManager.enforceCrossUserPermission(
4641                    Binder.getCallingUid(), userId, false, false,
4642                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4643                    + Debug.getCallers(5));
4644        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4645                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4646            // If the caller wants all packages and has a restricted profile associated with it,
4647            // then match all users. This is to make sure that launchers that need to access work
4648            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4649            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4650            flags |= PackageManager.MATCH_ANY_USER;
4651        }
4652        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4653            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4654                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4655        }
4656        return updateFlags(flags, userId);
4657    }
4658
4659    /**
4660     * Update given flags when being used to request {@link ApplicationInfo}.
4661     */
4662    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4663        return updateFlagsForPackage(flags, userId, cookie);
4664    }
4665
4666    /**
4667     * Update given flags when being used to request {@link ComponentInfo}.
4668     */
4669    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4670        if (cookie instanceof Intent) {
4671            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4672                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4673            }
4674        }
4675
4676        boolean triaged = true;
4677        // Caller is asking for component details, so they'd better be
4678        // asking for specific encryption matching behavior, or be triaged
4679        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4680                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4681                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4682            triaged = false;
4683        }
4684        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4685            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4686                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4687        }
4688
4689        return updateFlags(flags, userId);
4690    }
4691
4692    /**
4693     * Update given intent when being used to request {@link ResolveInfo}.
4694     */
4695    private Intent updateIntentForResolve(Intent intent) {
4696        if (intent.getSelector() != null) {
4697            intent = intent.getSelector();
4698        }
4699        if (DEBUG_PREFERRED) {
4700            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4701        }
4702        return intent;
4703    }
4704
4705    /**
4706     * Update given flags when being used to request {@link ResolveInfo}.
4707     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4708     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4709     * flag set. However, this flag is only honoured in three circumstances:
4710     * <ul>
4711     * <li>when called from a system process</li>
4712     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4713     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4714     * action and a {@code android.intent.category.BROWSABLE} category</li>
4715     * </ul>
4716     */
4717    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4718        return updateFlagsForResolve(flags, userId, intent, callingUid,
4719                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4720    }
4721    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4722            boolean wantInstantApps) {
4723        return updateFlagsForResolve(flags, userId, intent, callingUid,
4724                wantInstantApps, false /*onlyExposedExplicitly*/);
4725    }
4726    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4727            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4728        // Safe mode means we shouldn't match any third-party components
4729        if (mSafeMode) {
4730            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4731        }
4732        if (getInstantAppPackageName(callingUid) != null) {
4733            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4734            if (onlyExposedExplicitly) {
4735                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4736            }
4737            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4738            flags |= PackageManager.MATCH_INSTANT;
4739        } else {
4740            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4741            final boolean allowMatchInstant =
4742                    (wantInstantApps
4743                            && Intent.ACTION_VIEW.equals(intent.getAction())
4744                            && hasWebURI(intent))
4745                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4746            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4747                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4748            if (!allowMatchInstant) {
4749                flags &= ~PackageManager.MATCH_INSTANT;
4750            }
4751        }
4752        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4753    }
4754
4755    @Override
4756    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4757        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4758    }
4759
4760    /**
4761     * Important: The provided filterCallingUid is used exclusively to filter out activities
4762     * that can be seen based on user state. It's typically the original caller uid prior
4763     * to clearing. Because it can only be provided by trusted code, it's value can be
4764     * trusted and will be used as-is; unlike userId which will be validated by this method.
4765     */
4766    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4767            int filterCallingUid, int userId) {
4768        if (!sUserManager.exists(userId)) return null;
4769        flags = updateFlagsForComponent(flags, userId, component);
4770        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4771                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4772        synchronized (mPackages) {
4773            PackageParser.Activity a = mActivities.mActivities.get(component);
4774
4775            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4776            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4777                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4778                if (ps == null) return null;
4779                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4780                    return null;
4781                }
4782                return PackageParser.generateActivityInfo(
4783                        a, flags, ps.readUserState(userId), userId);
4784            }
4785            if (mResolveComponentName.equals(component)) {
4786                return PackageParser.generateActivityInfo(
4787                        mResolveActivity, flags, new PackageUserState(), userId);
4788            }
4789        }
4790        return null;
4791    }
4792
4793    @Override
4794    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4795            String resolvedType) {
4796        synchronized (mPackages) {
4797            if (component.equals(mResolveComponentName)) {
4798                // The resolver supports EVERYTHING!
4799                return true;
4800            }
4801            final int callingUid = Binder.getCallingUid();
4802            final int callingUserId = UserHandle.getUserId(callingUid);
4803            PackageParser.Activity a = mActivities.mActivities.get(component);
4804            if (a == null) {
4805                return false;
4806            }
4807            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4808            if (ps == null) {
4809                return false;
4810            }
4811            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4812                return false;
4813            }
4814            for (int i=0; i<a.intents.size(); i++) {
4815                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4816                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4817                    return true;
4818                }
4819            }
4820            return false;
4821        }
4822    }
4823
4824    @Override
4825    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4826        if (!sUserManager.exists(userId)) return null;
4827        final int callingUid = Binder.getCallingUid();
4828        flags = updateFlagsForComponent(flags, userId, component);
4829        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4830                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4831        synchronized (mPackages) {
4832            PackageParser.Activity a = mReceivers.mActivities.get(component);
4833            if (DEBUG_PACKAGE_INFO) Log.v(
4834                TAG, "getReceiverInfo " + component + ": " + a);
4835            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4836                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4837                if (ps == null) return null;
4838                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4839                    return null;
4840                }
4841                return PackageParser.generateActivityInfo(
4842                        a, flags, ps.readUserState(userId), userId);
4843            }
4844        }
4845        return null;
4846    }
4847
4848    @Override
4849    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4850            int flags, int userId) {
4851        if (!sUserManager.exists(userId)) return null;
4852        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4853        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4854            return null;
4855        }
4856
4857        flags = updateFlagsForPackage(flags, userId, null);
4858
4859        final boolean canSeeStaticLibraries =
4860                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4861                        == PERMISSION_GRANTED
4862                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4863                        == PERMISSION_GRANTED
4864                || canRequestPackageInstallsInternal(packageName,
4865                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4866                        false  /* throwIfPermNotDeclared*/)
4867                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4868                        == PERMISSION_GRANTED;
4869
4870        synchronized (mPackages) {
4871            List<SharedLibraryInfo> result = null;
4872
4873            final int libCount = mSharedLibraries.size();
4874            for (int i = 0; i < libCount; i++) {
4875                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4876                if (versionedLib == null) {
4877                    continue;
4878                }
4879
4880                final int versionCount = versionedLib.size();
4881                for (int j = 0; j < versionCount; j++) {
4882                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4883                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4884                        break;
4885                    }
4886                    final long identity = Binder.clearCallingIdentity();
4887                    try {
4888                        PackageInfo packageInfo = getPackageInfoVersioned(
4889                                libInfo.getDeclaringPackage(), flags
4890                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4891                        if (packageInfo == null) {
4892                            continue;
4893                        }
4894                    } finally {
4895                        Binder.restoreCallingIdentity(identity);
4896                    }
4897
4898                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4899                            libInfo.getVersion(), libInfo.getType(),
4900                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4901                            flags, userId));
4902
4903                    if (result == null) {
4904                        result = new ArrayList<>();
4905                    }
4906                    result.add(resLibInfo);
4907                }
4908            }
4909
4910            return result != null ? new ParceledListSlice<>(result) : null;
4911        }
4912    }
4913
4914    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4915            SharedLibraryInfo libInfo, int flags, int userId) {
4916        List<VersionedPackage> versionedPackages = null;
4917        final int packageCount = mSettings.mPackages.size();
4918        for (int i = 0; i < packageCount; i++) {
4919            PackageSetting ps = mSettings.mPackages.valueAt(i);
4920
4921            if (ps == null) {
4922                continue;
4923            }
4924
4925            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4926                continue;
4927            }
4928
4929            final String libName = libInfo.getName();
4930            if (libInfo.isStatic()) {
4931                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4932                if (libIdx < 0) {
4933                    continue;
4934                }
4935                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4936                    continue;
4937                }
4938                if (versionedPackages == null) {
4939                    versionedPackages = new ArrayList<>();
4940                }
4941                // If the dependent is a static shared lib, use the public package name
4942                String dependentPackageName = ps.name;
4943                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4944                    dependentPackageName = ps.pkg.manifestPackageName;
4945                }
4946                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4947            } else if (ps.pkg != null) {
4948                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4949                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4950                    if (versionedPackages == null) {
4951                        versionedPackages = new ArrayList<>();
4952                    }
4953                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4954                }
4955            }
4956        }
4957
4958        return versionedPackages;
4959    }
4960
4961    @Override
4962    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4963        if (!sUserManager.exists(userId)) return null;
4964        final int callingUid = Binder.getCallingUid();
4965        flags = updateFlagsForComponent(flags, userId, component);
4966        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4967                false /* requireFullPermission */, false /* checkShell */, "get service info");
4968        synchronized (mPackages) {
4969            PackageParser.Service s = mServices.mServices.get(component);
4970            if (DEBUG_PACKAGE_INFO) Log.v(
4971                TAG, "getServiceInfo " + component + ": " + s);
4972            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4973                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4974                if (ps == null) return null;
4975                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4976                    return null;
4977                }
4978                return PackageParser.generateServiceInfo(
4979                        s, flags, ps.readUserState(userId), userId);
4980            }
4981        }
4982        return null;
4983    }
4984
4985    @Override
4986    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4987        if (!sUserManager.exists(userId)) return null;
4988        final int callingUid = Binder.getCallingUid();
4989        flags = updateFlagsForComponent(flags, userId, component);
4990        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4991                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4992        synchronized (mPackages) {
4993            PackageParser.Provider p = mProviders.mProviders.get(component);
4994            if (DEBUG_PACKAGE_INFO) Log.v(
4995                TAG, "getProviderInfo " + component + ": " + p);
4996            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4997                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4998                if (ps == null) return null;
4999                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5000                    return null;
5001                }
5002                return PackageParser.generateProviderInfo(
5003                        p, flags, ps.readUserState(userId), userId);
5004            }
5005        }
5006        return null;
5007    }
5008
5009    @Override
5010    public String[] getSystemSharedLibraryNames() {
5011        // allow instant applications
5012        synchronized (mPackages) {
5013            Set<String> libs = null;
5014            final int libCount = mSharedLibraries.size();
5015            for (int i = 0; i < libCount; i++) {
5016                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5017                if (versionedLib == null) {
5018                    continue;
5019                }
5020                final int versionCount = versionedLib.size();
5021                for (int j = 0; j < versionCount; j++) {
5022                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5023                    if (!libEntry.info.isStatic()) {
5024                        if (libs == null) {
5025                            libs = new ArraySet<>();
5026                        }
5027                        libs.add(libEntry.info.getName());
5028                        break;
5029                    }
5030                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5031                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5032                            UserHandle.getUserId(Binder.getCallingUid()),
5033                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5034                        if (libs == null) {
5035                            libs = new ArraySet<>();
5036                        }
5037                        libs.add(libEntry.info.getName());
5038                        break;
5039                    }
5040                }
5041            }
5042
5043            if (libs != null) {
5044                String[] libsArray = new String[libs.size()];
5045                libs.toArray(libsArray);
5046                return libsArray;
5047            }
5048
5049            return null;
5050        }
5051    }
5052
5053    @Override
5054    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5055        // allow instant applications
5056        synchronized (mPackages) {
5057            return mServicesSystemSharedLibraryPackageName;
5058        }
5059    }
5060
5061    @Override
5062    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5063        // allow instant applications
5064        synchronized (mPackages) {
5065            return mSharedSystemSharedLibraryPackageName;
5066        }
5067    }
5068
5069    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5070        for (int i = userList.length - 1; i >= 0; --i) {
5071            final int userId = userList[i];
5072            // don't add instant app to the list of updates
5073            if (pkgSetting.getInstantApp(userId)) {
5074                continue;
5075            }
5076            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5077            if (changedPackages == null) {
5078                changedPackages = new SparseArray<>();
5079                mChangedPackages.put(userId, changedPackages);
5080            }
5081            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5082            if (sequenceNumbers == null) {
5083                sequenceNumbers = new HashMap<>();
5084                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5085            }
5086            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5087            if (sequenceNumber != null) {
5088                changedPackages.remove(sequenceNumber);
5089            }
5090            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5091            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5092        }
5093        mChangedPackagesSequenceNumber++;
5094    }
5095
5096    @Override
5097    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5098        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5099            return null;
5100        }
5101        synchronized (mPackages) {
5102            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5103                return null;
5104            }
5105            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5106            if (changedPackages == null) {
5107                return null;
5108            }
5109            final List<String> packageNames =
5110                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5111            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5112                final String packageName = changedPackages.get(i);
5113                if (packageName != null) {
5114                    packageNames.add(packageName);
5115                }
5116            }
5117            return packageNames.isEmpty()
5118                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5124        // allow instant applications
5125        ArrayList<FeatureInfo> res;
5126        synchronized (mAvailableFeatures) {
5127            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5128            res.addAll(mAvailableFeatures.values());
5129        }
5130        final FeatureInfo fi = new FeatureInfo();
5131        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5132                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5133        res.add(fi);
5134
5135        return new ParceledListSlice<>(res);
5136    }
5137
5138    @Override
5139    public boolean hasSystemFeature(String name, int version) {
5140        // allow instant applications
5141        synchronized (mAvailableFeatures) {
5142            final FeatureInfo feat = mAvailableFeatures.get(name);
5143            if (feat == null) {
5144                return false;
5145            } else {
5146                return feat.version >= version;
5147            }
5148        }
5149    }
5150
5151    @Override
5152    public int checkPermission(String permName, String pkgName, int userId) {
5153        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5154    }
5155
5156    @Override
5157    public int checkUidPermission(String permName, int uid) {
5158        final int callingUid = Binder.getCallingUid();
5159        final int callingUserId = UserHandle.getUserId(callingUid);
5160        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5161        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5162        final int userId = UserHandle.getUserId(uid);
5163        if (!sUserManager.exists(userId)) {
5164            return PackageManager.PERMISSION_DENIED;
5165        }
5166
5167        synchronized (mPackages) {
5168            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5169            if (obj != null) {
5170                if (obj instanceof SharedUserSetting) {
5171                    if (isCallerInstantApp) {
5172                        return PackageManager.PERMISSION_DENIED;
5173                    }
5174                } else if (obj instanceof PackageSetting) {
5175                    final PackageSetting ps = (PackageSetting) obj;
5176                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5177                        return PackageManager.PERMISSION_DENIED;
5178                    }
5179                }
5180                final SettingBase settingBase = (SettingBase) obj;
5181                final PermissionsState permissionsState = settingBase.getPermissionsState();
5182                if (permissionsState.hasPermission(permName, userId)) {
5183                    if (isUidInstantApp) {
5184                        if (mSettings.mPermissions.isPermissionInstant(permName)) {
5185                            return PackageManager.PERMISSION_GRANTED;
5186                        }
5187                    } else {
5188                        return PackageManager.PERMISSION_GRANTED;
5189                    }
5190                }
5191                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5192                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5193                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5194                    return PackageManager.PERMISSION_GRANTED;
5195                }
5196            } else {
5197                ArraySet<String> perms = mSystemPermissions.get(uid);
5198                if (perms != null) {
5199                    if (perms.contains(permName)) {
5200                        return PackageManager.PERMISSION_GRANTED;
5201                    }
5202                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5203                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5204                        return PackageManager.PERMISSION_GRANTED;
5205                    }
5206                }
5207            }
5208        }
5209
5210        return PackageManager.PERMISSION_DENIED;
5211    }
5212
5213    @Override
5214    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5215        if (UserHandle.getCallingUserId() != userId) {
5216            mContext.enforceCallingPermission(
5217                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5218                    "isPermissionRevokedByPolicy for user " + userId);
5219        }
5220
5221        if (checkPermission(permission, packageName, userId)
5222                == PackageManager.PERMISSION_GRANTED) {
5223            return false;
5224        }
5225
5226        final int callingUid = Binder.getCallingUid();
5227        if (getInstantAppPackageName(callingUid) != null) {
5228            if (!isCallerSameApp(packageName, callingUid)) {
5229                return false;
5230            }
5231        } else {
5232            if (isInstantApp(packageName, userId)) {
5233                return false;
5234            }
5235        }
5236
5237        final long identity = Binder.clearCallingIdentity();
5238        try {
5239            final int flags = getPermissionFlags(permission, packageName, userId);
5240            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5241        } finally {
5242            Binder.restoreCallingIdentity(identity);
5243        }
5244    }
5245
5246    @Override
5247    public String getPermissionControllerPackageName() {
5248        synchronized (mPackages) {
5249            return mRequiredInstallerPackage;
5250        }
5251    }
5252
5253    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5254        return mPermissionManager.addDynamicPermission(
5255                info, async, getCallingUid(), new PermissionCallback() {
5256                    @Override
5257                    public void onPermissionChanged() {
5258                        if (!async) {
5259                            mSettings.writeLPr();
5260                        } else {
5261                            scheduleWriteSettingsLocked();
5262                        }
5263                    }
5264                });
5265    }
5266
5267    @Override
5268    public boolean addPermission(PermissionInfo info) {
5269        synchronized (mPackages) {
5270            return addDynamicPermission(info, false);
5271        }
5272    }
5273
5274    @Override
5275    public boolean addPermissionAsync(PermissionInfo info) {
5276        synchronized (mPackages) {
5277            return addDynamicPermission(info, true);
5278        }
5279    }
5280
5281    @Override
5282    public void removePermission(String permName) {
5283        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5284    }
5285
5286    @Override
5287    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5288        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5289                getCallingUid(), userId, mPermissionCallback);
5290    }
5291
5292    @Override
5293    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5294        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5295                getCallingUid(), userId, mPermissionCallback);
5296    }
5297
5298    /**
5299     * Get the first event id for the permission.
5300     *
5301     * <p>There are four events for each permission: <ul>
5302     *     <li>Request permission: first id + 0</li>
5303     *     <li>Grant permission: first id + 1</li>
5304     *     <li>Request for permission denied: first id + 2</li>
5305     *     <li>Revoke permission: first id + 3</li>
5306     * </ul></p>
5307     *
5308     * @param name name of the permission
5309     *
5310     * @return The first event id for the permission
5311     */
5312    private static int getBaseEventId(@NonNull String name) {
5313        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5314
5315        if (eventIdIndex == -1) {
5316            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5317                    || Build.IS_USER) {
5318                Log.i(TAG, "Unknown permission " + name);
5319
5320                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5321            } else {
5322                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5323                //
5324                // Also update
5325                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5326                // - metrics_constants.proto
5327                throw new IllegalStateException("Unknown permission " + name);
5328            }
5329        }
5330
5331        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5332    }
5333
5334    /**
5335     * Log that a permission was revoked.
5336     *
5337     * @param context Context of the caller
5338     * @param name name of the permission
5339     * @param packageName package permission if for
5340     */
5341    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5342            @NonNull String packageName) {
5343        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5344    }
5345
5346    /**
5347     * Log that a permission request was granted.
5348     *
5349     * @param context Context of the caller
5350     * @param name name of the permission
5351     * @param packageName package permission if for
5352     */
5353    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5354            @NonNull String packageName) {
5355        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5356    }
5357
5358    @Override
5359    public void resetRuntimePermissions() {
5360        mContext.enforceCallingOrSelfPermission(
5361                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5362                "revokeRuntimePermission");
5363
5364        int callingUid = Binder.getCallingUid();
5365        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5366            mContext.enforceCallingOrSelfPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "resetRuntimePermissions");
5369        }
5370
5371        synchronized (mPackages) {
5372            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5373            for (int userId : UserManagerService.getInstance().getUserIds()) {
5374                final int packageCount = mPackages.size();
5375                for (int i = 0; i < packageCount; i++) {
5376                    PackageParser.Package pkg = mPackages.valueAt(i);
5377                    if (!(pkg.mExtras instanceof PackageSetting)) {
5378                        continue;
5379                    }
5380                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5381                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5382                }
5383            }
5384        }
5385    }
5386
5387    @Override
5388    public int getPermissionFlags(String permName, String packageName, int userId) {
5389        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5390    }
5391
5392    @Override
5393    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5394            int flagValues, int userId) {
5395        mPermissionManager.updatePermissionFlags(
5396                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5397                mPermissionCallback);
5398    }
5399
5400    /**
5401     * Update the permission flags for all packages and runtime permissions of a user in order
5402     * to allow device or profile owner to remove POLICY_FIXED.
5403     */
5404    @Override
5405    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5406        synchronized (mPackages) {
5407            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5408                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5409                    mPermissionCallback);
5410            if (changed) {
5411                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5412            }
5413        }
5414    }
5415
5416    @Override
5417    public boolean shouldShowRequestPermissionRationale(String permissionName,
5418            String packageName, int userId) {
5419        if (UserHandle.getCallingUserId() != userId) {
5420            mContext.enforceCallingPermission(
5421                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5422                    "canShowRequestPermissionRationale for user " + userId);
5423        }
5424
5425        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5426        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5427            return false;
5428        }
5429
5430        if (checkPermission(permissionName, packageName, userId)
5431                == PackageManager.PERMISSION_GRANTED) {
5432            return false;
5433        }
5434
5435        final int flags;
5436
5437        final long identity = Binder.clearCallingIdentity();
5438        try {
5439            flags = getPermissionFlags(permissionName,
5440                    packageName, userId);
5441        } finally {
5442            Binder.restoreCallingIdentity(identity);
5443        }
5444
5445        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5446                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5447                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5448
5449        if ((flags & fixedFlags) != 0) {
5450            return false;
5451        }
5452
5453        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5454    }
5455
5456    @Override
5457    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5458        mContext.enforceCallingOrSelfPermission(
5459                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5460                "addOnPermissionsChangeListener");
5461
5462        synchronized (mPackages) {
5463            mOnPermissionChangeListeners.addListenerLocked(listener);
5464        }
5465    }
5466
5467    @Override
5468    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5469        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5470            throw new SecurityException("Instant applications don't have access to this method");
5471        }
5472        synchronized (mPackages) {
5473            mOnPermissionChangeListeners.removeListenerLocked(listener);
5474        }
5475    }
5476
5477    @Override
5478    public boolean isProtectedBroadcast(String actionName) {
5479        // allow instant applications
5480        synchronized (mProtectedBroadcasts) {
5481            if (mProtectedBroadcasts.contains(actionName)) {
5482                return true;
5483            } else if (actionName != null) {
5484                // TODO: remove these terrible hacks
5485                if (actionName.startsWith("android.net.netmon.lingerExpired")
5486                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5487                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5488                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5489                    return true;
5490                }
5491            }
5492        }
5493        return false;
5494    }
5495
5496    @Override
5497    public int checkSignatures(String pkg1, String pkg2) {
5498        synchronized (mPackages) {
5499            final PackageParser.Package p1 = mPackages.get(pkg1);
5500            final PackageParser.Package p2 = mPackages.get(pkg2);
5501            if (p1 == null || p1.mExtras == null
5502                    || p2 == null || p2.mExtras == null) {
5503                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5504            }
5505            final int callingUid = Binder.getCallingUid();
5506            final int callingUserId = UserHandle.getUserId(callingUid);
5507            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5508            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5509            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5510                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5511                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5512            }
5513            return compareSignatures(p1.mSignatures, p2.mSignatures);
5514        }
5515    }
5516
5517    @Override
5518    public int checkUidSignatures(int uid1, int uid2) {
5519        final int callingUid = Binder.getCallingUid();
5520        final int callingUserId = UserHandle.getUserId(callingUid);
5521        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5522        // Map to base uids.
5523        uid1 = UserHandle.getAppId(uid1);
5524        uid2 = UserHandle.getAppId(uid2);
5525        // reader
5526        synchronized (mPackages) {
5527            Signature[] s1;
5528            Signature[] s2;
5529            Object obj = mSettings.getUserIdLPr(uid1);
5530            if (obj != null) {
5531                if (obj instanceof SharedUserSetting) {
5532                    if (isCallerInstantApp) {
5533                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5534                    }
5535                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5536                } else if (obj instanceof PackageSetting) {
5537                    final PackageSetting ps = (PackageSetting) obj;
5538                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5539                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5540                    }
5541                    s1 = ps.signatures.mSignatures;
5542                } else {
5543                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5544                }
5545            } else {
5546                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5547            }
5548            obj = mSettings.getUserIdLPr(uid2);
5549            if (obj != null) {
5550                if (obj instanceof SharedUserSetting) {
5551                    if (isCallerInstantApp) {
5552                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5553                    }
5554                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5555                } else if (obj instanceof PackageSetting) {
5556                    final PackageSetting ps = (PackageSetting) obj;
5557                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5558                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5559                    }
5560                    s2 = ps.signatures.mSignatures;
5561                } else {
5562                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5563                }
5564            } else {
5565                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566            }
5567            return compareSignatures(s1, s2);
5568        }
5569    }
5570
5571    /**
5572     * This method should typically only be used when granting or revoking
5573     * permissions, since the app may immediately restart after this call.
5574     * <p>
5575     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5576     * guard your work against the app being relaunched.
5577     */
5578    private void killUid(int appId, int userId, String reason) {
5579        final long identity = Binder.clearCallingIdentity();
5580        try {
5581            IActivityManager am = ActivityManager.getService();
5582            if (am != null) {
5583                try {
5584                    am.killUid(appId, userId, reason);
5585                } catch (RemoteException e) {
5586                    /* ignore - same process */
5587                }
5588            }
5589        } finally {
5590            Binder.restoreCallingIdentity(identity);
5591        }
5592    }
5593
5594    /**
5595     * Compares two sets of signatures. Returns:
5596     * <br />
5597     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5598     * <br />
5599     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5600     * <br />
5601     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5602     * <br />
5603     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5604     * <br />
5605     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5606     */
5607    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5608        if (s1 == null) {
5609            return s2 == null
5610                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5611                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5612        }
5613
5614        if (s2 == null) {
5615            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5616        }
5617
5618        if (s1.length != s2.length) {
5619            return PackageManager.SIGNATURE_NO_MATCH;
5620        }
5621
5622        // Since both signature sets are of size 1, we can compare without HashSets.
5623        if (s1.length == 1) {
5624            return s1[0].equals(s2[0]) ?
5625                    PackageManager.SIGNATURE_MATCH :
5626                    PackageManager.SIGNATURE_NO_MATCH;
5627        }
5628
5629        ArraySet<Signature> set1 = new ArraySet<Signature>();
5630        for (Signature sig : s1) {
5631            set1.add(sig);
5632        }
5633        ArraySet<Signature> set2 = new ArraySet<Signature>();
5634        for (Signature sig : s2) {
5635            set2.add(sig);
5636        }
5637        // Make sure s2 contains all signatures in s1.
5638        if (set1.equals(set2)) {
5639            return PackageManager.SIGNATURE_MATCH;
5640        }
5641        return PackageManager.SIGNATURE_NO_MATCH;
5642    }
5643
5644    /**
5645     * If the database version for this type of package (internal storage or
5646     * external storage) is less than the version where package signatures
5647     * were updated, return true.
5648     */
5649    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5650        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5651        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5652    }
5653
5654    /**
5655     * Used for backward compatibility to make sure any packages with
5656     * certificate chains get upgraded to the new style. {@code existingSigs}
5657     * will be in the old format (since they were stored on disk from before the
5658     * system upgrade) and {@code scannedSigs} will be in the newer format.
5659     */
5660    private int compareSignaturesCompat(PackageSignatures existingSigs,
5661            PackageParser.Package scannedPkg) {
5662        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5663            return PackageManager.SIGNATURE_NO_MATCH;
5664        }
5665
5666        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5667        for (Signature sig : existingSigs.mSignatures) {
5668            existingSet.add(sig);
5669        }
5670        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5671        for (Signature sig : scannedPkg.mSignatures) {
5672            try {
5673                Signature[] chainSignatures = sig.getChainSignatures();
5674                for (Signature chainSig : chainSignatures) {
5675                    scannedCompatSet.add(chainSig);
5676                }
5677            } catch (CertificateEncodingException e) {
5678                scannedCompatSet.add(sig);
5679            }
5680        }
5681        /*
5682         * Make sure the expanded scanned set contains all signatures in the
5683         * existing one.
5684         */
5685        if (scannedCompatSet.equals(existingSet)) {
5686            // Migrate the old signatures to the new scheme.
5687            existingSigs.assignSignatures(scannedPkg.mSignatures);
5688            // The new KeySets will be re-added later in the scanning process.
5689            synchronized (mPackages) {
5690                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5691            }
5692            return PackageManager.SIGNATURE_MATCH;
5693        }
5694        return PackageManager.SIGNATURE_NO_MATCH;
5695    }
5696
5697    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5698        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5699        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5700    }
5701
5702    private int compareSignaturesRecover(PackageSignatures existingSigs,
5703            PackageParser.Package scannedPkg) {
5704        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5705            return PackageManager.SIGNATURE_NO_MATCH;
5706        }
5707
5708        String msg = null;
5709        try {
5710            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5711                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5712                        + scannedPkg.packageName);
5713                return PackageManager.SIGNATURE_MATCH;
5714            }
5715        } catch (CertificateException e) {
5716            msg = e.getMessage();
5717        }
5718
5719        logCriticalInfo(Log.INFO,
5720                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5721        return PackageManager.SIGNATURE_NO_MATCH;
5722    }
5723
5724    @Override
5725    public List<String> getAllPackages() {
5726        final int callingUid = Binder.getCallingUid();
5727        final int callingUserId = UserHandle.getUserId(callingUid);
5728        synchronized (mPackages) {
5729            if (canViewInstantApps(callingUid, callingUserId)) {
5730                return new ArrayList<String>(mPackages.keySet());
5731            }
5732            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5733            final List<String> result = new ArrayList<>();
5734            if (instantAppPkgName != null) {
5735                // caller is an instant application; filter unexposed applications
5736                for (PackageParser.Package pkg : mPackages.values()) {
5737                    if (!pkg.visibleToInstantApps) {
5738                        continue;
5739                    }
5740                    result.add(pkg.packageName);
5741                }
5742            } else {
5743                // caller is a normal application; filter instant applications
5744                for (PackageParser.Package pkg : mPackages.values()) {
5745                    final PackageSetting ps =
5746                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5747                    if (ps != null
5748                            && ps.getInstantApp(callingUserId)
5749                            && !mInstantAppRegistry.isInstantAccessGranted(
5750                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5751                        continue;
5752                    }
5753                    result.add(pkg.packageName);
5754                }
5755            }
5756            return result;
5757        }
5758    }
5759
5760    @Override
5761    public String[] getPackagesForUid(int uid) {
5762        final int callingUid = Binder.getCallingUid();
5763        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5764        final int userId = UserHandle.getUserId(uid);
5765        uid = UserHandle.getAppId(uid);
5766        // reader
5767        synchronized (mPackages) {
5768            Object obj = mSettings.getUserIdLPr(uid);
5769            if (obj instanceof SharedUserSetting) {
5770                if (isCallerInstantApp) {
5771                    return null;
5772                }
5773                final SharedUserSetting sus = (SharedUserSetting) obj;
5774                final int N = sus.packages.size();
5775                String[] res = new String[N];
5776                final Iterator<PackageSetting> it = sus.packages.iterator();
5777                int i = 0;
5778                while (it.hasNext()) {
5779                    PackageSetting ps = it.next();
5780                    if (ps.getInstalled(userId)) {
5781                        res[i++] = ps.name;
5782                    } else {
5783                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5784                    }
5785                }
5786                return res;
5787            } else if (obj instanceof PackageSetting) {
5788                final PackageSetting ps = (PackageSetting) obj;
5789                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5790                    return new String[]{ps.name};
5791                }
5792            }
5793        }
5794        return null;
5795    }
5796
5797    @Override
5798    public String getNameForUid(int uid) {
5799        final int callingUid = Binder.getCallingUid();
5800        if (getInstantAppPackageName(callingUid) != null) {
5801            return null;
5802        }
5803        synchronized (mPackages) {
5804            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5805            if (obj instanceof SharedUserSetting) {
5806                final SharedUserSetting sus = (SharedUserSetting) obj;
5807                return sus.name + ":" + sus.userId;
5808            } else if (obj instanceof PackageSetting) {
5809                final PackageSetting ps = (PackageSetting) obj;
5810                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5811                    return null;
5812                }
5813                return ps.name;
5814            }
5815            return null;
5816        }
5817    }
5818
5819    @Override
5820    public String[] getNamesForUids(int[] uids) {
5821        if (uids == null || uids.length == 0) {
5822            return null;
5823        }
5824        final int callingUid = Binder.getCallingUid();
5825        if (getInstantAppPackageName(callingUid) != null) {
5826            return null;
5827        }
5828        final String[] names = new String[uids.length];
5829        synchronized (mPackages) {
5830            for (int i = uids.length - 1; i >= 0; i--) {
5831                final int uid = uids[i];
5832                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5833                if (obj instanceof SharedUserSetting) {
5834                    final SharedUserSetting sus = (SharedUserSetting) obj;
5835                    names[i] = "shared:" + sus.name;
5836                } else if (obj instanceof PackageSetting) {
5837                    final PackageSetting ps = (PackageSetting) obj;
5838                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5839                        names[i] = null;
5840                    } else {
5841                        names[i] = ps.name;
5842                    }
5843                } else {
5844                    names[i] = null;
5845                }
5846            }
5847        }
5848        return names;
5849    }
5850
5851    @Override
5852    public int getUidForSharedUser(String sharedUserName) {
5853        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5854            return -1;
5855        }
5856        if (sharedUserName == null) {
5857            return -1;
5858        }
5859        // reader
5860        synchronized (mPackages) {
5861            SharedUserSetting suid;
5862            try {
5863                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5864                if (suid != null) {
5865                    return suid.userId;
5866                }
5867            } catch (PackageManagerException ignore) {
5868                // can't happen, but, still need to catch it
5869            }
5870            return -1;
5871        }
5872    }
5873
5874    @Override
5875    public int getFlagsForUid(int uid) {
5876        final int callingUid = Binder.getCallingUid();
5877        if (getInstantAppPackageName(callingUid) != null) {
5878            return 0;
5879        }
5880        synchronized (mPackages) {
5881            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5882            if (obj instanceof SharedUserSetting) {
5883                final SharedUserSetting sus = (SharedUserSetting) obj;
5884                return sus.pkgFlags;
5885            } else if (obj instanceof PackageSetting) {
5886                final PackageSetting ps = (PackageSetting) obj;
5887                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5888                    return 0;
5889                }
5890                return ps.pkgFlags;
5891            }
5892        }
5893        return 0;
5894    }
5895
5896    @Override
5897    public int getPrivateFlagsForUid(int uid) {
5898        final int callingUid = Binder.getCallingUid();
5899        if (getInstantAppPackageName(callingUid) != null) {
5900            return 0;
5901        }
5902        synchronized (mPackages) {
5903            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5904            if (obj instanceof SharedUserSetting) {
5905                final SharedUserSetting sus = (SharedUserSetting) obj;
5906                return sus.pkgPrivateFlags;
5907            } else if (obj instanceof PackageSetting) {
5908                final PackageSetting ps = (PackageSetting) obj;
5909                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5910                    return 0;
5911                }
5912                return ps.pkgPrivateFlags;
5913            }
5914        }
5915        return 0;
5916    }
5917
5918    @Override
5919    public boolean isUidPrivileged(int uid) {
5920        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5921            return false;
5922        }
5923        uid = UserHandle.getAppId(uid);
5924        // reader
5925        synchronized (mPackages) {
5926            Object obj = mSettings.getUserIdLPr(uid);
5927            if (obj instanceof SharedUserSetting) {
5928                final SharedUserSetting sus = (SharedUserSetting) obj;
5929                final Iterator<PackageSetting> it = sus.packages.iterator();
5930                while (it.hasNext()) {
5931                    if (it.next().isPrivileged()) {
5932                        return true;
5933                    }
5934                }
5935            } else if (obj instanceof PackageSetting) {
5936                final PackageSetting ps = (PackageSetting) obj;
5937                return ps.isPrivileged();
5938            }
5939        }
5940        return false;
5941    }
5942
5943    @Override
5944    public String[] getAppOpPermissionPackages(String permName) {
5945        return mPermissionManager.getAppOpPermissionPackages(permName);
5946    }
5947
5948    @Override
5949    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5950            int flags, int userId) {
5951        return resolveIntentInternal(
5952                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5953    }
5954
5955    /**
5956     * Normally instant apps can only be resolved when they're visible to the caller.
5957     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5958     * since we need to allow the system to start any installed application.
5959     */
5960    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5961            int flags, int userId, boolean resolveForStart) {
5962        try {
5963            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5964
5965            if (!sUserManager.exists(userId)) return null;
5966            final int callingUid = Binder.getCallingUid();
5967            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5968            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5969                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5970
5971            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5972            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5973                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5975
5976            final ResolveInfo bestChoice =
5977                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5978            return bestChoice;
5979        } finally {
5980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5981        }
5982    }
5983
5984    @Override
5985    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5986        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5987            throw new SecurityException(
5988                    "findPersistentPreferredActivity can only be run by the system");
5989        }
5990        if (!sUserManager.exists(userId)) {
5991            return null;
5992        }
5993        final int callingUid = Binder.getCallingUid();
5994        intent = updateIntentForResolve(intent);
5995        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5996        final int flags = updateFlagsForResolve(
5997                0, userId, intent, callingUid, false /*includeInstantApps*/);
5998        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5999                userId);
6000        synchronized (mPackages) {
6001            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6002                    userId);
6003        }
6004    }
6005
6006    @Override
6007    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6008            IntentFilter filter, int match, ComponentName activity) {
6009        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6010            return;
6011        }
6012        final int userId = UserHandle.getCallingUserId();
6013        if (DEBUG_PREFERRED) {
6014            Log.v(TAG, "setLastChosenActivity intent=" + intent
6015                + " resolvedType=" + resolvedType
6016                + " flags=" + flags
6017                + " filter=" + filter
6018                + " match=" + match
6019                + " activity=" + activity);
6020            filter.dump(new PrintStreamPrinter(System.out), "    ");
6021        }
6022        intent.setComponent(null);
6023        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6024                userId);
6025        // Find any earlier preferred or last chosen entries and nuke them
6026        findPreferredActivity(intent, resolvedType,
6027                flags, query, 0, false, true, false, userId);
6028        // Add the new activity as the last chosen for this filter
6029        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6030                "Setting last chosen");
6031    }
6032
6033    @Override
6034    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6036            return null;
6037        }
6038        final int userId = UserHandle.getCallingUserId();
6039        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6040        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6041                userId);
6042        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6043                false, false, false, userId);
6044    }
6045
6046    /**
6047     * Returns whether or not instant apps have been disabled remotely.
6048     */
6049    private boolean isEphemeralDisabled() {
6050        return mEphemeralAppsDisabled;
6051    }
6052
6053    private boolean isInstantAppAllowed(
6054            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6055            boolean skipPackageCheck) {
6056        if (mInstantAppResolverConnection == null) {
6057            return false;
6058        }
6059        if (mInstantAppInstallerActivity == null) {
6060            return false;
6061        }
6062        if (intent.getComponent() != null) {
6063            return false;
6064        }
6065        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6066            return false;
6067        }
6068        if (!skipPackageCheck && intent.getPackage() != null) {
6069            return false;
6070        }
6071        final boolean isWebUri = hasWebURI(intent);
6072        if (!isWebUri || intent.getData().getHost() == null) {
6073            return false;
6074        }
6075        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6076        // Or if there's already an ephemeral app installed that handles the action
6077        synchronized (mPackages) {
6078            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6079            for (int n = 0; n < count; n++) {
6080                final ResolveInfo info = resolvedActivities.get(n);
6081                final String packageName = info.activityInfo.packageName;
6082                final PackageSetting ps = mSettings.mPackages.get(packageName);
6083                if (ps != null) {
6084                    // only check domain verification status if the app is not a browser
6085                    if (!info.handleAllWebDataURI) {
6086                        // Try to get the status from User settings first
6087                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6088                        final int status = (int) (packedStatus >> 32);
6089                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6090                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6091                            if (DEBUG_EPHEMERAL) {
6092                                Slog.v(TAG, "DENY instant app;"
6093                                    + " pkg: " + packageName + ", status: " + status);
6094                            }
6095                            return false;
6096                        }
6097                    }
6098                    if (ps.getInstantApp(userId)) {
6099                        if (DEBUG_EPHEMERAL) {
6100                            Slog.v(TAG, "DENY instant app installed;"
6101                                    + " pkg: " + packageName);
6102                        }
6103                        return false;
6104                    }
6105                }
6106            }
6107        }
6108        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6109        return true;
6110    }
6111
6112    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6113            Intent origIntent, String resolvedType, String callingPackage,
6114            Bundle verificationBundle, int userId) {
6115        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6116                new InstantAppRequest(responseObj, origIntent, resolvedType,
6117                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6118        mHandler.sendMessage(msg);
6119    }
6120
6121    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6122            int flags, List<ResolveInfo> query, int userId) {
6123        if (query != null) {
6124            final int N = query.size();
6125            if (N == 1) {
6126                return query.get(0);
6127            } else if (N > 1) {
6128                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6129                // If there is more than one activity with the same priority,
6130                // then let the user decide between them.
6131                ResolveInfo r0 = query.get(0);
6132                ResolveInfo r1 = query.get(1);
6133                if (DEBUG_INTENT_MATCHING || debug) {
6134                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6135                            + r1.activityInfo.name + "=" + r1.priority);
6136                }
6137                // If the first activity has a higher priority, or a different
6138                // default, then it is always desirable to pick it.
6139                if (r0.priority != r1.priority
6140                        || r0.preferredOrder != r1.preferredOrder
6141                        || r0.isDefault != r1.isDefault) {
6142                    return query.get(0);
6143                }
6144                // If we have saved a preference for a preferred activity for
6145                // this Intent, use that.
6146                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6147                        flags, query, r0.priority, true, false, debug, userId);
6148                if (ri != null) {
6149                    return ri;
6150                }
6151                // If we have an ephemeral app, use it
6152                for (int i = 0; i < N; i++) {
6153                    ri = query.get(i);
6154                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6155                        final String packageName = ri.activityInfo.packageName;
6156                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6157                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6158                        final int status = (int)(packedStatus >> 32);
6159                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6160                            return ri;
6161                        }
6162                    }
6163                }
6164                ri = new ResolveInfo(mResolveInfo);
6165                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6166                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6167                // If all of the options come from the same package, show the application's
6168                // label and icon instead of the generic resolver's.
6169                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6170                // and then throw away the ResolveInfo itself, meaning that the caller loses
6171                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6172                // a fallback for this case; we only set the target package's resources on
6173                // the ResolveInfo, not the ActivityInfo.
6174                final String intentPackage = intent.getPackage();
6175                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6176                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6177                    ri.resolvePackageName = intentPackage;
6178                    if (userNeedsBadging(userId)) {
6179                        ri.noResourceId = true;
6180                    } else {
6181                        ri.icon = appi.icon;
6182                    }
6183                    ri.iconResourceId = appi.icon;
6184                    ri.labelRes = appi.labelRes;
6185                }
6186                ri.activityInfo.applicationInfo = new ApplicationInfo(
6187                        ri.activityInfo.applicationInfo);
6188                if (userId != 0) {
6189                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6190                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6191                }
6192                // Make sure that the resolver is displayable in car mode
6193                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6194                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6195                return ri;
6196            }
6197        }
6198        return null;
6199    }
6200
6201    /**
6202     * Return true if the given list is not empty and all of its contents have
6203     * an activityInfo with the given package name.
6204     */
6205    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6206        if (ArrayUtils.isEmpty(list)) {
6207            return false;
6208        }
6209        for (int i = 0, N = list.size(); i < N; i++) {
6210            final ResolveInfo ri = list.get(i);
6211            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6212            if (ai == null || !packageName.equals(ai.packageName)) {
6213                return false;
6214            }
6215        }
6216        return true;
6217    }
6218
6219    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6220            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6221        final int N = query.size();
6222        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6223                .get(userId);
6224        // Get the list of persistent preferred activities that handle the intent
6225        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6226        List<PersistentPreferredActivity> pprefs = ppir != null
6227                ? ppir.queryIntent(intent, resolvedType,
6228                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6229                        userId)
6230                : null;
6231        if (pprefs != null && pprefs.size() > 0) {
6232            final int M = pprefs.size();
6233            for (int i=0; i<M; i++) {
6234                final PersistentPreferredActivity ppa = pprefs.get(i);
6235                if (DEBUG_PREFERRED || debug) {
6236                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6237                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6238                            + "\n  component=" + ppa.mComponent);
6239                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6240                }
6241                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6242                        flags | MATCH_DISABLED_COMPONENTS, userId);
6243                if (DEBUG_PREFERRED || debug) {
6244                    Slog.v(TAG, "Found persistent preferred activity:");
6245                    if (ai != null) {
6246                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6247                    } else {
6248                        Slog.v(TAG, "  null");
6249                    }
6250                }
6251                if (ai == null) {
6252                    // This previously registered persistent preferred activity
6253                    // component is no longer known. Ignore it and do NOT remove it.
6254                    continue;
6255                }
6256                for (int j=0; j<N; j++) {
6257                    final ResolveInfo ri = query.get(j);
6258                    if (!ri.activityInfo.applicationInfo.packageName
6259                            .equals(ai.applicationInfo.packageName)) {
6260                        continue;
6261                    }
6262                    if (!ri.activityInfo.name.equals(ai.name)) {
6263                        continue;
6264                    }
6265                    //  Found a persistent preference that can handle the intent.
6266                    if (DEBUG_PREFERRED || debug) {
6267                        Slog.v(TAG, "Returning persistent preferred activity: " +
6268                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6269                    }
6270                    return ri;
6271                }
6272            }
6273        }
6274        return null;
6275    }
6276
6277    // TODO: handle preferred activities missing while user has amnesia
6278    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6279            List<ResolveInfo> query, int priority, boolean always,
6280            boolean removeMatches, boolean debug, int userId) {
6281        if (!sUserManager.exists(userId)) return null;
6282        final int callingUid = Binder.getCallingUid();
6283        flags = updateFlagsForResolve(
6284                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6285        intent = updateIntentForResolve(intent);
6286        // writer
6287        synchronized (mPackages) {
6288            // Try to find a matching persistent preferred activity.
6289            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6290                    debug, userId);
6291
6292            // If a persistent preferred activity matched, use it.
6293            if (pri != null) {
6294                return pri;
6295            }
6296
6297            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6298            // Get the list of preferred activities that handle the intent
6299            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6300            List<PreferredActivity> prefs = pir != null
6301                    ? pir.queryIntent(intent, resolvedType,
6302                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6303                            userId)
6304                    : null;
6305            if (prefs != null && prefs.size() > 0) {
6306                boolean changed = false;
6307                try {
6308                    // First figure out how good the original match set is.
6309                    // We will only allow preferred activities that came
6310                    // from the same match quality.
6311                    int match = 0;
6312
6313                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6314
6315                    final int N = query.size();
6316                    for (int j=0; j<N; j++) {
6317                        final ResolveInfo ri = query.get(j);
6318                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6319                                + ": 0x" + Integer.toHexString(match));
6320                        if (ri.match > match) {
6321                            match = ri.match;
6322                        }
6323                    }
6324
6325                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6326                            + Integer.toHexString(match));
6327
6328                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6329                    final int M = prefs.size();
6330                    for (int i=0; i<M; i++) {
6331                        final PreferredActivity pa = prefs.get(i);
6332                        if (DEBUG_PREFERRED || debug) {
6333                            Slog.v(TAG, "Checking PreferredActivity ds="
6334                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6335                                    + "\n  component=" + pa.mPref.mComponent);
6336                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6337                        }
6338                        if (pa.mPref.mMatch != match) {
6339                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6340                                    + Integer.toHexString(pa.mPref.mMatch));
6341                            continue;
6342                        }
6343                        // If it's not an "always" type preferred activity and that's what we're
6344                        // looking for, skip it.
6345                        if (always && !pa.mPref.mAlways) {
6346                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6347                            continue;
6348                        }
6349                        final ActivityInfo ai = getActivityInfo(
6350                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6351                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6352                                userId);
6353                        if (DEBUG_PREFERRED || debug) {
6354                            Slog.v(TAG, "Found preferred activity:");
6355                            if (ai != null) {
6356                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6357                            } else {
6358                                Slog.v(TAG, "  null");
6359                            }
6360                        }
6361                        if (ai == null) {
6362                            // This previously registered preferred activity
6363                            // component is no longer known.  Most likely an update
6364                            // to the app was installed and in the new version this
6365                            // component no longer exists.  Clean it up by removing
6366                            // it from the preferred activities list, and skip it.
6367                            Slog.w(TAG, "Removing dangling preferred activity: "
6368                                    + pa.mPref.mComponent);
6369                            pir.removeFilter(pa);
6370                            changed = true;
6371                            continue;
6372                        }
6373                        for (int j=0; j<N; j++) {
6374                            final ResolveInfo ri = query.get(j);
6375                            if (!ri.activityInfo.applicationInfo.packageName
6376                                    .equals(ai.applicationInfo.packageName)) {
6377                                continue;
6378                            }
6379                            if (!ri.activityInfo.name.equals(ai.name)) {
6380                                continue;
6381                            }
6382
6383                            if (removeMatches) {
6384                                pir.removeFilter(pa);
6385                                changed = true;
6386                                if (DEBUG_PREFERRED) {
6387                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6388                                }
6389                                break;
6390                            }
6391
6392                            // Okay we found a previously set preferred or last chosen app.
6393                            // If the result set is different from when this
6394                            // was created, and is not a subset of the preferred set, we need to
6395                            // clear it and re-ask the user their preference, if we're looking for
6396                            // an "always" type entry.
6397                            if (always && !pa.mPref.sameSet(query)) {
6398                                if (pa.mPref.isSuperset(query)) {
6399                                    // some components of the set are no longer present in
6400                                    // the query, but the preferred activity can still be reused
6401                                    if (DEBUG_PREFERRED) {
6402                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6403                                                + " still valid as only non-preferred components"
6404                                                + " were removed for " + intent + " type "
6405                                                + resolvedType);
6406                                    }
6407                                    // remove obsolete components and re-add the up-to-date filter
6408                                    PreferredActivity freshPa = new PreferredActivity(pa,
6409                                            pa.mPref.mMatch,
6410                                            pa.mPref.discardObsoleteComponents(query),
6411                                            pa.mPref.mComponent,
6412                                            pa.mPref.mAlways);
6413                                    pir.removeFilter(pa);
6414                                    pir.addFilter(freshPa);
6415                                    changed = true;
6416                                } else {
6417                                    Slog.i(TAG,
6418                                            "Result set changed, dropping preferred activity for "
6419                                                    + intent + " type " + resolvedType);
6420                                    if (DEBUG_PREFERRED) {
6421                                        Slog.v(TAG, "Removing preferred activity since set changed "
6422                                                + pa.mPref.mComponent);
6423                                    }
6424                                    pir.removeFilter(pa);
6425                                    // Re-add the filter as a "last chosen" entry (!always)
6426                                    PreferredActivity lastChosen = new PreferredActivity(
6427                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6428                                    pir.addFilter(lastChosen);
6429                                    changed = true;
6430                                    return null;
6431                                }
6432                            }
6433
6434                            // Yay! Either the set matched or we're looking for the last chosen
6435                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6436                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6437                            return ri;
6438                        }
6439                    }
6440                } finally {
6441                    if (changed) {
6442                        if (DEBUG_PREFERRED) {
6443                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6444                        }
6445                        scheduleWritePackageRestrictionsLocked(userId);
6446                    }
6447                }
6448            }
6449        }
6450        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6451        return null;
6452    }
6453
6454    /*
6455     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6456     */
6457    @Override
6458    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6459            int targetUserId) {
6460        mContext.enforceCallingOrSelfPermission(
6461                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6462        List<CrossProfileIntentFilter> matches =
6463                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6464        if (matches != null) {
6465            int size = matches.size();
6466            for (int i = 0; i < size; i++) {
6467                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6468            }
6469        }
6470        if (hasWebURI(intent)) {
6471            // cross-profile app linking works only towards the parent.
6472            final int callingUid = Binder.getCallingUid();
6473            final UserInfo parent = getProfileParent(sourceUserId);
6474            synchronized(mPackages) {
6475                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6476                        false /*includeInstantApps*/);
6477                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6478                        intent, resolvedType, flags, sourceUserId, parent.id);
6479                return xpDomainInfo != null;
6480            }
6481        }
6482        return false;
6483    }
6484
6485    private UserInfo getProfileParent(int userId) {
6486        final long identity = Binder.clearCallingIdentity();
6487        try {
6488            return sUserManager.getProfileParent(userId);
6489        } finally {
6490            Binder.restoreCallingIdentity(identity);
6491        }
6492    }
6493
6494    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6495            String resolvedType, int userId) {
6496        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6497        if (resolver != null) {
6498            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6499        }
6500        return null;
6501    }
6502
6503    @Override
6504    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6505            String resolvedType, int flags, int userId) {
6506        try {
6507            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6508
6509            return new ParceledListSlice<>(
6510                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6511        } finally {
6512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6513        }
6514    }
6515
6516    /**
6517     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6518     * instant, returns {@code null}.
6519     */
6520    private String getInstantAppPackageName(int callingUid) {
6521        synchronized (mPackages) {
6522            // If the caller is an isolated app use the owner's uid for the lookup.
6523            if (Process.isIsolated(callingUid)) {
6524                callingUid = mIsolatedOwners.get(callingUid);
6525            }
6526            final int appId = UserHandle.getAppId(callingUid);
6527            final Object obj = mSettings.getUserIdLPr(appId);
6528            if (obj instanceof PackageSetting) {
6529                final PackageSetting ps = (PackageSetting) obj;
6530                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6531                return isInstantApp ? ps.pkg.packageName : null;
6532            }
6533        }
6534        return null;
6535    }
6536
6537    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6538            String resolvedType, int flags, int userId) {
6539        return queryIntentActivitiesInternal(
6540                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6541                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6542    }
6543
6544    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6545            String resolvedType, int flags, int filterCallingUid, int userId,
6546            boolean resolveForStart, boolean allowDynamicSplits) {
6547        if (!sUserManager.exists(userId)) return Collections.emptyList();
6548        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6549        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6550                false /* requireFullPermission */, false /* checkShell */,
6551                "query intent activities");
6552        final String pkgName = intent.getPackage();
6553        ComponentName comp = intent.getComponent();
6554        if (comp == null) {
6555            if (intent.getSelector() != null) {
6556                intent = intent.getSelector();
6557                comp = intent.getComponent();
6558            }
6559        }
6560
6561        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6562                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6563        if (comp != null) {
6564            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6565            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6566            if (ai != null) {
6567                // When specifying an explicit component, we prevent the activity from being
6568                // used when either 1) the calling package is normal and the activity is within
6569                // an ephemeral application or 2) the calling package is ephemeral and the
6570                // activity is not visible to ephemeral applications.
6571                final boolean matchInstantApp =
6572                        (flags & PackageManager.MATCH_INSTANT) != 0;
6573                final boolean matchVisibleToInstantAppOnly =
6574                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6575                final boolean matchExplicitlyVisibleOnly =
6576                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6577                final boolean isCallerInstantApp =
6578                        instantAppPkgName != null;
6579                final boolean isTargetSameInstantApp =
6580                        comp.getPackageName().equals(instantAppPkgName);
6581                final boolean isTargetInstantApp =
6582                        (ai.applicationInfo.privateFlags
6583                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6584                final boolean isTargetVisibleToInstantApp =
6585                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6586                final boolean isTargetExplicitlyVisibleToInstantApp =
6587                        isTargetVisibleToInstantApp
6588                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6589                final boolean isTargetHiddenFromInstantApp =
6590                        !isTargetVisibleToInstantApp
6591                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6592                final boolean blockResolution =
6593                        !isTargetSameInstantApp
6594                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6595                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6596                                        && isTargetHiddenFromInstantApp));
6597                if (!blockResolution) {
6598                    final ResolveInfo ri = new ResolveInfo();
6599                    ri.activityInfo = ai;
6600                    list.add(ri);
6601                }
6602            }
6603            return applyPostResolutionFilter(
6604                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6605        }
6606
6607        // reader
6608        boolean sortResult = false;
6609        boolean addEphemeral = false;
6610        List<ResolveInfo> result;
6611        final boolean ephemeralDisabled = isEphemeralDisabled();
6612        synchronized (mPackages) {
6613            if (pkgName == null) {
6614                List<CrossProfileIntentFilter> matchingFilters =
6615                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6616                // Check for results that need to skip the current profile.
6617                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6618                        resolvedType, flags, userId);
6619                if (xpResolveInfo != null) {
6620                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6621                    xpResult.add(xpResolveInfo);
6622                    return applyPostResolutionFilter(
6623                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6624                            allowDynamicSplits, filterCallingUid, userId);
6625                }
6626
6627                // Check for results in the current profile.
6628                result = filterIfNotSystemUser(mActivities.queryIntent(
6629                        intent, resolvedType, flags, userId), userId);
6630                addEphemeral = !ephemeralDisabled
6631                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6632                // Check for cross profile results.
6633                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6634                xpResolveInfo = queryCrossProfileIntents(
6635                        matchingFilters, intent, resolvedType, flags, userId,
6636                        hasNonNegativePriorityResult);
6637                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6638                    boolean isVisibleToUser = filterIfNotSystemUser(
6639                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6640                    if (isVisibleToUser) {
6641                        result.add(xpResolveInfo);
6642                        sortResult = true;
6643                    }
6644                }
6645                if (hasWebURI(intent)) {
6646                    CrossProfileDomainInfo xpDomainInfo = null;
6647                    final UserInfo parent = getProfileParent(userId);
6648                    if (parent != null) {
6649                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6650                                flags, userId, parent.id);
6651                    }
6652                    if (xpDomainInfo != null) {
6653                        if (xpResolveInfo != null) {
6654                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6655                            // in the result.
6656                            result.remove(xpResolveInfo);
6657                        }
6658                        if (result.size() == 0 && !addEphemeral) {
6659                            // No result in current profile, but found candidate in parent user.
6660                            // And we are not going to add emphemeral app, so we can return the
6661                            // result straight away.
6662                            result.add(xpDomainInfo.resolveInfo);
6663                            return applyPostResolutionFilter(result, instantAppPkgName,
6664                                    allowDynamicSplits, filterCallingUid, userId);
6665                        }
6666                    } else if (result.size() <= 1 && !addEphemeral) {
6667                        // No result in parent user and <= 1 result in current profile, and we
6668                        // are not going to add emphemeral app, so we can return the result without
6669                        // further processing.
6670                        return applyPostResolutionFilter(result, instantAppPkgName,
6671                                allowDynamicSplits, filterCallingUid, userId);
6672                    }
6673                    // We have more than one candidate (combining results from current and parent
6674                    // profile), so we need filtering and sorting.
6675                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6676                            intent, flags, result, xpDomainInfo, userId);
6677                    sortResult = true;
6678                }
6679            } else {
6680                final PackageParser.Package pkg = mPackages.get(pkgName);
6681                result = null;
6682                if (pkg != null) {
6683                    result = filterIfNotSystemUser(
6684                            mActivities.queryIntentForPackage(
6685                                    intent, resolvedType, flags, pkg.activities, userId),
6686                            userId);
6687                }
6688                if (result == null || result.size() == 0) {
6689                    // the caller wants to resolve for a particular package; however, there
6690                    // were no installed results, so, try to find an ephemeral result
6691                    addEphemeral = !ephemeralDisabled
6692                            && isInstantAppAllowed(
6693                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6694                    if (result == null) {
6695                        result = new ArrayList<>();
6696                    }
6697                }
6698            }
6699        }
6700        if (addEphemeral) {
6701            result = maybeAddInstantAppInstaller(
6702                    result, intent, resolvedType, flags, userId, resolveForStart);
6703        }
6704        if (sortResult) {
6705            Collections.sort(result, mResolvePrioritySorter);
6706        }
6707        return applyPostResolutionFilter(
6708                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6709    }
6710
6711    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6712            String resolvedType, int flags, int userId, boolean resolveForStart) {
6713        // first, check to see if we've got an instant app already installed
6714        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6715        ResolveInfo localInstantApp = null;
6716        boolean blockResolution = false;
6717        if (!alreadyResolvedLocally) {
6718            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6719                    flags
6720                        | PackageManager.GET_RESOLVED_FILTER
6721                        | PackageManager.MATCH_INSTANT
6722                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6723                    userId);
6724            for (int i = instantApps.size() - 1; i >= 0; --i) {
6725                final ResolveInfo info = instantApps.get(i);
6726                final String packageName = info.activityInfo.packageName;
6727                final PackageSetting ps = mSettings.mPackages.get(packageName);
6728                if (ps.getInstantApp(userId)) {
6729                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6730                    final int status = (int)(packedStatus >> 32);
6731                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6732                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6733                        // there's a local instant application installed, but, the user has
6734                        // chosen to never use it; skip resolution and don't acknowledge
6735                        // an instant application is even available
6736                        if (DEBUG_EPHEMERAL) {
6737                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6738                        }
6739                        blockResolution = true;
6740                        break;
6741                    } else {
6742                        // we have a locally installed instant application; skip resolution
6743                        // but acknowledge there's an instant application available
6744                        if (DEBUG_EPHEMERAL) {
6745                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6746                        }
6747                        localInstantApp = info;
6748                        break;
6749                    }
6750                }
6751            }
6752        }
6753        // no app installed, let's see if one's available
6754        AuxiliaryResolveInfo auxiliaryResponse = null;
6755        if (!blockResolution) {
6756            if (localInstantApp == null) {
6757                // we don't have an instant app locally, resolve externally
6758                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6759                final InstantAppRequest requestObject = new InstantAppRequest(
6760                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6761                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6762                        resolveForStart);
6763                auxiliaryResponse =
6764                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6765                                mContext, mInstantAppResolverConnection, requestObject);
6766                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6767            } else {
6768                // we have an instant application locally, but, we can't admit that since
6769                // callers shouldn't be able to determine prior browsing. create a dummy
6770                // auxiliary response so the downstream code behaves as if there's an
6771                // instant application available externally. when it comes time to start
6772                // the instant application, we'll do the right thing.
6773                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6774                auxiliaryResponse = new AuxiliaryResolveInfo(
6775                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6776                        ai.versionCode, null /*failureIntent*/);
6777            }
6778        }
6779        if (auxiliaryResponse != null) {
6780            if (DEBUG_EPHEMERAL) {
6781                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6782            }
6783            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6784            final PackageSetting ps =
6785                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6786            if (ps != null) {
6787                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6788                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6789                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6790                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6791                // make sure this resolver is the default
6792                ephemeralInstaller.isDefault = true;
6793                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6794                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6795                // add a non-generic filter
6796                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6797                ephemeralInstaller.filter.addDataPath(
6798                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6799                ephemeralInstaller.isInstantAppAvailable = true;
6800                result.add(ephemeralInstaller);
6801            }
6802        }
6803        return result;
6804    }
6805
6806    private static class CrossProfileDomainInfo {
6807        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6808        ResolveInfo resolveInfo;
6809        /* Best domain verification status of the activities found in the other profile */
6810        int bestDomainVerificationStatus;
6811    }
6812
6813    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6814            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6815        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6816                sourceUserId)) {
6817            return null;
6818        }
6819        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6820                resolvedType, flags, parentUserId);
6821
6822        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6823            return null;
6824        }
6825        CrossProfileDomainInfo result = null;
6826        int size = resultTargetUser.size();
6827        for (int i = 0; i < size; i++) {
6828            ResolveInfo riTargetUser = resultTargetUser.get(i);
6829            // Intent filter verification is only for filters that specify a host. So don't return
6830            // those that handle all web uris.
6831            if (riTargetUser.handleAllWebDataURI) {
6832                continue;
6833            }
6834            String packageName = riTargetUser.activityInfo.packageName;
6835            PackageSetting ps = mSettings.mPackages.get(packageName);
6836            if (ps == null) {
6837                continue;
6838            }
6839            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6840            int status = (int)(verificationState >> 32);
6841            if (result == null) {
6842                result = new CrossProfileDomainInfo();
6843                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6844                        sourceUserId, parentUserId);
6845                result.bestDomainVerificationStatus = status;
6846            } else {
6847                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6848                        result.bestDomainVerificationStatus);
6849            }
6850        }
6851        // Don't consider matches with status NEVER across profiles.
6852        if (result != null && result.bestDomainVerificationStatus
6853                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6854            return null;
6855        }
6856        return result;
6857    }
6858
6859    /**
6860     * Verification statuses are ordered from the worse to the best, except for
6861     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6862     */
6863    private int bestDomainVerificationStatus(int status1, int status2) {
6864        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6865            return status2;
6866        }
6867        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6868            return status1;
6869        }
6870        return (int) MathUtils.max(status1, status2);
6871    }
6872
6873    private boolean isUserEnabled(int userId) {
6874        long callingId = Binder.clearCallingIdentity();
6875        try {
6876            UserInfo userInfo = sUserManager.getUserInfo(userId);
6877            return userInfo != null && userInfo.isEnabled();
6878        } finally {
6879            Binder.restoreCallingIdentity(callingId);
6880        }
6881    }
6882
6883    /**
6884     * Filter out activities with systemUserOnly flag set, when current user is not System.
6885     *
6886     * @return filtered list
6887     */
6888    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6889        if (userId == UserHandle.USER_SYSTEM) {
6890            return resolveInfos;
6891        }
6892        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6893            ResolveInfo info = resolveInfos.get(i);
6894            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6895                resolveInfos.remove(i);
6896            }
6897        }
6898        return resolveInfos;
6899    }
6900
6901    /**
6902     * Filters out ephemeral activities.
6903     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6904     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6905     *
6906     * @param resolveInfos The pre-filtered list of resolved activities
6907     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6908     *          is performed.
6909     * @return A filtered list of resolved activities.
6910     */
6911    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6912            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6913        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6914            final ResolveInfo info = resolveInfos.get(i);
6915            // allow activities that are defined in the provided package
6916            if (allowDynamicSplits
6917                    && info.activityInfo.splitName != null
6918                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6919                            info.activityInfo.splitName)) {
6920                // requested activity is defined in a split that hasn't been installed yet.
6921                // add the installer to the resolve list
6922                if (DEBUG_INSTALL) {
6923                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6924                }
6925                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6926                final ComponentName installFailureActivity = findInstallFailureActivity(
6927                        info.activityInfo.packageName,  filterCallingUid, userId);
6928                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6929                        info.activityInfo.packageName, info.activityInfo.splitName,
6930                        installFailureActivity,
6931                        info.activityInfo.applicationInfo.versionCode,
6932                        null /*failureIntent*/);
6933                // make sure this resolver is the default
6934                installerInfo.isDefault = true;
6935                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6936                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6937                // add a non-generic filter
6938                installerInfo.filter = new IntentFilter();
6939                // load resources from the correct package
6940                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6941                resolveInfos.set(i, installerInfo);
6942                continue;
6943            }
6944            // caller is a full app, don't need to apply any other filtering
6945            if (ephemeralPkgName == null) {
6946                continue;
6947            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6948                // caller is same app; don't need to apply any other filtering
6949                continue;
6950            }
6951            // allow activities that have been explicitly exposed to ephemeral apps
6952            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6953            if (!isEphemeralApp
6954                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6955                continue;
6956            }
6957            resolveInfos.remove(i);
6958        }
6959        return resolveInfos;
6960    }
6961
6962    /**
6963     * Returns the activity component that can handle install failures.
6964     * <p>By default, the instant application installer handles failures. However, an
6965     * application may want to handle failures on its own. Applications do this by
6966     * creating an activity with an intent filter that handles the action
6967     * {@link Intent#ACTION_INSTALL_FAILURE}.
6968     */
6969    private @Nullable ComponentName findInstallFailureActivity(
6970            String packageName, int filterCallingUid, int userId) {
6971        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6972        failureActivityIntent.setPackage(packageName);
6973        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6974        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6975                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6976                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6977        final int NR = result.size();
6978        if (NR > 0) {
6979            for (int i = 0; i < NR; i++) {
6980                final ResolveInfo info = result.get(i);
6981                if (info.activityInfo.splitName != null) {
6982                    continue;
6983                }
6984                return new ComponentName(packageName, info.activityInfo.name);
6985            }
6986        }
6987        return null;
6988    }
6989
6990    /**
6991     * @param resolveInfos list of resolve infos in descending priority order
6992     * @return if the list contains a resolve info with non-negative priority
6993     */
6994    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6995        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6996    }
6997
6998    private static boolean hasWebURI(Intent intent) {
6999        if (intent.getData() == null) {
7000            return false;
7001        }
7002        final String scheme = intent.getScheme();
7003        if (TextUtils.isEmpty(scheme)) {
7004            return false;
7005        }
7006        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7007    }
7008
7009    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7010            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7011            int userId) {
7012        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7013
7014        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7015            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7016                    candidates.size());
7017        }
7018
7019        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7020        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7021        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7022        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7023        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7024        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7025
7026        synchronized (mPackages) {
7027            final int count = candidates.size();
7028            // First, try to use linked apps. Partition the candidates into four lists:
7029            // one for the final results, one for the "do not use ever", one for "undefined status"
7030            // and finally one for "browser app type".
7031            for (int n=0; n<count; n++) {
7032                ResolveInfo info = candidates.get(n);
7033                String packageName = info.activityInfo.packageName;
7034                PackageSetting ps = mSettings.mPackages.get(packageName);
7035                if (ps != null) {
7036                    // Add to the special match all list (Browser use case)
7037                    if (info.handleAllWebDataURI) {
7038                        matchAllList.add(info);
7039                        continue;
7040                    }
7041                    // Try to get the status from User settings first
7042                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7043                    int status = (int)(packedStatus >> 32);
7044                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7045                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7046                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7047                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7048                                    + " : linkgen=" + linkGeneration);
7049                        }
7050                        // Use link-enabled generation as preferredOrder, i.e.
7051                        // prefer newly-enabled over earlier-enabled.
7052                        info.preferredOrder = linkGeneration;
7053                        alwaysList.add(info);
7054                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7055                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7056                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7057                        }
7058                        neverList.add(info);
7059                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7060                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7061                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7062                        }
7063                        alwaysAskList.add(info);
7064                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7065                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7066                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7067                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7068                        }
7069                        undefinedList.add(info);
7070                    }
7071                }
7072            }
7073
7074            // We'll want to include browser possibilities in a few cases
7075            boolean includeBrowser = false;
7076
7077            // First try to add the "always" resolution(s) for the current user, if any
7078            if (alwaysList.size() > 0) {
7079                result.addAll(alwaysList);
7080            } else {
7081                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7082                result.addAll(undefinedList);
7083                // Maybe add one for the other profile.
7084                if (xpDomainInfo != null && (
7085                        xpDomainInfo.bestDomainVerificationStatus
7086                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7087                    result.add(xpDomainInfo.resolveInfo);
7088                }
7089                includeBrowser = true;
7090            }
7091
7092            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7093            // If there were 'always' entries their preferred order has been set, so we also
7094            // back that off to make the alternatives equivalent
7095            if (alwaysAskList.size() > 0) {
7096                for (ResolveInfo i : result) {
7097                    i.preferredOrder = 0;
7098                }
7099                result.addAll(alwaysAskList);
7100                includeBrowser = true;
7101            }
7102
7103            if (includeBrowser) {
7104                // Also add browsers (all of them or only the default one)
7105                if (DEBUG_DOMAIN_VERIFICATION) {
7106                    Slog.v(TAG, "   ...including browsers in candidate set");
7107                }
7108                if ((matchFlags & MATCH_ALL) != 0) {
7109                    result.addAll(matchAllList);
7110                } else {
7111                    // Browser/generic handling case.  If there's a default browser, go straight
7112                    // to that (but only if there is no other higher-priority match).
7113                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7114                    int maxMatchPrio = 0;
7115                    ResolveInfo defaultBrowserMatch = null;
7116                    final int numCandidates = matchAllList.size();
7117                    for (int n = 0; n < numCandidates; n++) {
7118                        ResolveInfo info = matchAllList.get(n);
7119                        // track the highest overall match priority...
7120                        if (info.priority > maxMatchPrio) {
7121                            maxMatchPrio = info.priority;
7122                        }
7123                        // ...and the highest-priority default browser match
7124                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7125                            if (defaultBrowserMatch == null
7126                                    || (defaultBrowserMatch.priority < info.priority)) {
7127                                if (debug) {
7128                                    Slog.v(TAG, "Considering default browser match " + info);
7129                                }
7130                                defaultBrowserMatch = info;
7131                            }
7132                        }
7133                    }
7134                    if (defaultBrowserMatch != null
7135                            && defaultBrowserMatch.priority >= maxMatchPrio
7136                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7137                    {
7138                        if (debug) {
7139                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7140                        }
7141                        result.add(defaultBrowserMatch);
7142                    } else {
7143                        result.addAll(matchAllList);
7144                    }
7145                }
7146
7147                // If there is nothing selected, add all candidates and remove the ones that the user
7148                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7149                if (result.size() == 0) {
7150                    result.addAll(candidates);
7151                    result.removeAll(neverList);
7152                }
7153            }
7154        }
7155        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7156            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7157                    result.size());
7158            for (ResolveInfo info : result) {
7159                Slog.v(TAG, "  + " + info.activityInfo);
7160            }
7161        }
7162        return result;
7163    }
7164
7165    // Returns a packed value as a long:
7166    //
7167    // high 'int'-sized word: link status: undefined/ask/never/always.
7168    // low 'int'-sized word: relative priority among 'always' results.
7169    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7170        long result = ps.getDomainVerificationStatusForUser(userId);
7171        // if none available, get the master status
7172        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7173            if (ps.getIntentFilterVerificationInfo() != null) {
7174                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7175            }
7176        }
7177        return result;
7178    }
7179
7180    private ResolveInfo querySkipCurrentProfileIntents(
7181            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7182            int flags, int sourceUserId) {
7183        if (matchingFilters != null) {
7184            int size = matchingFilters.size();
7185            for (int i = 0; i < size; i ++) {
7186                CrossProfileIntentFilter filter = matchingFilters.get(i);
7187                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7188                    // Checking if there are activities in the target user that can handle the
7189                    // intent.
7190                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7191                            resolvedType, flags, sourceUserId);
7192                    if (resolveInfo != null) {
7193                        return resolveInfo;
7194                    }
7195                }
7196            }
7197        }
7198        return null;
7199    }
7200
7201    // Return matching ResolveInfo in target user if any.
7202    private ResolveInfo queryCrossProfileIntents(
7203            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7204            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7205        if (matchingFilters != null) {
7206            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7207            // match the same intent. For performance reasons, it is better not to
7208            // run queryIntent twice for the same userId
7209            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7210            int size = matchingFilters.size();
7211            for (int i = 0; i < size; i++) {
7212                CrossProfileIntentFilter filter = matchingFilters.get(i);
7213                int targetUserId = filter.getTargetUserId();
7214                boolean skipCurrentProfile =
7215                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7216                boolean skipCurrentProfileIfNoMatchFound =
7217                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7218                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7219                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7220                    // Checking if there are activities in the target user that can handle the
7221                    // intent.
7222                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7223                            resolvedType, flags, sourceUserId);
7224                    if (resolveInfo != null) return resolveInfo;
7225                    alreadyTriedUserIds.put(targetUserId, true);
7226                }
7227            }
7228        }
7229        return null;
7230    }
7231
7232    /**
7233     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7234     * will forward the intent to the filter's target user.
7235     * Otherwise, returns null.
7236     */
7237    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7238            String resolvedType, int flags, int sourceUserId) {
7239        int targetUserId = filter.getTargetUserId();
7240        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7241                resolvedType, flags, targetUserId);
7242        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7243            // If all the matches in the target profile are suspended, return null.
7244            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7245                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7246                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7247                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7248                            targetUserId);
7249                }
7250            }
7251        }
7252        return null;
7253    }
7254
7255    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7256            int sourceUserId, int targetUserId) {
7257        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7258        long ident = Binder.clearCallingIdentity();
7259        boolean targetIsProfile;
7260        try {
7261            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7262        } finally {
7263            Binder.restoreCallingIdentity(ident);
7264        }
7265        String className;
7266        if (targetIsProfile) {
7267            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7268        } else {
7269            className = FORWARD_INTENT_TO_PARENT;
7270        }
7271        ComponentName forwardingActivityComponentName = new ComponentName(
7272                mAndroidApplication.packageName, className);
7273        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7274                sourceUserId);
7275        if (!targetIsProfile) {
7276            forwardingActivityInfo.showUserIcon = targetUserId;
7277            forwardingResolveInfo.noResourceId = true;
7278        }
7279        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7280        forwardingResolveInfo.priority = 0;
7281        forwardingResolveInfo.preferredOrder = 0;
7282        forwardingResolveInfo.match = 0;
7283        forwardingResolveInfo.isDefault = true;
7284        forwardingResolveInfo.filter = filter;
7285        forwardingResolveInfo.targetUserId = targetUserId;
7286        return forwardingResolveInfo;
7287    }
7288
7289    @Override
7290    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7291            Intent[] specifics, String[] specificTypes, Intent intent,
7292            String resolvedType, int flags, int userId) {
7293        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7294                specificTypes, intent, resolvedType, flags, userId));
7295    }
7296
7297    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7298            Intent[] specifics, String[] specificTypes, Intent intent,
7299            String resolvedType, int flags, int userId) {
7300        if (!sUserManager.exists(userId)) return Collections.emptyList();
7301        final int callingUid = Binder.getCallingUid();
7302        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7303                false /*includeInstantApps*/);
7304        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7305                false /*requireFullPermission*/, false /*checkShell*/,
7306                "query intent activity options");
7307        final String resultsAction = intent.getAction();
7308
7309        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7310                | PackageManager.GET_RESOLVED_FILTER, userId);
7311
7312        if (DEBUG_INTENT_MATCHING) {
7313            Log.v(TAG, "Query " + intent + ": " + results);
7314        }
7315
7316        int specificsPos = 0;
7317        int N;
7318
7319        // todo: note that the algorithm used here is O(N^2).  This
7320        // isn't a problem in our current environment, but if we start running
7321        // into situations where we have more than 5 or 10 matches then this
7322        // should probably be changed to something smarter...
7323
7324        // First we go through and resolve each of the specific items
7325        // that were supplied, taking care of removing any corresponding
7326        // duplicate items in the generic resolve list.
7327        if (specifics != null) {
7328            for (int i=0; i<specifics.length; i++) {
7329                final Intent sintent = specifics[i];
7330                if (sintent == null) {
7331                    continue;
7332                }
7333
7334                if (DEBUG_INTENT_MATCHING) {
7335                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7336                }
7337
7338                String action = sintent.getAction();
7339                if (resultsAction != null && resultsAction.equals(action)) {
7340                    // If this action was explicitly requested, then don't
7341                    // remove things that have it.
7342                    action = null;
7343                }
7344
7345                ResolveInfo ri = null;
7346                ActivityInfo ai = null;
7347
7348                ComponentName comp = sintent.getComponent();
7349                if (comp == null) {
7350                    ri = resolveIntent(
7351                        sintent,
7352                        specificTypes != null ? specificTypes[i] : null,
7353                            flags, userId);
7354                    if (ri == null) {
7355                        continue;
7356                    }
7357                    if (ri == mResolveInfo) {
7358                        // ACK!  Must do something better with this.
7359                    }
7360                    ai = ri.activityInfo;
7361                    comp = new ComponentName(ai.applicationInfo.packageName,
7362                            ai.name);
7363                } else {
7364                    ai = getActivityInfo(comp, flags, userId);
7365                    if (ai == null) {
7366                        continue;
7367                    }
7368                }
7369
7370                // Look for any generic query activities that are duplicates
7371                // of this specific one, and remove them from the results.
7372                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7373                N = results.size();
7374                int j;
7375                for (j=specificsPos; j<N; j++) {
7376                    ResolveInfo sri = results.get(j);
7377                    if ((sri.activityInfo.name.equals(comp.getClassName())
7378                            && sri.activityInfo.applicationInfo.packageName.equals(
7379                                    comp.getPackageName()))
7380                        || (action != null && sri.filter.matchAction(action))) {
7381                        results.remove(j);
7382                        if (DEBUG_INTENT_MATCHING) Log.v(
7383                            TAG, "Removing duplicate item from " + j
7384                            + " due to specific " + specificsPos);
7385                        if (ri == null) {
7386                            ri = sri;
7387                        }
7388                        j--;
7389                        N--;
7390                    }
7391                }
7392
7393                // Add this specific item to its proper place.
7394                if (ri == null) {
7395                    ri = new ResolveInfo();
7396                    ri.activityInfo = ai;
7397                }
7398                results.add(specificsPos, ri);
7399                ri.specificIndex = i;
7400                specificsPos++;
7401            }
7402        }
7403
7404        // Now we go through the remaining generic results and remove any
7405        // duplicate actions that are found here.
7406        N = results.size();
7407        for (int i=specificsPos; i<N-1; i++) {
7408            final ResolveInfo rii = results.get(i);
7409            if (rii.filter == null) {
7410                continue;
7411            }
7412
7413            // Iterate over all of the actions of this result's intent
7414            // filter...  typically this should be just one.
7415            final Iterator<String> it = rii.filter.actionsIterator();
7416            if (it == null) {
7417                continue;
7418            }
7419            while (it.hasNext()) {
7420                final String action = it.next();
7421                if (resultsAction != null && resultsAction.equals(action)) {
7422                    // If this action was explicitly requested, then don't
7423                    // remove things that have it.
7424                    continue;
7425                }
7426                for (int j=i+1; j<N; j++) {
7427                    final ResolveInfo rij = results.get(j);
7428                    if (rij.filter != null && rij.filter.hasAction(action)) {
7429                        results.remove(j);
7430                        if (DEBUG_INTENT_MATCHING) Log.v(
7431                            TAG, "Removing duplicate item from " + j
7432                            + " due to action " + action + " at " + i);
7433                        j--;
7434                        N--;
7435                    }
7436                }
7437            }
7438
7439            // If the caller didn't request filter information, drop it now
7440            // so we don't have to marshall/unmarshall it.
7441            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7442                rii.filter = null;
7443            }
7444        }
7445
7446        // Filter out the caller activity if so requested.
7447        if (caller != null) {
7448            N = results.size();
7449            for (int i=0; i<N; i++) {
7450                ActivityInfo ainfo = results.get(i).activityInfo;
7451                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7452                        && caller.getClassName().equals(ainfo.name)) {
7453                    results.remove(i);
7454                    break;
7455                }
7456            }
7457        }
7458
7459        // If the caller didn't request filter information,
7460        // drop them now so we don't have to
7461        // marshall/unmarshall it.
7462        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7463            N = results.size();
7464            for (int i=0; i<N; i++) {
7465                results.get(i).filter = null;
7466            }
7467        }
7468
7469        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7470        return results;
7471    }
7472
7473    @Override
7474    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7475            String resolvedType, int flags, int userId) {
7476        return new ParceledListSlice<>(
7477                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7478                        false /*allowDynamicSplits*/));
7479    }
7480
7481    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7482            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7483        if (!sUserManager.exists(userId)) return Collections.emptyList();
7484        final int callingUid = Binder.getCallingUid();
7485        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7486                false /*requireFullPermission*/, false /*checkShell*/,
7487                "query intent receivers");
7488        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7489        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7490                false /*includeInstantApps*/);
7491        ComponentName comp = intent.getComponent();
7492        if (comp == null) {
7493            if (intent.getSelector() != null) {
7494                intent = intent.getSelector();
7495                comp = intent.getComponent();
7496            }
7497        }
7498        if (comp != null) {
7499            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7500            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7501            if (ai != null) {
7502                // When specifying an explicit component, we prevent the activity from being
7503                // used when either 1) the calling package is normal and the activity is within
7504                // an instant application or 2) the calling package is ephemeral and the
7505                // activity is not visible to instant applications.
7506                final boolean matchInstantApp =
7507                        (flags & PackageManager.MATCH_INSTANT) != 0;
7508                final boolean matchVisibleToInstantAppOnly =
7509                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7510                final boolean matchExplicitlyVisibleOnly =
7511                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7512                final boolean isCallerInstantApp =
7513                        instantAppPkgName != null;
7514                final boolean isTargetSameInstantApp =
7515                        comp.getPackageName().equals(instantAppPkgName);
7516                final boolean isTargetInstantApp =
7517                        (ai.applicationInfo.privateFlags
7518                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7519                final boolean isTargetVisibleToInstantApp =
7520                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7521                final boolean isTargetExplicitlyVisibleToInstantApp =
7522                        isTargetVisibleToInstantApp
7523                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7524                final boolean isTargetHiddenFromInstantApp =
7525                        !isTargetVisibleToInstantApp
7526                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7527                final boolean blockResolution =
7528                        !isTargetSameInstantApp
7529                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7530                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7531                                        && isTargetHiddenFromInstantApp));
7532                if (!blockResolution) {
7533                    ResolveInfo ri = new ResolveInfo();
7534                    ri.activityInfo = ai;
7535                    list.add(ri);
7536                }
7537            }
7538            return applyPostResolutionFilter(
7539                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7540        }
7541
7542        // reader
7543        synchronized (mPackages) {
7544            String pkgName = intent.getPackage();
7545            if (pkgName == null) {
7546                final List<ResolveInfo> result =
7547                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7548                return applyPostResolutionFilter(
7549                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7550            }
7551            final PackageParser.Package pkg = mPackages.get(pkgName);
7552            if (pkg != null) {
7553                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7554                        intent, resolvedType, flags, pkg.receivers, userId);
7555                return applyPostResolutionFilter(
7556                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7557            }
7558            return Collections.emptyList();
7559        }
7560    }
7561
7562    @Override
7563    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7564        final int callingUid = Binder.getCallingUid();
7565        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7566    }
7567
7568    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7569            int userId, int callingUid) {
7570        if (!sUserManager.exists(userId)) return null;
7571        flags = updateFlagsForResolve(
7572                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7573        List<ResolveInfo> query = queryIntentServicesInternal(
7574                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7575        if (query != null) {
7576            if (query.size() >= 1) {
7577                // If there is more than one service with the same priority,
7578                // just arbitrarily pick the first one.
7579                return query.get(0);
7580            }
7581        }
7582        return null;
7583    }
7584
7585    @Override
7586    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7587            String resolvedType, int flags, int userId) {
7588        final int callingUid = Binder.getCallingUid();
7589        return new ParceledListSlice<>(queryIntentServicesInternal(
7590                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7591    }
7592
7593    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7594            String resolvedType, int flags, int userId, int callingUid,
7595            boolean includeInstantApps) {
7596        if (!sUserManager.exists(userId)) return Collections.emptyList();
7597        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7598                false /*requireFullPermission*/, false /*checkShell*/,
7599                "query intent receivers");
7600        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7601        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7602        ComponentName comp = intent.getComponent();
7603        if (comp == null) {
7604            if (intent.getSelector() != null) {
7605                intent = intent.getSelector();
7606                comp = intent.getComponent();
7607            }
7608        }
7609        if (comp != null) {
7610            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7611            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7612            if (si != null) {
7613                // When specifying an explicit component, we prevent the service from being
7614                // used when either 1) the service is in an instant application and the
7615                // caller is not the same instant application or 2) the calling package is
7616                // ephemeral and the activity is not visible to ephemeral applications.
7617                final boolean matchInstantApp =
7618                        (flags & PackageManager.MATCH_INSTANT) != 0;
7619                final boolean matchVisibleToInstantAppOnly =
7620                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7621                final boolean isCallerInstantApp =
7622                        instantAppPkgName != null;
7623                final boolean isTargetSameInstantApp =
7624                        comp.getPackageName().equals(instantAppPkgName);
7625                final boolean isTargetInstantApp =
7626                        (si.applicationInfo.privateFlags
7627                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7628                final boolean isTargetHiddenFromInstantApp =
7629                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7630                final boolean blockResolution =
7631                        !isTargetSameInstantApp
7632                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7633                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7634                                        && isTargetHiddenFromInstantApp));
7635                if (!blockResolution) {
7636                    final ResolveInfo ri = new ResolveInfo();
7637                    ri.serviceInfo = si;
7638                    list.add(ri);
7639                }
7640            }
7641            return list;
7642        }
7643
7644        // reader
7645        synchronized (mPackages) {
7646            String pkgName = intent.getPackage();
7647            if (pkgName == null) {
7648                return applyPostServiceResolutionFilter(
7649                        mServices.queryIntent(intent, resolvedType, flags, userId),
7650                        instantAppPkgName);
7651            }
7652            final PackageParser.Package pkg = mPackages.get(pkgName);
7653            if (pkg != null) {
7654                return applyPostServiceResolutionFilter(
7655                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7656                                userId),
7657                        instantAppPkgName);
7658            }
7659            return Collections.emptyList();
7660        }
7661    }
7662
7663    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7664            String instantAppPkgName) {
7665        if (instantAppPkgName == null) {
7666            return resolveInfos;
7667        }
7668        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7669            final ResolveInfo info = resolveInfos.get(i);
7670            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7671            // allow services that are defined in the provided package
7672            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7673                if (info.serviceInfo.splitName != null
7674                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7675                                info.serviceInfo.splitName)) {
7676                    // requested service is defined in a split that hasn't been installed yet.
7677                    // add the installer to the resolve list
7678                    if (DEBUG_EPHEMERAL) {
7679                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7680                    }
7681                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7682                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7683                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7684                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7685                            null /*failureIntent*/);
7686                    // make sure this resolver is the default
7687                    installerInfo.isDefault = true;
7688                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7689                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7690                    // add a non-generic filter
7691                    installerInfo.filter = new IntentFilter();
7692                    // load resources from the correct package
7693                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7694                    resolveInfos.set(i, installerInfo);
7695                }
7696                continue;
7697            }
7698            // allow services that have been explicitly exposed to ephemeral apps
7699            if (!isEphemeralApp
7700                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7701                continue;
7702            }
7703            resolveInfos.remove(i);
7704        }
7705        return resolveInfos;
7706    }
7707
7708    @Override
7709    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7710            String resolvedType, int flags, int userId) {
7711        return new ParceledListSlice<>(
7712                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7713    }
7714
7715    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7716            Intent intent, String resolvedType, int flags, int userId) {
7717        if (!sUserManager.exists(userId)) return Collections.emptyList();
7718        final int callingUid = Binder.getCallingUid();
7719        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7720        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7721                false /*includeInstantApps*/);
7722        ComponentName comp = intent.getComponent();
7723        if (comp == null) {
7724            if (intent.getSelector() != null) {
7725                intent = intent.getSelector();
7726                comp = intent.getComponent();
7727            }
7728        }
7729        if (comp != null) {
7730            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7731            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7732            if (pi != null) {
7733                // When specifying an explicit component, we prevent the provider from being
7734                // used when either 1) the provider is in an instant application and the
7735                // caller is not the same instant application or 2) the calling package is an
7736                // instant application and the provider is not visible to instant applications.
7737                final boolean matchInstantApp =
7738                        (flags & PackageManager.MATCH_INSTANT) != 0;
7739                final boolean matchVisibleToInstantAppOnly =
7740                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7741                final boolean isCallerInstantApp =
7742                        instantAppPkgName != null;
7743                final boolean isTargetSameInstantApp =
7744                        comp.getPackageName().equals(instantAppPkgName);
7745                final boolean isTargetInstantApp =
7746                        (pi.applicationInfo.privateFlags
7747                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7748                final boolean isTargetHiddenFromInstantApp =
7749                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7750                final boolean blockResolution =
7751                        !isTargetSameInstantApp
7752                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7753                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7754                                        && isTargetHiddenFromInstantApp));
7755                if (!blockResolution) {
7756                    final ResolveInfo ri = new ResolveInfo();
7757                    ri.providerInfo = pi;
7758                    list.add(ri);
7759                }
7760            }
7761            return list;
7762        }
7763
7764        // reader
7765        synchronized (mPackages) {
7766            String pkgName = intent.getPackage();
7767            if (pkgName == null) {
7768                return applyPostContentProviderResolutionFilter(
7769                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7770                        instantAppPkgName);
7771            }
7772            final PackageParser.Package pkg = mPackages.get(pkgName);
7773            if (pkg != null) {
7774                return applyPostContentProviderResolutionFilter(
7775                        mProviders.queryIntentForPackage(
7776                        intent, resolvedType, flags, pkg.providers, userId),
7777                        instantAppPkgName);
7778            }
7779            return Collections.emptyList();
7780        }
7781    }
7782
7783    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7784            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7785        if (instantAppPkgName == null) {
7786            return resolveInfos;
7787        }
7788        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7789            final ResolveInfo info = resolveInfos.get(i);
7790            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7791            // allow providers that are defined in the provided package
7792            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7793                if (info.providerInfo.splitName != null
7794                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7795                                info.providerInfo.splitName)) {
7796                    // requested provider is defined in a split that hasn't been installed yet.
7797                    // add the installer to the resolve list
7798                    if (DEBUG_EPHEMERAL) {
7799                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7800                    }
7801                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7802                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7803                            info.providerInfo.packageName, info.providerInfo.splitName,
7804                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7805                            null /*failureIntent*/);
7806                    // make sure this resolver is the default
7807                    installerInfo.isDefault = true;
7808                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7809                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7810                    // add a non-generic filter
7811                    installerInfo.filter = new IntentFilter();
7812                    // load resources from the correct package
7813                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7814                    resolveInfos.set(i, installerInfo);
7815                }
7816                continue;
7817            }
7818            // allow providers that have been explicitly exposed to instant applications
7819            if (!isEphemeralApp
7820                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7821                continue;
7822            }
7823            resolveInfos.remove(i);
7824        }
7825        return resolveInfos;
7826    }
7827
7828    @Override
7829    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7830        final int callingUid = Binder.getCallingUid();
7831        if (getInstantAppPackageName(callingUid) != null) {
7832            return ParceledListSlice.emptyList();
7833        }
7834        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7835        flags = updateFlagsForPackage(flags, userId, null);
7836        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7837        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7838                true /* requireFullPermission */, false /* checkShell */,
7839                "get installed packages");
7840
7841        // writer
7842        synchronized (mPackages) {
7843            ArrayList<PackageInfo> list;
7844            if (listUninstalled) {
7845                list = new ArrayList<>(mSettings.mPackages.size());
7846                for (PackageSetting ps : mSettings.mPackages.values()) {
7847                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7848                        continue;
7849                    }
7850                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7851                        continue;
7852                    }
7853                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7854                    if (pi != null) {
7855                        list.add(pi);
7856                    }
7857                }
7858            } else {
7859                list = new ArrayList<>(mPackages.size());
7860                for (PackageParser.Package p : mPackages.values()) {
7861                    final PackageSetting ps = (PackageSetting) p.mExtras;
7862                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7863                        continue;
7864                    }
7865                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7866                        continue;
7867                    }
7868                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7869                            p.mExtras, flags, userId);
7870                    if (pi != null) {
7871                        list.add(pi);
7872                    }
7873                }
7874            }
7875
7876            return new ParceledListSlice<>(list);
7877        }
7878    }
7879
7880    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7881            String[] permissions, boolean[] tmp, int flags, int userId) {
7882        int numMatch = 0;
7883        final PermissionsState permissionsState = ps.getPermissionsState();
7884        for (int i=0; i<permissions.length; i++) {
7885            final String permission = permissions[i];
7886            if (permissionsState.hasPermission(permission, userId)) {
7887                tmp[i] = true;
7888                numMatch++;
7889            } else {
7890                tmp[i] = false;
7891            }
7892        }
7893        if (numMatch == 0) {
7894            return;
7895        }
7896        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7897
7898        // The above might return null in cases of uninstalled apps or install-state
7899        // skew across users/profiles.
7900        if (pi != null) {
7901            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7902                if (numMatch == permissions.length) {
7903                    pi.requestedPermissions = permissions;
7904                } else {
7905                    pi.requestedPermissions = new String[numMatch];
7906                    numMatch = 0;
7907                    for (int i=0; i<permissions.length; i++) {
7908                        if (tmp[i]) {
7909                            pi.requestedPermissions[numMatch] = permissions[i];
7910                            numMatch++;
7911                        }
7912                    }
7913                }
7914            }
7915            list.add(pi);
7916        }
7917    }
7918
7919    @Override
7920    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7921            String[] permissions, int flags, int userId) {
7922        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7923        flags = updateFlagsForPackage(flags, userId, permissions);
7924        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7925                true /* requireFullPermission */, false /* checkShell */,
7926                "get packages holding permissions");
7927        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7928
7929        // writer
7930        synchronized (mPackages) {
7931            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7932            boolean[] tmpBools = new boolean[permissions.length];
7933            if (listUninstalled) {
7934                for (PackageSetting ps : mSettings.mPackages.values()) {
7935                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7936                            userId);
7937                }
7938            } else {
7939                for (PackageParser.Package pkg : mPackages.values()) {
7940                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7941                    if (ps != null) {
7942                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7943                                userId);
7944                    }
7945                }
7946            }
7947
7948            return new ParceledListSlice<PackageInfo>(list);
7949        }
7950    }
7951
7952    @Override
7953    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7954        final int callingUid = Binder.getCallingUid();
7955        if (getInstantAppPackageName(callingUid) != null) {
7956            return ParceledListSlice.emptyList();
7957        }
7958        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7959        flags = updateFlagsForApplication(flags, userId, null);
7960        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7961
7962        // writer
7963        synchronized (mPackages) {
7964            ArrayList<ApplicationInfo> list;
7965            if (listUninstalled) {
7966                list = new ArrayList<>(mSettings.mPackages.size());
7967                for (PackageSetting ps : mSettings.mPackages.values()) {
7968                    ApplicationInfo ai;
7969                    int effectiveFlags = flags;
7970                    if (ps.isSystem()) {
7971                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7972                    }
7973                    if (ps.pkg != null) {
7974                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7975                            continue;
7976                        }
7977                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7978                            continue;
7979                        }
7980                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7981                                ps.readUserState(userId), userId);
7982                        if (ai != null) {
7983                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7984                        }
7985                    } else {
7986                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7987                        // and already converts to externally visible package name
7988                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7989                                callingUid, effectiveFlags, userId);
7990                    }
7991                    if (ai != null) {
7992                        list.add(ai);
7993                    }
7994                }
7995            } else {
7996                list = new ArrayList<>(mPackages.size());
7997                for (PackageParser.Package p : mPackages.values()) {
7998                    if (p.mExtras != null) {
7999                        PackageSetting ps = (PackageSetting) p.mExtras;
8000                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8001                            continue;
8002                        }
8003                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8004                            continue;
8005                        }
8006                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8007                                ps.readUserState(userId), userId);
8008                        if (ai != null) {
8009                            ai.packageName = resolveExternalPackageNameLPr(p);
8010                            list.add(ai);
8011                        }
8012                    }
8013                }
8014            }
8015
8016            return new ParceledListSlice<>(list);
8017        }
8018    }
8019
8020    @Override
8021    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8022        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8023            return null;
8024        }
8025        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8026            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8027                    "getEphemeralApplications");
8028        }
8029        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8030                true /* requireFullPermission */, false /* checkShell */,
8031                "getEphemeralApplications");
8032        synchronized (mPackages) {
8033            List<InstantAppInfo> instantApps = mInstantAppRegistry
8034                    .getInstantAppsLPr(userId);
8035            if (instantApps != null) {
8036                return new ParceledListSlice<>(instantApps);
8037            }
8038        }
8039        return null;
8040    }
8041
8042    @Override
8043    public boolean isInstantApp(String packageName, int userId) {
8044        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8045                true /* requireFullPermission */, false /* checkShell */,
8046                "isInstantApp");
8047        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8048            return false;
8049        }
8050
8051        synchronized (mPackages) {
8052            int callingUid = Binder.getCallingUid();
8053            if (Process.isIsolated(callingUid)) {
8054                callingUid = mIsolatedOwners.get(callingUid);
8055            }
8056            final PackageSetting ps = mSettings.mPackages.get(packageName);
8057            PackageParser.Package pkg = mPackages.get(packageName);
8058            final boolean returnAllowed =
8059                    ps != null
8060                    && (isCallerSameApp(packageName, callingUid)
8061                            || canViewInstantApps(callingUid, userId)
8062                            || mInstantAppRegistry.isInstantAccessGranted(
8063                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8064            if (returnAllowed) {
8065                return ps.getInstantApp(userId);
8066            }
8067        }
8068        return false;
8069    }
8070
8071    @Override
8072    public byte[] getInstantAppCookie(String packageName, int userId) {
8073        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8074            return null;
8075        }
8076
8077        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8078                true /* requireFullPermission */, false /* checkShell */,
8079                "getInstantAppCookie");
8080        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8081            return null;
8082        }
8083        synchronized (mPackages) {
8084            return mInstantAppRegistry.getInstantAppCookieLPw(
8085                    packageName, userId);
8086        }
8087    }
8088
8089    @Override
8090    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8091        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8092            return true;
8093        }
8094
8095        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8096                true /* requireFullPermission */, true /* checkShell */,
8097                "setInstantAppCookie");
8098        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8099            return false;
8100        }
8101        synchronized (mPackages) {
8102            return mInstantAppRegistry.setInstantAppCookieLPw(
8103                    packageName, cookie, userId);
8104        }
8105    }
8106
8107    @Override
8108    public Bitmap getInstantAppIcon(String packageName, int userId) {
8109        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8110            return null;
8111        }
8112
8113        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8114            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8115                    "getInstantAppIcon");
8116        }
8117        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8118                true /* requireFullPermission */, false /* checkShell */,
8119                "getInstantAppIcon");
8120
8121        synchronized (mPackages) {
8122            return mInstantAppRegistry.getInstantAppIconLPw(
8123                    packageName, userId);
8124        }
8125    }
8126
8127    private boolean isCallerSameApp(String packageName, int uid) {
8128        PackageParser.Package pkg = mPackages.get(packageName);
8129        return pkg != null
8130                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8131    }
8132
8133    @Override
8134    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8135        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8136            return ParceledListSlice.emptyList();
8137        }
8138        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8139    }
8140
8141    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8142        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8143
8144        // reader
8145        synchronized (mPackages) {
8146            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8147            final int userId = UserHandle.getCallingUserId();
8148            while (i.hasNext()) {
8149                final PackageParser.Package p = i.next();
8150                if (p.applicationInfo == null) continue;
8151
8152                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8153                        && !p.applicationInfo.isDirectBootAware();
8154                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8155                        && p.applicationInfo.isDirectBootAware();
8156
8157                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8158                        && (!mSafeMode || isSystemApp(p))
8159                        && (matchesUnaware || matchesAware)) {
8160                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8161                    if (ps != null) {
8162                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8163                                ps.readUserState(userId), userId);
8164                        if (ai != null) {
8165                            finalList.add(ai);
8166                        }
8167                    }
8168                }
8169            }
8170        }
8171
8172        return finalList;
8173    }
8174
8175    @Override
8176    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8177        return resolveContentProviderInternal(name, flags, userId);
8178    }
8179
8180    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8181        if (!sUserManager.exists(userId)) return null;
8182        flags = updateFlagsForComponent(flags, userId, name);
8183        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8184        // reader
8185        synchronized (mPackages) {
8186            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8187            PackageSetting ps = provider != null
8188                    ? mSettings.mPackages.get(provider.owner.packageName)
8189                    : null;
8190            if (ps != null) {
8191                final boolean isInstantApp = ps.getInstantApp(userId);
8192                // normal application; filter out instant application provider
8193                if (instantAppPkgName == null && isInstantApp) {
8194                    return null;
8195                }
8196                // instant application; filter out other instant applications
8197                if (instantAppPkgName != null
8198                        && isInstantApp
8199                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8200                    return null;
8201                }
8202                // instant application; filter out non-exposed provider
8203                if (instantAppPkgName != null
8204                        && !isInstantApp
8205                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8206                    return null;
8207                }
8208                // provider not enabled
8209                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8210                    return null;
8211                }
8212                return PackageParser.generateProviderInfo(
8213                        provider, flags, ps.readUserState(userId), userId);
8214            }
8215            return null;
8216        }
8217    }
8218
8219    /**
8220     * @deprecated
8221     */
8222    @Deprecated
8223    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8224        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8225            return;
8226        }
8227        // reader
8228        synchronized (mPackages) {
8229            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8230                    .entrySet().iterator();
8231            final int userId = UserHandle.getCallingUserId();
8232            while (i.hasNext()) {
8233                Map.Entry<String, PackageParser.Provider> entry = i.next();
8234                PackageParser.Provider p = entry.getValue();
8235                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8236
8237                if (ps != null && p.syncable
8238                        && (!mSafeMode || (p.info.applicationInfo.flags
8239                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8240                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8241                            ps.readUserState(userId), userId);
8242                    if (info != null) {
8243                        outNames.add(entry.getKey());
8244                        outInfo.add(info);
8245                    }
8246                }
8247            }
8248        }
8249    }
8250
8251    @Override
8252    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8253            int uid, int flags, String metaDataKey) {
8254        final int callingUid = Binder.getCallingUid();
8255        final int userId = processName != null ? UserHandle.getUserId(uid)
8256                : UserHandle.getCallingUserId();
8257        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8258        flags = updateFlagsForComponent(flags, userId, processName);
8259        ArrayList<ProviderInfo> finalList = null;
8260        // reader
8261        synchronized (mPackages) {
8262            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8263            while (i.hasNext()) {
8264                final PackageParser.Provider p = i.next();
8265                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8266                if (ps != null && p.info.authority != null
8267                        && (processName == null
8268                                || (p.info.processName.equals(processName)
8269                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8270                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8271
8272                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8273                    // parameter.
8274                    if (metaDataKey != null
8275                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8276                        continue;
8277                    }
8278                    final ComponentName component =
8279                            new ComponentName(p.info.packageName, p.info.name);
8280                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8281                        continue;
8282                    }
8283                    if (finalList == null) {
8284                        finalList = new ArrayList<ProviderInfo>(3);
8285                    }
8286                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8287                            ps.readUserState(userId), userId);
8288                    if (info != null) {
8289                        finalList.add(info);
8290                    }
8291                }
8292            }
8293        }
8294
8295        if (finalList != null) {
8296            Collections.sort(finalList, mProviderInitOrderSorter);
8297            return new ParceledListSlice<ProviderInfo>(finalList);
8298        }
8299
8300        return ParceledListSlice.emptyList();
8301    }
8302
8303    @Override
8304    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8305        // reader
8306        synchronized (mPackages) {
8307            final int callingUid = Binder.getCallingUid();
8308            final int callingUserId = UserHandle.getUserId(callingUid);
8309            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8310            if (ps == null) return null;
8311            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8312                return null;
8313            }
8314            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8315            return PackageParser.generateInstrumentationInfo(i, flags);
8316        }
8317    }
8318
8319    @Override
8320    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8321            String targetPackage, int flags) {
8322        final int callingUid = Binder.getCallingUid();
8323        final int callingUserId = UserHandle.getUserId(callingUid);
8324        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8325        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8326            return ParceledListSlice.emptyList();
8327        }
8328        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8329    }
8330
8331    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8332            int flags) {
8333        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8334
8335        // reader
8336        synchronized (mPackages) {
8337            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8338            while (i.hasNext()) {
8339                final PackageParser.Instrumentation p = i.next();
8340                if (targetPackage == null
8341                        || targetPackage.equals(p.info.targetPackage)) {
8342                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8343                            flags);
8344                    if (ii != null) {
8345                        finalList.add(ii);
8346                    }
8347                }
8348            }
8349        }
8350
8351        return finalList;
8352    }
8353
8354    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8356        try {
8357            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8358        } finally {
8359            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8360        }
8361    }
8362
8363    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8364        final File[] files = dir.listFiles();
8365        if (ArrayUtils.isEmpty(files)) {
8366            Log.d(TAG, "No files in app dir " + dir);
8367            return;
8368        }
8369
8370        if (DEBUG_PACKAGE_SCANNING) {
8371            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8372                    + " flags=0x" + Integer.toHexString(parseFlags));
8373        }
8374        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8375                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8376                mParallelPackageParserCallback);
8377
8378        // Submit files for parsing in parallel
8379        int fileCount = 0;
8380        for (File file : files) {
8381            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8382                    && !PackageInstallerService.isStageName(file.getName());
8383            if (!isPackage) {
8384                // Ignore entries which are not packages
8385                continue;
8386            }
8387            parallelPackageParser.submit(file, parseFlags);
8388            fileCount++;
8389        }
8390
8391        // Process results one by one
8392        for (; fileCount > 0; fileCount--) {
8393            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8394            Throwable throwable = parseResult.throwable;
8395            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8396
8397            if (throwable == null) {
8398                // Static shared libraries have synthetic package names
8399                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8400                    renameStaticSharedLibraryPackage(parseResult.pkg);
8401                }
8402                try {
8403                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8404                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8405                                currentTime, null);
8406                    }
8407                } catch (PackageManagerException e) {
8408                    errorCode = e.error;
8409                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8410                }
8411            } else if (throwable instanceof PackageParser.PackageParserException) {
8412                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8413                        throwable;
8414                errorCode = e.error;
8415                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8416            } else {
8417                throw new IllegalStateException("Unexpected exception occurred while parsing "
8418                        + parseResult.scanFile, throwable);
8419            }
8420
8421            // Delete invalid userdata apps
8422            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8423                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8424                logCriticalInfo(Log.WARN,
8425                        "Deleting invalid package at " + parseResult.scanFile);
8426                removeCodePathLI(parseResult.scanFile);
8427            }
8428        }
8429        parallelPackageParser.close();
8430    }
8431
8432    private static File getSettingsProblemFile() {
8433        File dataDir = Environment.getDataDirectory();
8434        File systemDir = new File(dataDir, "system");
8435        File fname = new File(systemDir, "uiderrors.txt");
8436        return fname;
8437    }
8438
8439    public static void reportSettingsProblem(int priority, String msg) {
8440        logCriticalInfo(priority, msg);
8441    }
8442
8443    public static void logCriticalInfo(int priority, String msg) {
8444        Slog.println(priority, TAG, msg);
8445        EventLogTags.writePmCriticalInfo(msg);
8446        try {
8447            File fname = getSettingsProblemFile();
8448            FileOutputStream out = new FileOutputStream(fname, true);
8449            PrintWriter pw = new FastPrintWriter(out);
8450            SimpleDateFormat formatter = new SimpleDateFormat();
8451            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8452            pw.println(dateString + ": " + msg);
8453            pw.close();
8454            FileUtils.setPermissions(
8455                    fname.toString(),
8456                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8457                    -1, -1);
8458        } catch (java.io.IOException e) {
8459        }
8460    }
8461
8462    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8463        if (srcFile.isDirectory()) {
8464            final File baseFile = new File(pkg.baseCodePath);
8465            long maxModifiedTime = baseFile.lastModified();
8466            if (pkg.splitCodePaths != null) {
8467                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8468                    final File splitFile = new File(pkg.splitCodePaths[i]);
8469                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8470                }
8471            }
8472            return maxModifiedTime;
8473        }
8474        return srcFile.lastModified();
8475    }
8476
8477    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8478            final int policyFlags) throws PackageManagerException {
8479        // When upgrading from pre-N MR1, verify the package time stamp using the package
8480        // directory and not the APK file.
8481        final long lastModifiedTime = mIsPreNMR1Upgrade
8482                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8483        if (ps != null
8484                && ps.codePath.equals(srcFile)
8485                && ps.timeStamp == lastModifiedTime
8486                && !isCompatSignatureUpdateNeeded(pkg)
8487                && !isRecoverSignatureUpdateNeeded(pkg)) {
8488            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8489            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8490            ArraySet<PublicKey> signingKs;
8491            synchronized (mPackages) {
8492                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8493            }
8494            if (ps.signatures.mSignatures != null
8495                    && ps.signatures.mSignatures.length != 0
8496                    && signingKs != null) {
8497                // Optimization: reuse the existing cached certificates
8498                // if the package appears to be unchanged.
8499                pkg.mSignatures = ps.signatures.mSignatures;
8500                pkg.mSigningKeys = signingKs;
8501                return;
8502            }
8503
8504            Slog.w(TAG, "PackageSetting for " + ps.name
8505                    + " is missing signatures.  Collecting certs again to recover them.");
8506        } else {
8507            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8508        }
8509
8510        try {
8511            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8512            PackageParser.collectCertificates(pkg, policyFlags);
8513        } catch (PackageParserException e) {
8514            throw PackageManagerException.from(e);
8515        } finally {
8516            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8517        }
8518    }
8519
8520    /**
8521     *  Traces a package scan.
8522     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8523     */
8524    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8525            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8526        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8527        try {
8528            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8529        } finally {
8530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8531        }
8532    }
8533
8534    /**
8535     *  Scans a package and returns the newly parsed package.
8536     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8537     */
8538    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8539            long currentTime, UserHandle user) throws PackageManagerException {
8540        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8541        PackageParser pp = new PackageParser();
8542        pp.setSeparateProcesses(mSeparateProcesses);
8543        pp.setOnlyCoreApps(mOnlyCore);
8544        pp.setDisplayMetrics(mMetrics);
8545        pp.setCallback(mPackageParserCallback);
8546
8547        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8548            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8549        }
8550
8551        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8552        final PackageParser.Package pkg;
8553        try {
8554            pkg = pp.parsePackage(scanFile, parseFlags);
8555        } catch (PackageParserException e) {
8556            throw PackageManagerException.from(e);
8557        } finally {
8558            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8559        }
8560
8561        // Static shared libraries have synthetic package names
8562        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8563            renameStaticSharedLibraryPackage(pkg);
8564        }
8565
8566        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8567    }
8568
8569    /**
8570     *  Scans a package and returns the newly parsed package.
8571     *  @throws PackageManagerException on a parse error.
8572     */
8573    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8574            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8575            throws PackageManagerException {
8576        // If the package has children and this is the first dive in the function
8577        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8578        // packages (parent and children) would be successfully scanned before the
8579        // actual scan since scanning mutates internal state and we want to atomically
8580        // install the package and its children.
8581        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8582            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8583                scanFlags |= SCAN_CHECK_ONLY;
8584            }
8585        } else {
8586            scanFlags &= ~SCAN_CHECK_ONLY;
8587        }
8588
8589        // Scan the parent
8590        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8591                scanFlags, currentTime, user);
8592
8593        // Scan the children
8594        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8595        for (int i = 0; i < childCount; i++) {
8596            PackageParser.Package childPackage = pkg.childPackages.get(i);
8597            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8598                    currentTime, user);
8599        }
8600
8601
8602        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8603            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8604        }
8605
8606        return scannedPkg;
8607    }
8608
8609    /**
8610     *  Scans a package and returns the newly parsed package.
8611     *  @throws PackageManagerException on a parse error.
8612     */
8613    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8614            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8615            throws PackageManagerException {
8616        PackageSetting ps = null;
8617        PackageSetting updatedPkg;
8618        // reader
8619        synchronized (mPackages) {
8620            // Look to see if we already know about this package.
8621            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8622            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8623                // This package has been renamed to its original name.  Let's
8624                // use that.
8625                ps = mSettings.getPackageLPr(oldName);
8626            }
8627            // If there was no original package, see one for the real package name.
8628            if (ps == null) {
8629                ps = mSettings.getPackageLPr(pkg.packageName);
8630            }
8631            // Check to see if this package could be hiding/updating a system
8632            // package.  Must look for it either under the original or real
8633            // package name depending on our state.
8634            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8635            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8636
8637            // If this is a package we don't know about on the system partition, we
8638            // may need to remove disabled child packages on the system partition
8639            // or may need to not add child packages if the parent apk is updated
8640            // on the data partition and no longer defines this child package.
8641            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8642                // If this is a parent package for an updated system app and this system
8643                // app got an OTA update which no longer defines some of the child packages
8644                // we have to prune them from the disabled system packages.
8645                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8646                if (disabledPs != null) {
8647                    final int scannedChildCount = (pkg.childPackages != null)
8648                            ? pkg.childPackages.size() : 0;
8649                    final int disabledChildCount = disabledPs.childPackageNames != null
8650                            ? disabledPs.childPackageNames.size() : 0;
8651                    for (int i = 0; i < disabledChildCount; i++) {
8652                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8653                        boolean disabledPackageAvailable = false;
8654                        for (int j = 0; j < scannedChildCount; j++) {
8655                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8656                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8657                                disabledPackageAvailable = true;
8658                                break;
8659                            }
8660                         }
8661                         if (!disabledPackageAvailable) {
8662                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8663                         }
8664                    }
8665                }
8666            }
8667        }
8668
8669        final boolean isUpdatedPkg = updatedPkg != null;
8670        final boolean isUpdatedSystemPkg = isUpdatedPkg
8671                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8672        boolean isUpdatedPkgBetter = false;
8673        // First check if this is a system package that may involve an update
8674        if (isUpdatedSystemPkg) {
8675            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8676            // it needs to drop FLAG_PRIVILEGED.
8677            if (locationIsPrivileged(scanFile)) {
8678                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8679            } else {
8680                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8681            }
8682            // If new package is not located in "/oem" (e.g. due to an OTA),
8683            // it needs to drop FLAG_OEM.
8684            if (locationIsOem(scanFile)) {
8685                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8686            } else {
8687                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8688            }
8689
8690            if (ps != null && !ps.codePath.equals(scanFile)) {
8691                // The path has changed from what was last scanned...  check the
8692                // version of the new path against what we have stored to determine
8693                // what to do.
8694                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8695                if (pkg.mVersionCode <= ps.versionCode) {
8696                    // The system package has been updated and the code path does not match
8697                    // Ignore entry. Skip it.
8698                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8699                            + " ignored: updated version " + ps.versionCode
8700                            + " better than this " + pkg.mVersionCode);
8701                    if (!updatedPkg.codePath.equals(scanFile)) {
8702                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8703                                + ps.name + " changing from " + updatedPkg.codePathString
8704                                + " to " + scanFile);
8705                        updatedPkg.codePath = scanFile;
8706                        updatedPkg.codePathString = scanFile.toString();
8707                        updatedPkg.resourcePath = scanFile;
8708                        updatedPkg.resourcePathString = scanFile.toString();
8709                    }
8710                    updatedPkg.pkg = pkg;
8711                    updatedPkg.versionCode = pkg.mVersionCode;
8712
8713                    // Update the disabled system child packages to point to the package too.
8714                    final int childCount = updatedPkg.childPackageNames != null
8715                            ? updatedPkg.childPackageNames.size() : 0;
8716                    for (int i = 0; i < childCount; i++) {
8717                        String childPackageName = updatedPkg.childPackageNames.get(i);
8718                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8719                                childPackageName);
8720                        if (updatedChildPkg != null) {
8721                            updatedChildPkg.pkg = pkg;
8722                            updatedChildPkg.versionCode = pkg.mVersionCode;
8723                        }
8724                    }
8725                } else {
8726                    // The current app on the system partition is better than
8727                    // what we have updated to on the data partition; switch
8728                    // back to the system partition version.
8729                    // At this point, its safely assumed that package installation for
8730                    // apps in system partition will go through. If not there won't be a working
8731                    // version of the app
8732                    // writer
8733                    synchronized (mPackages) {
8734                        // Just remove the loaded entries from package lists.
8735                        mPackages.remove(ps.name);
8736                    }
8737
8738                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8739                            + " reverting from " + ps.codePathString
8740                            + ": new version " + pkg.mVersionCode
8741                            + " better than installed " + ps.versionCode);
8742
8743                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8744                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8745                    synchronized (mInstallLock) {
8746                        args.cleanUpResourcesLI();
8747                    }
8748                    synchronized (mPackages) {
8749                        mSettings.enableSystemPackageLPw(ps.name);
8750                    }
8751                    isUpdatedPkgBetter = true;
8752                }
8753            }
8754        }
8755
8756        String resourcePath = null;
8757        String baseResourcePath = null;
8758        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8759            if (ps != null && ps.resourcePathString != null) {
8760                resourcePath = ps.resourcePathString;
8761                baseResourcePath = ps.resourcePathString;
8762            } else {
8763                // Should not happen at all. Just log an error.
8764                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8765            }
8766        } else {
8767            resourcePath = pkg.codePath;
8768            baseResourcePath = pkg.baseCodePath;
8769        }
8770
8771        // Set application objects path explicitly.
8772        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8773        pkg.setApplicationInfoCodePath(pkg.codePath);
8774        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8775        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8776        pkg.setApplicationInfoResourcePath(resourcePath);
8777        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8778        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8779
8780        // throw an exception if we have an update to a system application, but, it's not more
8781        // recent than the package we've already scanned
8782        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8783            // Set CPU Abis to application info.
8784            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8785                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8786                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8787            } else {
8788                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8789                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8790            }
8791
8792            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8793                    + scanFile + " ignored: updated version " + ps.versionCode
8794                    + " better than this " + pkg.mVersionCode);
8795        }
8796
8797        if (isUpdatedPkg) {
8798            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8799            // initially
8800            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8801
8802            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8803            // flag set initially
8804            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8805                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8806            }
8807
8808            // An updated OEM app will not have the PARSE_IS_OEM
8809            // flag set initially
8810            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8811                policyFlags |= PackageParser.PARSE_IS_OEM;
8812            }
8813        }
8814
8815        // Verify certificates against what was last scanned
8816        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8817
8818        /*
8819         * A new system app appeared, but we already had a non-system one of the
8820         * same name installed earlier.
8821         */
8822        boolean shouldHideSystemApp = false;
8823        if (!isUpdatedPkg && ps != null
8824                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8825            /*
8826             * Check to make sure the signatures match first. If they don't,
8827             * wipe the installed application and its data.
8828             */
8829            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8830                    != PackageManager.SIGNATURE_MATCH) {
8831                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8832                        + " signatures don't match existing userdata copy; removing");
8833                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8834                        "scanPackageInternalLI")) {
8835                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8836                }
8837                ps = null;
8838            } else {
8839                /*
8840                 * If the newly-added system app is an older version than the
8841                 * already installed version, hide it. It will be scanned later
8842                 * and re-added like an update.
8843                 */
8844                if (pkg.mVersionCode <= ps.versionCode) {
8845                    shouldHideSystemApp = true;
8846                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8847                            + " but new version " + pkg.mVersionCode + " better than installed "
8848                            + ps.versionCode + "; hiding system");
8849                } else {
8850                    /*
8851                     * The newly found system app is a newer version that the
8852                     * one previously installed. Simply remove the
8853                     * already-installed application and replace it with our own
8854                     * while keeping the application data.
8855                     */
8856                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8857                            + " reverting from " + ps.codePathString + ": new version "
8858                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8859                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8860                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8861                    synchronized (mInstallLock) {
8862                        args.cleanUpResourcesLI();
8863                    }
8864                }
8865            }
8866        }
8867
8868        // The apk is forward locked (not public) if its code and resources
8869        // are kept in different files. (except for app in either system or
8870        // vendor path).
8871        // TODO grab this value from PackageSettings
8872        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8873            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8874                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8875            }
8876        }
8877
8878        final int userId = ((user == null) ? 0 : user.getIdentifier());
8879        if (ps != null && ps.getInstantApp(userId)) {
8880            scanFlags |= SCAN_AS_INSTANT_APP;
8881        }
8882        if (ps != null && ps.getVirtulalPreload(userId)) {
8883            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8884        }
8885
8886        // Note that we invoke the following method only if we are about to unpack an application
8887        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8888                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8889
8890        /*
8891         * If the system app should be overridden by a previously installed
8892         * data, hide the system app now and let the /data/app scan pick it up
8893         * again.
8894         */
8895        if (shouldHideSystemApp) {
8896            synchronized (mPackages) {
8897                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8898            }
8899        }
8900
8901        return scannedPkg;
8902    }
8903
8904    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8905        // Derive the new package synthetic package name
8906        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8907                + pkg.staticSharedLibVersion);
8908    }
8909
8910    private static String fixProcessName(String defProcessName,
8911            String processName) {
8912        if (processName == null) {
8913            return defProcessName;
8914        }
8915        return processName;
8916    }
8917
8918    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8919            throws PackageManagerException {
8920        if (pkgSetting.signatures.mSignatures != null) {
8921            // Already existing package. Make sure signatures match
8922            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8923                    == PackageManager.SIGNATURE_MATCH;
8924            if (!match) {
8925                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8926                        == PackageManager.SIGNATURE_MATCH;
8927            }
8928            if (!match) {
8929                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8930                        == PackageManager.SIGNATURE_MATCH;
8931            }
8932            if (!match) {
8933                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8934                        + pkg.packageName + " signatures do not match the "
8935                        + "previously installed version; ignoring!");
8936            }
8937        }
8938
8939        // Check for shared user signatures
8940        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8941            // Already existing package. Make sure signatures match
8942            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8943                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8944            if (!match) {
8945                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8946                        == PackageManager.SIGNATURE_MATCH;
8947            }
8948            if (!match) {
8949                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8950                        == PackageManager.SIGNATURE_MATCH;
8951            }
8952            if (!match) {
8953                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8954                        "Package " + pkg.packageName
8955                        + " has no signatures that match those in shared user "
8956                        + pkgSetting.sharedUser.name + "; ignoring!");
8957            }
8958        }
8959    }
8960
8961    /**
8962     * Enforces that only the system UID or root's UID can call a method exposed
8963     * via Binder.
8964     *
8965     * @param message used as message if SecurityException is thrown
8966     * @throws SecurityException if the caller is not system or root
8967     */
8968    private static final void enforceSystemOrRoot(String message) {
8969        final int uid = Binder.getCallingUid();
8970        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8971            throw new SecurityException(message);
8972        }
8973    }
8974
8975    @Override
8976    public void performFstrimIfNeeded() {
8977        enforceSystemOrRoot("Only the system can request fstrim");
8978
8979        // Before everything else, see whether we need to fstrim.
8980        try {
8981            IStorageManager sm = PackageHelper.getStorageManager();
8982            if (sm != null) {
8983                boolean doTrim = false;
8984                final long interval = android.provider.Settings.Global.getLong(
8985                        mContext.getContentResolver(),
8986                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8987                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8988                if (interval > 0) {
8989                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8990                    if (timeSinceLast > interval) {
8991                        doTrim = true;
8992                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8993                                + "; running immediately");
8994                    }
8995                }
8996                if (doTrim) {
8997                    final boolean dexOptDialogShown;
8998                    synchronized (mPackages) {
8999                        dexOptDialogShown = mDexOptDialogShown;
9000                    }
9001                    if (!isFirstBoot() && dexOptDialogShown) {
9002                        try {
9003                            ActivityManager.getService().showBootMessage(
9004                                    mContext.getResources().getString(
9005                                            R.string.android_upgrading_fstrim), true);
9006                        } catch (RemoteException e) {
9007                        }
9008                    }
9009                    sm.runMaintenance();
9010                }
9011            } else {
9012                Slog.e(TAG, "storageManager service unavailable!");
9013            }
9014        } catch (RemoteException e) {
9015            // Can't happen; StorageManagerService is local
9016        }
9017    }
9018
9019    @Override
9020    public void updatePackagesIfNeeded() {
9021        enforceSystemOrRoot("Only the system can request package update");
9022
9023        // We need to re-extract after an OTA.
9024        boolean causeUpgrade = isUpgrade();
9025
9026        // First boot or factory reset.
9027        // Note: we also handle devices that are upgrading to N right now as if it is their
9028        //       first boot, as they do not have profile data.
9029        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9030
9031        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9032        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9033
9034        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9035            return;
9036        }
9037
9038        List<PackageParser.Package> pkgs;
9039        synchronized (mPackages) {
9040            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9041        }
9042
9043        final long startTime = System.nanoTime();
9044        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9045                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9046                    false /* bootComplete */);
9047
9048        final int elapsedTimeSeconds =
9049                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9050
9051        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9052        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9053        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9054        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9055        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9056    }
9057
9058    /*
9059     * Return the prebuilt profile path given a package base code path.
9060     */
9061    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9062        return pkg.baseCodePath + ".prof";
9063    }
9064
9065    /**
9066     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9067     * containing statistics about the invocation. The array consists of three elements,
9068     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9069     * and {@code numberOfPackagesFailed}.
9070     */
9071    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9072            final String compilerFilter, boolean bootComplete) {
9073
9074        int numberOfPackagesVisited = 0;
9075        int numberOfPackagesOptimized = 0;
9076        int numberOfPackagesSkipped = 0;
9077        int numberOfPackagesFailed = 0;
9078        final int numberOfPackagesToDexopt = pkgs.size();
9079
9080        for (PackageParser.Package pkg : pkgs) {
9081            numberOfPackagesVisited++;
9082
9083            boolean useProfileForDexopt = false;
9084
9085            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9086                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9087                // that are already compiled.
9088                File profileFile = new File(getPrebuildProfilePath(pkg));
9089                // Copy profile if it exists.
9090                if (profileFile.exists()) {
9091                    try {
9092                        // We could also do this lazily before calling dexopt in
9093                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9094                        // is that we don't have a good way to say "do this only once".
9095                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9096                                pkg.applicationInfo.uid, pkg.packageName)) {
9097                            Log.e(TAG, "Installer failed to copy system profile!");
9098                        } else {
9099                            // Disabled as this causes speed-profile compilation during first boot
9100                            // even if things are already compiled.
9101                            // useProfileForDexopt = true;
9102                        }
9103                    } catch (Exception e) {
9104                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9105                                e);
9106                    }
9107                } else {
9108                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9109                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9110                    // minimize the number off apps being speed-profile compiled during first boot.
9111                    // The other paths will not change the filter.
9112                    if (disabledPs != null && disabledPs.pkg.isStub) {
9113                        // The package is the stub one, remove the stub suffix to get the normal
9114                        // package and APK names.
9115                        String systemProfilePath =
9116                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9117                        File systemProfile = new File(systemProfilePath);
9118                        // Use the profile for compilation if there exists one for the same package
9119                        // in the system partition.
9120                        useProfileForDexopt = systemProfile.exists();
9121                    }
9122                }
9123            }
9124
9125            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9126                if (DEBUG_DEXOPT) {
9127                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9128                }
9129                numberOfPackagesSkipped++;
9130                continue;
9131            }
9132
9133            if (DEBUG_DEXOPT) {
9134                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9135                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9136            }
9137
9138            if (showDialog) {
9139                try {
9140                    ActivityManager.getService().showBootMessage(
9141                            mContext.getResources().getString(R.string.android_upgrading_apk,
9142                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9143                } catch (RemoteException e) {
9144                }
9145                synchronized (mPackages) {
9146                    mDexOptDialogShown = true;
9147                }
9148            }
9149
9150            String pkgCompilerFilter = compilerFilter;
9151            if (useProfileForDexopt) {
9152                // Use background dexopt mode to try and use the profile. Note that this does not
9153                // guarantee usage of the profile.
9154                pkgCompilerFilter =
9155                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9156                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9157            }
9158
9159            // checkProfiles is false to avoid merging profiles during boot which
9160            // might interfere with background compilation (b/28612421).
9161            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9162            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9163            // trade-off worth doing to save boot time work.
9164            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9165            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9166                    pkg.packageName,
9167                    pkgCompilerFilter,
9168                    dexoptFlags));
9169
9170            switch (primaryDexOptStaus) {
9171                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9172                    numberOfPackagesOptimized++;
9173                    break;
9174                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9175                    numberOfPackagesSkipped++;
9176                    break;
9177                case PackageDexOptimizer.DEX_OPT_FAILED:
9178                    numberOfPackagesFailed++;
9179                    break;
9180                default:
9181                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9182                    break;
9183            }
9184        }
9185
9186        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9187                numberOfPackagesFailed };
9188    }
9189
9190    @Override
9191    public void notifyPackageUse(String packageName, int reason) {
9192        synchronized (mPackages) {
9193            final int callingUid = Binder.getCallingUid();
9194            final int callingUserId = UserHandle.getUserId(callingUid);
9195            if (getInstantAppPackageName(callingUid) != null) {
9196                if (!isCallerSameApp(packageName, callingUid)) {
9197                    return;
9198                }
9199            } else {
9200                if (isInstantApp(packageName, callingUserId)) {
9201                    return;
9202                }
9203            }
9204            notifyPackageUseLocked(packageName, reason);
9205        }
9206    }
9207
9208    private void notifyPackageUseLocked(String packageName, int reason) {
9209        final PackageParser.Package p = mPackages.get(packageName);
9210        if (p == null) {
9211            return;
9212        }
9213        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9214    }
9215
9216    @Override
9217    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9218            List<String> classPaths, String loaderIsa) {
9219        int userId = UserHandle.getCallingUserId();
9220        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9221        if (ai == null) {
9222            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9223                + loadingPackageName + ", user=" + userId);
9224            return;
9225        }
9226        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9227    }
9228
9229    @Override
9230    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9231            IDexModuleRegisterCallback callback) {
9232        int userId = UserHandle.getCallingUserId();
9233        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9234        DexManager.RegisterDexModuleResult result;
9235        if (ai == null) {
9236            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9237                     " calling user. package=" + packageName + ", user=" + userId);
9238            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9239        } else {
9240            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9241        }
9242
9243        if (callback != null) {
9244            mHandler.post(() -> {
9245                try {
9246                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9247                } catch (RemoteException e) {
9248                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9249                }
9250            });
9251        }
9252    }
9253
9254    /**
9255     * Ask the package manager to perform a dex-opt with the given compiler filter.
9256     *
9257     * Note: exposed only for the shell command to allow moving packages explicitly to a
9258     *       definite state.
9259     */
9260    @Override
9261    public boolean performDexOptMode(String packageName,
9262            boolean checkProfiles, String targetCompilerFilter, boolean force,
9263            boolean bootComplete, String splitName) {
9264        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9265                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9266                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9267        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9268                splitName, flags));
9269    }
9270
9271    /**
9272     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9273     * secondary dex files belonging to the given package.
9274     *
9275     * Note: exposed only for the shell command to allow moving packages explicitly to a
9276     *       definite state.
9277     */
9278    @Override
9279    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9280            boolean force) {
9281        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9282                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9283                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9284                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9285        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9286    }
9287
9288    /*package*/ boolean performDexOpt(DexoptOptions options) {
9289        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9290            return false;
9291        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9292            return false;
9293        }
9294
9295        if (options.isDexoptOnlySecondaryDex()) {
9296            return mDexManager.dexoptSecondaryDex(options);
9297        } else {
9298            int dexoptStatus = performDexOptWithStatus(options);
9299            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9300        }
9301    }
9302
9303    /**
9304     * Perform dexopt on the given package and return one of following result:
9305     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9306     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9307     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9308     */
9309    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9310        return performDexOptTraced(options);
9311    }
9312
9313    private int performDexOptTraced(DexoptOptions options) {
9314        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9315        try {
9316            return performDexOptInternal(options);
9317        } finally {
9318            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9319        }
9320    }
9321
9322    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9323    // if the package can now be considered up to date for the given filter.
9324    private int performDexOptInternal(DexoptOptions options) {
9325        PackageParser.Package p;
9326        synchronized (mPackages) {
9327            p = mPackages.get(options.getPackageName());
9328            if (p == null) {
9329                // Package could not be found. Report failure.
9330                return PackageDexOptimizer.DEX_OPT_FAILED;
9331            }
9332            mPackageUsage.maybeWriteAsync(mPackages);
9333            mCompilerStats.maybeWriteAsync();
9334        }
9335        long callingId = Binder.clearCallingIdentity();
9336        try {
9337            synchronized (mInstallLock) {
9338                return performDexOptInternalWithDependenciesLI(p, options);
9339            }
9340        } finally {
9341            Binder.restoreCallingIdentity(callingId);
9342        }
9343    }
9344
9345    public ArraySet<String> getOptimizablePackages() {
9346        ArraySet<String> pkgs = new ArraySet<String>();
9347        synchronized (mPackages) {
9348            for (PackageParser.Package p : mPackages.values()) {
9349                if (PackageDexOptimizer.canOptimizePackage(p)) {
9350                    pkgs.add(p.packageName);
9351                }
9352            }
9353        }
9354        return pkgs;
9355    }
9356
9357    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9358            DexoptOptions options) {
9359        // Select the dex optimizer based on the force parameter.
9360        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9361        //       allocate an object here.
9362        PackageDexOptimizer pdo = options.isForce()
9363                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9364                : mPackageDexOptimizer;
9365
9366        // Dexopt all dependencies first. Note: we ignore the return value and march on
9367        // on errors.
9368        // Note that we are going to call performDexOpt on those libraries as many times as
9369        // they are referenced in packages. When we do a batch of performDexOpt (for example
9370        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9371        // and the first package that uses the library will dexopt it. The
9372        // others will see that the compiled code for the library is up to date.
9373        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9374        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9375        if (!deps.isEmpty()) {
9376            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9377                    options.getCompilerFilter(), options.getSplitName(),
9378                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9379            for (PackageParser.Package depPackage : deps) {
9380                // TODO: Analyze and investigate if we (should) profile libraries.
9381                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9382                        getOrCreateCompilerPackageStats(depPackage),
9383                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9384            }
9385        }
9386        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9387                getOrCreateCompilerPackageStats(p),
9388                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9389    }
9390
9391    /**
9392     * Reconcile the information we have about the secondary dex files belonging to
9393     * {@code packagName} and the actual dex files. For all dex files that were
9394     * deleted, update the internal records and delete the generated oat files.
9395     */
9396    @Override
9397    public void reconcileSecondaryDexFiles(String packageName) {
9398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9399            return;
9400        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9401            return;
9402        }
9403        mDexManager.reconcileSecondaryDexFiles(packageName);
9404    }
9405
9406    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9407    // a reference there.
9408    /*package*/ DexManager getDexManager() {
9409        return mDexManager;
9410    }
9411
9412    /**
9413     * Execute the background dexopt job immediately.
9414     */
9415    @Override
9416    public boolean runBackgroundDexoptJob() {
9417        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9418            return false;
9419        }
9420        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9421    }
9422
9423    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9424        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9425                || p.usesStaticLibraries != null) {
9426            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9427            Set<String> collectedNames = new HashSet<>();
9428            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9429
9430            retValue.remove(p);
9431
9432            return retValue;
9433        } else {
9434            return Collections.emptyList();
9435        }
9436    }
9437
9438    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9439            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9440        if (!collectedNames.contains(p.packageName)) {
9441            collectedNames.add(p.packageName);
9442            collected.add(p);
9443
9444            if (p.usesLibraries != null) {
9445                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9446                        null, collected, collectedNames);
9447            }
9448            if (p.usesOptionalLibraries != null) {
9449                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9450                        null, collected, collectedNames);
9451            }
9452            if (p.usesStaticLibraries != null) {
9453                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9454                        p.usesStaticLibrariesVersions, collected, collectedNames);
9455            }
9456        }
9457    }
9458
9459    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9460            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9461        final int libNameCount = libs.size();
9462        for (int i = 0; i < libNameCount; i++) {
9463            String libName = libs.get(i);
9464            int version = (versions != null && versions.length == libNameCount)
9465                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9466            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9467            if (libPkg != null) {
9468                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9469            }
9470        }
9471    }
9472
9473    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9474        synchronized (mPackages) {
9475            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9476            if (libEntry != null) {
9477                return mPackages.get(libEntry.apk);
9478            }
9479            return null;
9480        }
9481    }
9482
9483    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9484        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9485        if (versionedLib == null) {
9486            return null;
9487        }
9488        return versionedLib.get(version);
9489    }
9490
9491    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9492        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9493                pkg.staticSharedLibName);
9494        if (versionedLib == null) {
9495            return null;
9496        }
9497        int previousLibVersion = -1;
9498        final int versionCount = versionedLib.size();
9499        for (int i = 0; i < versionCount; i++) {
9500            final int libVersion = versionedLib.keyAt(i);
9501            if (libVersion < pkg.staticSharedLibVersion) {
9502                previousLibVersion = Math.max(previousLibVersion, libVersion);
9503            }
9504        }
9505        if (previousLibVersion >= 0) {
9506            return versionedLib.get(previousLibVersion);
9507        }
9508        return null;
9509    }
9510
9511    public void shutdown() {
9512        mPackageUsage.writeNow(mPackages);
9513        mCompilerStats.writeNow();
9514        mDexManager.writePackageDexUsageNow();
9515    }
9516
9517    @Override
9518    public void dumpProfiles(String packageName) {
9519        PackageParser.Package pkg;
9520        synchronized (mPackages) {
9521            pkg = mPackages.get(packageName);
9522            if (pkg == null) {
9523                throw new IllegalArgumentException("Unknown package: " + packageName);
9524            }
9525        }
9526        /* Only the shell, root, or the app user should be able to dump profiles. */
9527        int callingUid = Binder.getCallingUid();
9528        if (callingUid != Process.SHELL_UID &&
9529            callingUid != Process.ROOT_UID &&
9530            callingUid != pkg.applicationInfo.uid) {
9531            throw new SecurityException("dumpProfiles");
9532        }
9533
9534        synchronized (mInstallLock) {
9535            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9536            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9537            try {
9538                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9539                String codePaths = TextUtils.join(";", allCodePaths);
9540                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9541            } catch (InstallerException e) {
9542                Slog.w(TAG, "Failed to dump profiles", e);
9543            }
9544            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9545        }
9546    }
9547
9548    @Override
9549    public void forceDexOpt(String packageName) {
9550        enforceSystemOrRoot("forceDexOpt");
9551
9552        PackageParser.Package pkg;
9553        synchronized (mPackages) {
9554            pkg = mPackages.get(packageName);
9555            if (pkg == null) {
9556                throw new IllegalArgumentException("Unknown package: " + packageName);
9557            }
9558        }
9559
9560        synchronized (mInstallLock) {
9561            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9562
9563            // Whoever is calling forceDexOpt wants a compiled package.
9564            // Don't use profiles since that may cause compilation to be skipped.
9565            final int res = performDexOptInternalWithDependenciesLI(
9566                    pkg,
9567                    new DexoptOptions(packageName,
9568                            getDefaultCompilerFilter(),
9569                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9570
9571            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9572            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9573                throw new IllegalStateException("Failed to dexopt: " + res);
9574            }
9575        }
9576    }
9577
9578    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9579        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9580            Slog.w(TAG, "Unable to update from " + oldPkg.name
9581                    + " to " + newPkg.packageName
9582                    + ": old package not in system partition");
9583            return false;
9584        } else if (mPackages.get(oldPkg.name) != null) {
9585            Slog.w(TAG, "Unable to update from " + oldPkg.name
9586                    + " to " + newPkg.packageName
9587                    + ": old package still exists");
9588            return false;
9589        }
9590        return true;
9591    }
9592
9593    void removeCodePathLI(File codePath) {
9594        if (codePath.isDirectory()) {
9595            try {
9596                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9597            } catch (InstallerException e) {
9598                Slog.w(TAG, "Failed to remove code path", e);
9599            }
9600        } else {
9601            codePath.delete();
9602        }
9603    }
9604
9605    private int[] resolveUserIds(int userId) {
9606        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9607    }
9608
9609    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9610        if (pkg == null) {
9611            Slog.wtf(TAG, "Package was null!", new Throwable());
9612            return;
9613        }
9614        clearAppDataLeafLIF(pkg, userId, flags);
9615        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9616        for (int i = 0; i < childCount; i++) {
9617            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9618        }
9619    }
9620
9621    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9622        final PackageSetting ps;
9623        synchronized (mPackages) {
9624            ps = mSettings.mPackages.get(pkg.packageName);
9625        }
9626        for (int realUserId : resolveUserIds(userId)) {
9627            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9628            try {
9629                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9630                        ceDataInode);
9631            } catch (InstallerException e) {
9632                Slog.w(TAG, String.valueOf(e));
9633            }
9634        }
9635    }
9636
9637    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9638        if (pkg == null) {
9639            Slog.wtf(TAG, "Package was null!", new Throwable());
9640            return;
9641        }
9642        destroyAppDataLeafLIF(pkg, userId, flags);
9643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9644        for (int i = 0; i < childCount; i++) {
9645            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9646        }
9647    }
9648
9649    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9650        final PackageSetting ps;
9651        synchronized (mPackages) {
9652            ps = mSettings.mPackages.get(pkg.packageName);
9653        }
9654        for (int realUserId : resolveUserIds(userId)) {
9655            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9656            try {
9657                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9658                        ceDataInode);
9659            } catch (InstallerException e) {
9660                Slog.w(TAG, String.valueOf(e));
9661            }
9662            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9663        }
9664    }
9665
9666    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9667        if (pkg == null) {
9668            Slog.wtf(TAG, "Package was null!", new Throwable());
9669            return;
9670        }
9671        destroyAppProfilesLeafLIF(pkg);
9672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9673        for (int i = 0; i < childCount; i++) {
9674            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9675        }
9676    }
9677
9678    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9679        try {
9680            mInstaller.destroyAppProfiles(pkg.packageName);
9681        } catch (InstallerException e) {
9682            Slog.w(TAG, String.valueOf(e));
9683        }
9684    }
9685
9686    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9687        if (pkg == null) {
9688            Slog.wtf(TAG, "Package was null!", new Throwable());
9689            return;
9690        }
9691        clearAppProfilesLeafLIF(pkg);
9692        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9693        for (int i = 0; i < childCount; i++) {
9694            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9695        }
9696    }
9697
9698    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9699        try {
9700            mInstaller.clearAppProfiles(pkg.packageName);
9701        } catch (InstallerException e) {
9702            Slog.w(TAG, String.valueOf(e));
9703        }
9704    }
9705
9706    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9707            long lastUpdateTime) {
9708        // Set parent install/update time
9709        PackageSetting ps = (PackageSetting) pkg.mExtras;
9710        if (ps != null) {
9711            ps.firstInstallTime = firstInstallTime;
9712            ps.lastUpdateTime = lastUpdateTime;
9713        }
9714        // Set children install/update time
9715        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9716        for (int i = 0; i < childCount; i++) {
9717            PackageParser.Package childPkg = pkg.childPackages.get(i);
9718            ps = (PackageSetting) childPkg.mExtras;
9719            if (ps != null) {
9720                ps.firstInstallTime = firstInstallTime;
9721                ps.lastUpdateTime = lastUpdateTime;
9722            }
9723        }
9724    }
9725
9726    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9727            SharedLibraryEntry file,
9728            PackageParser.Package changingLib) {
9729        if (file.path != null) {
9730            usesLibraryFiles.add(file.path);
9731            return;
9732        }
9733        PackageParser.Package p = mPackages.get(file.apk);
9734        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9735            // If we are doing this while in the middle of updating a library apk,
9736            // then we need to make sure to use that new apk for determining the
9737            // dependencies here.  (We haven't yet finished committing the new apk
9738            // to the package manager state.)
9739            if (p == null || p.packageName.equals(changingLib.packageName)) {
9740                p = changingLib;
9741            }
9742        }
9743        if (p != null) {
9744            usesLibraryFiles.addAll(p.getAllCodePaths());
9745            if (p.usesLibraryFiles != null) {
9746                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9747            }
9748        }
9749    }
9750
9751    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9752            PackageParser.Package changingLib) throws PackageManagerException {
9753        if (pkg == null) {
9754            return;
9755        }
9756        // The collection used here must maintain the order of addition (so
9757        // that libraries are searched in the correct order) and must have no
9758        // duplicates.
9759        Set<String> usesLibraryFiles = null;
9760        if (pkg.usesLibraries != null) {
9761            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9762                    null, null, pkg.packageName, changingLib, true,
9763                    pkg.applicationInfo.targetSdkVersion, null);
9764        }
9765        if (pkg.usesStaticLibraries != null) {
9766            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9767                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9768                    pkg.packageName, changingLib, true,
9769                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9770        }
9771        if (pkg.usesOptionalLibraries != null) {
9772            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9773                    null, null, pkg.packageName, changingLib, false,
9774                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9775        }
9776        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9777            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9778        } else {
9779            pkg.usesLibraryFiles = null;
9780        }
9781    }
9782
9783    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9784            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9785            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9786            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9787            throws PackageManagerException {
9788        final int libCount = requestedLibraries.size();
9789        for (int i = 0; i < libCount; i++) {
9790            final String libName = requestedLibraries.get(i);
9791            final int libVersion = requiredVersions != null ? requiredVersions[i]
9792                    : SharedLibraryInfo.VERSION_UNDEFINED;
9793            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9794            if (libEntry == null) {
9795                if (required) {
9796                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9797                            "Package " + packageName + " requires unavailable shared library "
9798                                    + libName + "; failing!");
9799                } else if (DEBUG_SHARED_LIBRARIES) {
9800                    Slog.i(TAG, "Package " + packageName
9801                            + " desires unavailable shared library "
9802                            + libName + "; ignoring!");
9803                }
9804            } else {
9805                if (requiredVersions != null && requiredCertDigests != null) {
9806                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9807                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9808                            "Package " + packageName + " requires unavailable static shared"
9809                                    + " library " + libName + " version "
9810                                    + libEntry.info.getVersion() + "; failing!");
9811                    }
9812
9813                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9814                    if (libPkg == null) {
9815                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9816                                "Package " + packageName + " requires unavailable static shared"
9817                                        + " library; failing!");
9818                    }
9819
9820                    final String[] expectedCertDigests = requiredCertDigests[i];
9821                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9822                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9823                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9824                            : PackageUtils.computeSignaturesSha256Digests(
9825                                    new Signature[]{libPkg.mSignatures[0]});
9826
9827                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9828                    // target O we don't parse the "additional-certificate" tags similarly
9829                    // how we only consider all certs only for apps targeting O (see above).
9830                    // Therefore, the size check is safe to make.
9831                    if (expectedCertDigests.length != libCertDigests.length) {
9832                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9833                                "Package " + packageName + " requires differently signed" +
9834                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9835                    }
9836
9837                    // Use a predictable order as signature order may vary
9838                    Arrays.sort(libCertDigests);
9839                    Arrays.sort(expectedCertDigests);
9840
9841                    final int certCount = libCertDigests.length;
9842                    for (int j = 0; j < certCount; j++) {
9843                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9844                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9845                                    "Package " + packageName + " requires differently signed" +
9846                                            " static shared library; failing!");
9847                        }
9848                    }
9849                }
9850
9851                if (outUsedLibraries == null) {
9852                    // Use LinkedHashSet to preserve the order of files added to
9853                    // usesLibraryFiles while eliminating duplicates.
9854                    outUsedLibraries = new LinkedHashSet<>();
9855                }
9856                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9857            }
9858        }
9859        return outUsedLibraries;
9860    }
9861
9862    private static boolean hasString(List<String> list, List<String> which) {
9863        if (list == null) {
9864            return false;
9865        }
9866        for (int i=list.size()-1; i>=0; i--) {
9867            for (int j=which.size()-1; j>=0; j--) {
9868                if (which.get(j).equals(list.get(i))) {
9869                    return true;
9870                }
9871            }
9872        }
9873        return false;
9874    }
9875
9876    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9877            PackageParser.Package changingPkg) {
9878        ArrayList<PackageParser.Package> res = null;
9879        for (PackageParser.Package pkg : mPackages.values()) {
9880            if (changingPkg != null
9881                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9882                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9883                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9884                            changingPkg.staticSharedLibName)) {
9885                return null;
9886            }
9887            if (res == null) {
9888                res = new ArrayList<>();
9889            }
9890            res.add(pkg);
9891            try {
9892                updateSharedLibrariesLPr(pkg, changingPkg);
9893            } catch (PackageManagerException e) {
9894                // If a system app update or an app and a required lib missing we
9895                // delete the package and for updated system apps keep the data as
9896                // it is better for the user to reinstall than to be in an limbo
9897                // state. Also libs disappearing under an app should never happen
9898                // - just in case.
9899                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9900                    final int flags = pkg.isUpdatedSystemApp()
9901                            ? PackageManager.DELETE_KEEP_DATA : 0;
9902                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9903                            flags , null, true, null);
9904                }
9905                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9906            }
9907        }
9908        return res;
9909    }
9910
9911    /**
9912     * Derive the value of the {@code cpuAbiOverride} based on the provided
9913     * value and an optional stored value from the package settings.
9914     */
9915    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9916        String cpuAbiOverride = null;
9917
9918        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9919            cpuAbiOverride = null;
9920        } else if (abiOverride != null) {
9921            cpuAbiOverride = abiOverride;
9922        } else if (settings != null) {
9923            cpuAbiOverride = settings.cpuAbiOverrideString;
9924        }
9925
9926        return cpuAbiOverride;
9927    }
9928
9929    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9930            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9931                    throws PackageManagerException {
9932        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9933        // If the package has children and this is the first dive in the function
9934        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9935        // whether all packages (parent and children) would be successfully scanned
9936        // before the actual scan since scanning mutates internal state and we want
9937        // to atomically install the package and its children.
9938        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9939            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9940                scanFlags |= SCAN_CHECK_ONLY;
9941            }
9942        } else {
9943            scanFlags &= ~SCAN_CHECK_ONLY;
9944        }
9945
9946        final PackageParser.Package scannedPkg;
9947        try {
9948            // Scan the parent
9949            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9950            // Scan the children
9951            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9952            for (int i = 0; i < childCount; i++) {
9953                PackageParser.Package childPkg = pkg.childPackages.get(i);
9954                scanPackageLI(childPkg, policyFlags,
9955                        scanFlags, currentTime, user);
9956            }
9957        } finally {
9958            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9959        }
9960
9961        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9962            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9963        }
9964
9965        return scannedPkg;
9966    }
9967
9968    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9969            int scanFlags, long currentTime, @Nullable UserHandle user)
9970                    throws PackageManagerException {
9971        boolean success = false;
9972        try {
9973            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9974                    currentTime, user);
9975            success = true;
9976            return res;
9977        } finally {
9978            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9979                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9980                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9981                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9982                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9983            }
9984        }
9985    }
9986
9987    /**
9988     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9989     */
9990    private static boolean apkHasCode(String fileName) {
9991        StrictJarFile jarFile = null;
9992        try {
9993            jarFile = new StrictJarFile(fileName,
9994                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9995            return jarFile.findEntry("classes.dex") != null;
9996        } catch (IOException ignore) {
9997        } finally {
9998            try {
9999                if (jarFile != null) {
10000                    jarFile.close();
10001                }
10002            } catch (IOException ignore) {}
10003        }
10004        return false;
10005    }
10006
10007    /**
10008     * Enforces code policy for the package. This ensures that if an APK has
10009     * declared hasCode="true" in its manifest that the APK actually contains
10010     * code.
10011     *
10012     * @throws PackageManagerException If bytecode could not be found when it should exist
10013     */
10014    private static void assertCodePolicy(PackageParser.Package pkg)
10015            throws PackageManagerException {
10016        final boolean shouldHaveCode =
10017                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10018        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10019            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10020                    "Package " + pkg.baseCodePath + " code is missing");
10021        }
10022
10023        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10024            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10025                final boolean splitShouldHaveCode =
10026                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10027                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10028                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10029                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10030                }
10031            }
10032        }
10033    }
10034
10035    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10036            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10037                    throws PackageManagerException {
10038        if (DEBUG_PACKAGE_SCANNING) {
10039            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10040                Log.d(TAG, "Scanning package " + pkg.packageName);
10041        }
10042
10043        applyPolicy(pkg, policyFlags);
10044
10045        assertPackageIsValid(pkg, policyFlags, scanFlags);
10046
10047        if (Build.IS_DEBUGGABLE &&
10048                pkg.isPrivilegedApp() &&
10049                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10050            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10051        }
10052
10053        // Initialize package source and resource directories
10054        final File scanFile = new File(pkg.codePath);
10055        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10056        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10057
10058        SharedUserSetting suid = null;
10059        PackageSetting pkgSetting = null;
10060
10061        // Getting the package setting may have a side-effect, so if we
10062        // are only checking if scan would succeed, stash a copy of the
10063        // old setting to restore at the end.
10064        PackageSetting nonMutatedPs = null;
10065
10066        // We keep references to the derived CPU Abis from settings in oder to reuse
10067        // them in the case where we're not upgrading or booting for the first time.
10068        String primaryCpuAbiFromSettings = null;
10069        String secondaryCpuAbiFromSettings = null;
10070
10071        // writer
10072        synchronized (mPackages) {
10073            if (pkg.mSharedUserId != null) {
10074                // SIDE EFFECTS; may potentially allocate a new shared user
10075                suid = mSettings.getSharedUserLPw(
10076                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10077                if (DEBUG_PACKAGE_SCANNING) {
10078                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10079                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10080                                + "): packages=" + suid.packages);
10081                }
10082            }
10083
10084            // Check if we are renaming from an original package name.
10085            PackageSetting origPackage = null;
10086            String realName = null;
10087            if (pkg.mOriginalPackages != null) {
10088                // This package may need to be renamed to a previously
10089                // installed name.  Let's check on that...
10090                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10091                if (pkg.mOriginalPackages.contains(renamed)) {
10092                    // This package had originally been installed as the
10093                    // original name, and we have already taken care of
10094                    // transitioning to the new one.  Just update the new
10095                    // one to continue using the old name.
10096                    realName = pkg.mRealPackage;
10097                    if (!pkg.packageName.equals(renamed)) {
10098                        // Callers into this function may have already taken
10099                        // care of renaming the package; only do it here if
10100                        // it is not already done.
10101                        pkg.setPackageName(renamed);
10102                    }
10103                } else {
10104                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10105                        if ((origPackage = mSettings.getPackageLPr(
10106                                pkg.mOriginalPackages.get(i))) != null) {
10107                            // We do have the package already installed under its
10108                            // original name...  should we use it?
10109                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10110                                // New package is not compatible with original.
10111                                origPackage = null;
10112                                continue;
10113                            } else if (origPackage.sharedUser != null) {
10114                                // Make sure uid is compatible between packages.
10115                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10116                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10117                                            + " to " + pkg.packageName + ": old uid "
10118                                            + origPackage.sharedUser.name
10119                                            + " differs from " + pkg.mSharedUserId);
10120                                    origPackage = null;
10121                                    continue;
10122                                }
10123                                // TODO: Add case when shared user id is added [b/28144775]
10124                            } else {
10125                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10126                                        + pkg.packageName + " to old name " + origPackage.name);
10127                            }
10128                            break;
10129                        }
10130                    }
10131                }
10132            }
10133
10134            if (mTransferedPackages.contains(pkg.packageName)) {
10135                Slog.w(TAG, "Package " + pkg.packageName
10136                        + " was transferred to another, but its .apk remains");
10137            }
10138
10139            // See comments in nonMutatedPs declaration
10140            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10141                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10142                if (foundPs != null) {
10143                    nonMutatedPs = new PackageSetting(foundPs);
10144                }
10145            }
10146
10147            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10148                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10149                if (foundPs != null) {
10150                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10151                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10152                }
10153            }
10154
10155            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10156            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10157                PackageManagerService.reportSettingsProblem(Log.WARN,
10158                        "Package " + pkg.packageName + " shared user changed from "
10159                                + (pkgSetting.sharedUser != null
10160                                        ? pkgSetting.sharedUser.name : "<nothing>")
10161                                + " to "
10162                                + (suid != null ? suid.name : "<nothing>")
10163                                + "; replacing with new");
10164                pkgSetting = null;
10165            }
10166            final PackageSetting oldPkgSetting =
10167                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10168            final PackageSetting disabledPkgSetting =
10169                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10170
10171            String[] usesStaticLibraries = null;
10172            if (pkg.usesStaticLibraries != null) {
10173                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10174                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10175            }
10176
10177            if (pkgSetting == null) {
10178                final String parentPackageName = (pkg.parentPackage != null)
10179                        ? pkg.parentPackage.packageName : null;
10180                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10181                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10182                // REMOVE SharedUserSetting from method; update in a separate call
10183                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10184                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10185                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10186                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10187                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10188                        true /*allowInstall*/, instantApp, virtualPreload,
10189                        parentPackageName, pkg.getChildPackageNames(),
10190                        UserManagerService.getInstance(), usesStaticLibraries,
10191                        pkg.usesStaticLibrariesVersions);
10192                // SIDE EFFECTS; updates system state; move elsewhere
10193                if (origPackage != null) {
10194                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10195                }
10196                mSettings.addUserToSettingLPw(pkgSetting);
10197            } else {
10198                // REMOVE SharedUserSetting from method; update in a separate call.
10199                //
10200                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10201                // secondaryCpuAbi are not known at this point so we always update them
10202                // to null here, only to reset them at a later point.
10203                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10204                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10205                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10206                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10207                        UserManagerService.getInstance(), usesStaticLibraries,
10208                        pkg.usesStaticLibrariesVersions);
10209            }
10210            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10211            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10212
10213            // SIDE EFFECTS; modifies system state; move elsewhere
10214            if (pkgSetting.origPackage != null) {
10215                // If we are first transitioning from an original package,
10216                // fix up the new package's name now.  We need to do this after
10217                // looking up the package under its new name, so getPackageLP
10218                // can take care of fiddling things correctly.
10219                pkg.setPackageName(origPackage.name);
10220
10221                // File a report about this.
10222                String msg = "New package " + pkgSetting.realName
10223                        + " renamed to replace old package " + pkgSetting.name;
10224                reportSettingsProblem(Log.WARN, msg);
10225
10226                // Make a note of it.
10227                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10228                    mTransferedPackages.add(origPackage.name);
10229                }
10230
10231                // No longer need to retain this.
10232                pkgSetting.origPackage = null;
10233            }
10234
10235            // SIDE EFFECTS; modifies system state; move elsewhere
10236            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10237                // Make a note of it.
10238                mTransferedPackages.add(pkg.packageName);
10239            }
10240
10241            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10242                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10243            }
10244
10245            if ((scanFlags & SCAN_BOOTING) == 0
10246                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10247                // Check all shared libraries and map to their actual file path.
10248                // We only do this here for apps not on a system dir, because those
10249                // are the only ones that can fail an install due to this.  We
10250                // will take care of the system apps by updating all of their
10251                // library paths after the scan is done. Also during the initial
10252                // scan don't update any libs as we do this wholesale after all
10253                // apps are scanned to avoid dependency based scanning.
10254                updateSharedLibrariesLPr(pkg, null);
10255            }
10256
10257            if (mFoundPolicyFile) {
10258                SELinuxMMAC.assignSeInfoValue(pkg);
10259            }
10260            pkg.applicationInfo.uid = pkgSetting.appId;
10261            pkg.mExtras = pkgSetting;
10262
10263
10264            // Static shared libs have same package with different versions where
10265            // we internally use a synthetic package name to allow multiple versions
10266            // of the same package, therefore we need to compare signatures against
10267            // the package setting for the latest library version.
10268            PackageSetting signatureCheckPs = pkgSetting;
10269            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10270                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10271                if (libraryEntry != null) {
10272                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10273                }
10274            }
10275
10276            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10277                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10278                    // We just determined the app is signed correctly, so bring
10279                    // over the latest parsed certs.
10280                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10281                } else {
10282                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10283                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10284                                "Package " + pkg.packageName + " upgrade keys do not match the "
10285                                + "previously installed version");
10286                    } else {
10287                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10288                        String msg = "System package " + pkg.packageName
10289                                + " signature changed; retaining data.";
10290                        reportSettingsProblem(Log.WARN, msg);
10291                    }
10292                }
10293            } else {
10294                try {
10295                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10296                    verifySignaturesLP(signatureCheckPs, pkg);
10297                    // We just determined the app is signed correctly, so bring
10298                    // over the latest parsed certs.
10299                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10300                } catch (PackageManagerException e) {
10301                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10302                        throw e;
10303                    }
10304                    // The signature has changed, but this package is in the system
10305                    // image...  let's recover!
10306                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10307                    // However...  if this package is part of a shared user, but it
10308                    // doesn't match the signature of the shared user, let's fail.
10309                    // What this means is that you can't change the signatures
10310                    // associated with an overall shared user, which doesn't seem all
10311                    // that unreasonable.
10312                    if (signatureCheckPs.sharedUser != null) {
10313                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10314                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10315                            throw new PackageManagerException(
10316                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10317                                    "Signature mismatch for shared user: "
10318                                            + pkgSetting.sharedUser);
10319                        }
10320                    }
10321                    // File a report about this.
10322                    String msg = "System package " + pkg.packageName
10323                            + " signature changed; retaining data.";
10324                    reportSettingsProblem(Log.WARN, msg);
10325                }
10326            }
10327
10328            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10329                // This package wants to adopt ownership of permissions from
10330                // another package.
10331                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10332                    final String origName = pkg.mAdoptPermissions.get(i);
10333                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10334                    if (orig != null) {
10335                        if (verifyPackageUpdateLPr(orig, pkg)) {
10336                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10337                                    + pkg.packageName);
10338                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10339                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10340                        }
10341                    }
10342                }
10343            }
10344        }
10345
10346        pkg.applicationInfo.processName = fixProcessName(
10347                pkg.applicationInfo.packageName,
10348                pkg.applicationInfo.processName);
10349
10350        if (pkg != mPlatformPackage) {
10351            // Get all of our default paths setup
10352            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10353        }
10354
10355        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10356
10357        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10358            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10359                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10360                final boolean extractNativeLibs = !pkg.isLibrary();
10361                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10362                        mAppLib32InstallDir);
10363                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10364
10365                // Some system apps still use directory structure for native libraries
10366                // in which case we might end up not detecting abi solely based on apk
10367                // structure. Try to detect abi based on directory structure.
10368                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10369                        pkg.applicationInfo.primaryCpuAbi == null) {
10370                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10371                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10372                }
10373            } else {
10374                // This is not a first boot or an upgrade, don't bother deriving the
10375                // ABI during the scan. Instead, trust the value that was stored in the
10376                // package setting.
10377                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10378                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10379
10380                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10381
10382                if (DEBUG_ABI_SELECTION) {
10383                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10384                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10385                        pkg.applicationInfo.secondaryCpuAbi);
10386                }
10387            }
10388        } else {
10389            if ((scanFlags & SCAN_MOVE) != 0) {
10390                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10391                // but we already have this packages package info in the PackageSetting. We just
10392                // use that and derive the native library path based on the new codepath.
10393                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10394                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10395            }
10396
10397            // Set native library paths again. For moves, the path will be updated based on the
10398            // ABIs we've determined above. For non-moves, the path will be updated based on the
10399            // ABIs we determined during compilation, but the path will depend on the final
10400            // package path (after the rename away from the stage path).
10401            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10402        }
10403
10404        // This is a special case for the "system" package, where the ABI is
10405        // dictated by the zygote configuration (and init.rc). We should keep track
10406        // of this ABI so that we can deal with "normal" applications that run under
10407        // the same UID correctly.
10408        if (mPlatformPackage == pkg) {
10409            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10410                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10411        }
10412
10413        // If there's a mismatch between the abi-override in the package setting
10414        // and the abiOverride specified for the install. Warn about this because we
10415        // would've already compiled the app without taking the package setting into
10416        // account.
10417        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10418            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10419                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10420                        " for package " + pkg.packageName);
10421            }
10422        }
10423
10424        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10425        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10426        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10427
10428        // Copy the derived override back to the parsed package, so that we can
10429        // update the package settings accordingly.
10430        pkg.cpuAbiOverride = cpuAbiOverride;
10431
10432        if (DEBUG_ABI_SELECTION) {
10433            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10434                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10435                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10436        }
10437
10438        // Push the derived path down into PackageSettings so we know what to
10439        // clean up at uninstall time.
10440        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10441
10442        if (DEBUG_ABI_SELECTION) {
10443            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10444                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10445                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10446        }
10447
10448        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10449        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10450            // We don't do this here during boot because we can do it all
10451            // at once after scanning all existing packages.
10452            //
10453            // We also do this *before* we perform dexopt on this package, so that
10454            // we can avoid redundant dexopts, and also to make sure we've got the
10455            // code and package path correct.
10456            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10457        }
10458
10459        if (mFactoryTest && pkg.requestedPermissions.contains(
10460                android.Manifest.permission.FACTORY_TEST)) {
10461            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10462        }
10463
10464        if (isSystemApp(pkg)) {
10465            pkgSetting.isOrphaned = true;
10466        }
10467
10468        // Take care of first install / last update times.
10469        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10470        if (currentTime != 0) {
10471            if (pkgSetting.firstInstallTime == 0) {
10472                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10473            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10474                pkgSetting.lastUpdateTime = currentTime;
10475            }
10476        } else if (pkgSetting.firstInstallTime == 0) {
10477            // We need *something*.  Take time time stamp of the file.
10478            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10479        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10480            if (scanFileTime != pkgSetting.timeStamp) {
10481                // A package on the system image has changed; consider this
10482                // to be an update.
10483                pkgSetting.lastUpdateTime = scanFileTime;
10484            }
10485        }
10486        pkgSetting.setTimeStamp(scanFileTime);
10487
10488        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10489            if (nonMutatedPs != null) {
10490                synchronized (mPackages) {
10491                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10492                }
10493            }
10494        } else {
10495            final int userId = user == null ? 0 : user.getIdentifier();
10496            // Modify state for the given package setting
10497            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10498                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10499            if (pkgSetting.getInstantApp(userId)) {
10500                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10501            }
10502        }
10503        return pkg;
10504    }
10505
10506    /**
10507     * Applies policy to the parsed package based upon the given policy flags.
10508     * Ensures the package is in a good state.
10509     * <p>
10510     * Implementation detail: This method must NOT have any side effect. It would
10511     * ideally be static, but, it requires locks to read system state.
10512     */
10513    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10514        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10515            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10516            if (pkg.applicationInfo.isDirectBootAware()) {
10517                // we're direct boot aware; set for all components
10518                for (PackageParser.Service s : pkg.services) {
10519                    s.info.encryptionAware = s.info.directBootAware = true;
10520                }
10521                for (PackageParser.Provider p : pkg.providers) {
10522                    p.info.encryptionAware = p.info.directBootAware = true;
10523                }
10524                for (PackageParser.Activity a : pkg.activities) {
10525                    a.info.encryptionAware = a.info.directBootAware = true;
10526                }
10527                for (PackageParser.Activity r : pkg.receivers) {
10528                    r.info.encryptionAware = r.info.directBootAware = true;
10529                }
10530            }
10531            if (compressedFileExists(pkg.codePath)) {
10532                pkg.isStub = true;
10533            }
10534        } else {
10535            // Only allow system apps to be flagged as core apps.
10536            pkg.coreApp = false;
10537            // clear flags not applicable to regular apps
10538            pkg.applicationInfo.privateFlags &=
10539                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10540            pkg.applicationInfo.privateFlags &=
10541                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10542        }
10543        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10544
10545        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10546            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10547        }
10548
10549        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10550            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10551        }
10552
10553        if (!isSystemApp(pkg)) {
10554            // Only system apps can use these features.
10555            pkg.mOriginalPackages = null;
10556            pkg.mRealPackage = null;
10557            pkg.mAdoptPermissions = null;
10558        }
10559    }
10560
10561    /**
10562     * Asserts the parsed package is valid according to the given policy. If the
10563     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10564     * <p>
10565     * Implementation detail: This method must NOT have any side effects. It would
10566     * ideally be static, but, it requires locks to read system state.
10567     *
10568     * @throws PackageManagerException If the package fails any of the validation checks
10569     */
10570    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10571            throws PackageManagerException {
10572        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10573            assertCodePolicy(pkg);
10574        }
10575
10576        if (pkg.applicationInfo.getCodePath() == null ||
10577                pkg.applicationInfo.getResourcePath() == null) {
10578            // Bail out. The resource and code paths haven't been set.
10579            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10580                    "Code and resource paths haven't been set correctly");
10581        }
10582
10583        // Make sure we're not adding any bogus keyset info
10584        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10585        ksms.assertScannedPackageValid(pkg);
10586
10587        synchronized (mPackages) {
10588            // The special "android" package can only be defined once
10589            if (pkg.packageName.equals("android")) {
10590                if (mAndroidApplication != null) {
10591                    Slog.w(TAG, "*************************************************");
10592                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10593                    Slog.w(TAG, " codePath=" + pkg.codePath);
10594                    Slog.w(TAG, "*************************************************");
10595                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10596                            "Core android package being redefined.  Skipping.");
10597                }
10598            }
10599
10600            // A package name must be unique; don't allow duplicates
10601            if (mPackages.containsKey(pkg.packageName)) {
10602                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10603                        "Application package " + pkg.packageName
10604                        + " already installed.  Skipping duplicate.");
10605            }
10606
10607            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10608                // Static libs have a synthetic package name containing the version
10609                // but we still want the base name to be unique.
10610                if (mPackages.containsKey(pkg.manifestPackageName)) {
10611                    throw new PackageManagerException(
10612                            "Duplicate static shared lib provider package");
10613                }
10614
10615                // Static shared libraries should have at least O target SDK
10616                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10617                    throw new PackageManagerException(
10618                            "Packages declaring static-shared libs must target O SDK or higher");
10619                }
10620
10621                // Package declaring static a shared lib cannot be instant apps
10622                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10623                    throw new PackageManagerException(
10624                            "Packages declaring static-shared libs cannot be instant apps");
10625                }
10626
10627                // Package declaring static a shared lib cannot be renamed since the package
10628                // name is synthetic and apps can't code around package manager internals.
10629                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10630                    throw new PackageManagerException(
10631                            "Packages declaring static-shared libs cannot be renamed");
10632                }
10633
10634                // Package declaring static a shared lib cannot declare child packages
10635                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10636                    throw new PackageManagerException(
10637                            "Packages declaring static-shared libs cannot have child packages");
10638                }
10639
10640                // Package declaring static a shared lib cannot declare dynamic libs
10641                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10642                    throw new PackageManagerException(
10643                            "Packages declaring static-shared libs cannot declare dynamic libs");
10644                }
10645
10646                // Package declaring static a shared lib cannot declare shared users
10647                if (pkg.mSharedUserId != null) {
10648                    throw new PackageManagerException(
10649                            "Packages declaring static-shared libs cannot declare shared users");
10650                }
10651
10652                // Static shared libs cannot declare activities
10653                if (!pkg.activities.isEmpty()) {
10654                    throw new PackageManagerException(
10655                            "Static shared libs cannot declare activities");
10656                }
10657
10658                // Static shared libs cannot declare services
10659                if (!pkg.services.isEmpty()) {
10660                    throw new PackageManagerException(
10661                            "Static shared libs cannot declare services");
10662                }
10663
10664                // Static shared libs cannot declare providers
10665                if (!pkg.providers.isEmpty()) {
10666                    throw new PackageManagerException(
10667                            "Static shared libs cannot declare content providers");
10668                }
10669
10670                // Static shared libs cannot declare receivers
10671                if (!pkg.receivers.isEmpty()) {
10672                    throw new PackageManagerException(
10673                            "Static shared libs cannot declare broadcast receivers");
10674                }
10675
10676                // Static shared libs cannot declare permission groups
10677                if (!pkg.permissionGroups.isEmpty()) {
10678                    throw new PackageManagerException(
10679                            "Static shared libs cannot declare permission groups");
10680                }
10681
10682                // Static shared libs cannot declare permissions
10683                if (!pkg.permissions.isEmpty()) {
10684                    throw new PackageManagerException(
10685                            "Static shared libs cannot declare permissions");
10686                }
10687
10688                // Static shared libs cannot declare protected broadcasts
10689                if (pkg.protectedBroadcasts != null) {
10690                    throw new PackageManagerException(
10691                            "Static shared libs cannot declare protected broadcasts");
10692                }
10693
10694                // Static shared libs cannot be overlay targets
10695                if (pkg.mOverlayTarget != null) {
10696                    throw new PackageManagerException(
10697                            "Static shared libs cannot be overlay targets");
10698                }
10699
10700                // The version codes must be ordered as lib versions
10701                int minVersionCode = Integer.MIN_VALUE;
10702                int maxVersionCode = Integer.MAX_VALUE;
10703
10704                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10705                        pkg.staticSharedLibName);
10706                if (versionedLib != null) {
10707                    final int versionCount = versionedLib.size();
10708                    for (int i = 0; i < versionCount; i++) {
10709                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10710                        final int libVersionCode = libInfo.getDeclaringPackage()
10711                                .getVersionCode();
10712                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10713                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10714                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10715                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10716                        } else {
10717                            minVersionCode = maxVersionCode = libVersionCode;
10718                            break;
10719                        }
10720                    }
10721                }
10722                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10723                    throw new PackageManagerException("Static shared"
10724                            + " lib version codes must be ordered as lib versions");
10725                }
10726            }
10727
10728            // Only privileged apps and updated privileged apps can add child packages.
10729            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10730                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10731                    throw new PackageManagerException("Only privileged apps can add child "
10732                            + "packages. Ignoring package " + pkg.packageName);
10733                }
10734                final int childCount = pkg.childPackages.size();
10735                for (int i = 0; i < childCount; i++) {
10736                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10737                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10738                            childPkg.packageName)) {
10739                        throw new PackageManagerException("Can't override child of "
10740                                + "another disabled app. Ignoring package " + pkg.packageName);
10741                    }
10742                }
10743            }
10744
10745            // If we're only installing presumed-existing packages, require that the
10746            // scanned APK is both already known and at the path previously established
10747            // for it.  Previously unknown packages we pick up normally, but if we have an
10748            // a priori expectation about this package's install presence, enforce it.
10749            // With a singular exception for new system packages. When an OTA contains
10750            // a new system package, we allow the codepath to change from a system location
10751            // to the user-installed location. If we don't allow this change, any newer,
10752            // user-installed version of the application will be ignored.
10753            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10754                if (mExpectingBetter.containsKey(pkg.packageName)) {
10755                    logCriticalInfo(Log.WARN,
10756                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10757                } else {
10758                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10759                    if (known != null) {
10760                        if (DEBUG_PACKAGE_SCANNING) {
10761                            Log.d(TAG, "Examining " + pkg.codePath
10762                                    + " and requiring known paths " + known.codePathString
10763                                    + " & " + known.resourcePathString);
10764                        }
10765                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10766                                || !pkg.applicationInfo.getResourcePath().equals(
10767                                        known.resourcePathString)) {
10768                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10769                                    "Application package " + pkg.packageName
10770                                    + " found at " + pkg.applicationInfo.getCodePath()
10771                                    + " but expected at " + known.codePathString
10772                                    + "; ignoring.");
10773                        }
10774                    } else {
10775                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10776                                "Application package " + pkg.packageName
10777                                + " not found; ignoring.");
10778                    }
10779                }
10780            }
10781
10782            // Verify that this new package doesn't have any content providers
10783            // that conflict with existing packages.  Only do this if the
10784            // package isn't already installed, since we don't want to break
10785            // things that are installed.
10786            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10787                final int N = pkg.providers.size();
10788                int i;
10789                for (i=0; i<N; i++) {
10790                    PackageParser.Provider p = pkg.providers.get(i);
10791                    if (p.info.authority != null) {
10792                        String names[] = p.info.authority.split(";");
10793                        for (int j = 0; j < names.length; j++) {
10794                            if (mProvidersByAuthority.containsKey(names[j])) {
10795                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10796                                final String otherPackageName =
10797                                        ((other != null && other.getComponentName() != null) ?
10798                                                other.getComponentName().getPackageName() : "?");
10799                                throw new PackageManagerException(
10800                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10801                                        "Can't install because provider name " + names[j]
10802                                                + " (in package " + pkg.applicationInfo.packageName
10803                                                + ") is already used by " + otherPackageName);
10804                            }
10805                        }
10806                    }
10807                }
10808            }
10809        }
10810    }
10811
10812    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10813            int type, String declaringPackageName, int declaringVersionCode) {
10814        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10815        if (versionedLib == null) {
10816            versionedLib = new SparseArray<>();
10817            mSharedLibraries.put(name, versionedLib);
10818            if (type == SharedLibraryInfo.TYPE_STATIC) {
10819                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10820            }
10821        } else if (versionedLib.indexOfKey(version) >= 0) {
10822            return false;
10823        }
10824        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10825                version, type, declaringPackageName, declaringVersionCode);
10826        versionedLib.put(version, libEntry);
10827        return true;
10828    }
10829
10830    private boolean removeSharedLibraryLPw(String name, int version) {
10831        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10832        if (versionedLib == null) {
10833            return false;
10834        }
10835        final int libIdx = versionedLib.indexOfKey(version);
10836        if (libIdx < 0) {
10837            return false;
10838        }
10839        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10840        versionedLib.remove(version);
10841        if (versionedLib.size() <= 0) {
10842            mSharedLibraries.remove(name);
10843            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10844                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10845                        .getPackageName());
10846            }
10847        }
10848        return true;
10849    }
10850
10851    /**
10852     * Adds a scanned package to the system. When this method is finished, the package will
10853     * be available for query, resolution, etc...
10854     */
10855    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10856            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10857        final String pkgName = pkg.packageName;
10858        if (mCustomResolverComponentName != null &&
10859                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10860            setUpCustomResolverActivity(pkg);
10861        }
10862
10863        if (pkg.packageName.equals("android")) {
10864            synchronized (mPackages) {
10865                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10866                    // Set up information for our fall-back user intent resolution activity.
10867                    mPlatformPackage = pkg;
10868                    pkg.mVersionCode = mSdkVersion;
10869                    mAndroidApplication = pkg.applicationInfo;
10870                    if (!mResolverReplaced) {
10871                        mResolveActivity.applicationInfo = mAndroidApplication;
10872                        mResolveActivity.name = ResolverActivity.class.getName();
10873                        mResolveActivity.packageName = mAndroidApplication.packageName;
10874                        mResolveActivity.processName = "system:ui";
10875                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10876                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10877                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10878                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10879                        mResolveActivity.exported = true;
10880                        mResolveActivity.enabled = true;
10881                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10882                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10883                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10884                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10885                                | ActivityInfo.CONFIG_ORIENTATION
10886                                | ActivityInfo.CONFIG_KEYBOARD
10887                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10888                        mResolveInfo.activityInfo = mResolveActivity;
10889                        mResolveInfo.priority = 0;
10890                        mResolveInfo.preferredOrder = 0;
10891                        mResolveInfo.match = 0;
10892                        mResolveComponentName = new ComponentName(
10893                                mAndroidApplication.packageName, mResolveActivity.name);
10894                    }
10895                }
10896            }
10897        }
10898
10899        ArrayList<PackageParser.Package> clientLibPkgs = null;
10900        // writer
10901        synchronized (mPackages) {
10902            boolean hasStaticSharedLibs = false;
10903
10904            // Any app can add new static shared libraries
10905            if (pkg.staticSharedLibName != null) {
10906                // Static shared libs don't allow renaming as they have synthetic package
10907                // names to allow install of multiple versions, so use name from manifest.
10908                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10909                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10910                        pkg.manifestPackageName, pkg.mVersionCode)) {
10911                    hasStaticSharedLibs = true;
10912                } else {
10913                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10914                                + pkg.staticSharedLibName + " already exists; skipping");
10915                }
10916                // Static shared libs cannot be updated once installed since they
10917                // use synthetic package name which includes the version code, so
10918                // not need to update other packages's shared lib dependencies.
10919            }
10920
10921            if (!hasStaticSharedLibs
10922                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10923                // Only system apps can add new dynamic shared libraries.
10924                if (pkg.libraryNames != null) {
10925                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10926                        String name = pkg.libraryNames.get(i);
10927                        boolean allowed = false;
10928                        if (pkg.isUpdatedSystemApp()) {
10929                            // New library entries can only be added through the
10930                            // system image.  This is important to get rid of a lot
10931                            // of nasty edge cases: for example if we allowed a non-
10932                            // system update of the app to add a library, then uninstalling
10933                            // the update would make the library go away, and assumptions
10934                            // we made such as through app install filtering would now
10935                            // have allowed apps on the device which aren't compatible
10936                            // with it.  Better to just have the restriction here, be
10937                            // conservative, and create many fewer cases that can negatively
10938                            // impact the user experience.
10939                            final PackageSetting sysPs = mSettings
10940                                    .getDisabledSystemPkgLPr(pkg.packageName);
10941                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10942                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10943                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10944                                        allowed = true;
10945                                        break;
10946                                    }
10947                                }
10948                            }
10949                        } else {
10950                            allowed = true;
10951                        }
10952                        if (allowed) {
10953                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10954                                    SharedLibraryInfo.VERSION_UNDEFINED,
10955                                    SharedLibraryInfo.TYPE_DYNAMIC,
10956                                    pkg.packageName, pkg.mVersionCode)) {
10957                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10958                                        + name + " already exists; skipping");
10959                            }
10960                        } else {
10961                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10962                                    + name + " that is not declared on system image; skipping");
10963                        }
10964                    }
10965
10966                    if ((scanFlags & SCAN_BOOTING) == 0) {
10967                        // If we are not booting, we need to update any applications
10968                        // that are clients of our shared library.  If we are booting,
10969                        // this will all be done once the scan is complete.
10970                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10971                    }
10972                }
10973            }
10974        }
10975
10976        if ((scanFlags & SCAN_BOOTING) != 0) {
10977            // No apps can run during boot scan, so they don't need to be frozen
10978        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10979            // Caller asked to not kill app, so it's probably not frozen
10980        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10981            // Caller asked us to ignore frozen check for some reason; they
10982            // probably didn't know the package name
10983        } else {
10984            // We're doing major surgery on this package, so it better be frozen
10985            // right now to keep it from launching
10986            checkPackageFrozen(pkgName);
10987        }
10988
10989        // Also need to kill any apps that are dependent on the library.
10990        if (clientLibPkgs != null) {
10991            for (int i=0; i<clientLibPkgs.size(); i++) {
10992                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10993                killApplication(clientPkg.applicationInfo.packageName,
10994                        clientPkg.applicationInfo.uid, "update lib");
10995            }
10996        }
10997
10998        // writer
10999        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11000
11001        synchronized (mPackages) {
11002            // We don't expect installation to fail beyond this point
11003
11004            // Add the new setting to mSettings
11005            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11006            // Add the new setting to mPackages
11007            mPackages.put(pkg.applicationInfo.packageName, pkg);
11008            // Make sure we don't accidentally delete its data.
11009            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11010            while (iter.hasNext()) {
11011                PackageCleanItem item = iter.next();
11012                if (pkgName.equals(item.packageName)) {
11013                    iter.remove();
11014                }
11015            }
11016
11017            // Add the package's KeySets to the global KeySetManagerService
11018            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11019            ksms.addScannedPackageLPw(pkg);
11020
11021            int N = pkg.providers.size();
11022            StringBuilder r = null;
11023            int i;
11024            for (i=0; i<N; i++) {
11025                PackageParser.Provider p = pkg.providers.get(i);
11026                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11027                        p.info.processName);
11028                mProviders.addProvider(p);
11029                p.syncable = p.info.isSyncable;
11030                if (p.info.authority != null) {
11031                    String names[] = p.info.authority.split(";");
11032                    p.info.authority = null;
11033                    for (int j = 0; j < names.length; j++) {
11034                        if (j == 1 && p.syncable) {
11035                            // We only want the first authority for a provider to possibly be
11036                            // syncable, so if we already added this provider using a different
11037                            // authority clear the syncable flag. We copy the provider before
11038                            // changing it because the mProviders object contains a reference
11039                            // to a provider that we don't want to change.
11040                            // Only do this for the second authority since the resulting provider
11041                            // object can be the same for all future authorities for this provider.
11042                            p = new PackageParser.Provider(p);
11043                            p.syncable = false;
11044                        }
11045                        if (!mProvidersByAuthority.containsKey(names[j])) {
11046                            mProvidersByAuthority.put(names[j], p);
11047                            if (p.info.authority == null) {
11048                                p.info.authority = names[j];
11049                            } else {
11050                                p.info.authority = p.info.authority + ";" + names[j];
11051                            }
11052                            if (DEBUG_PACKAGE_SCANNING) {
11053                                if (chatty)
11054                                    Log.d(TAG, "Registered content provider: " + names[j]
11055                                            + ", className = " + p.info.name + ", isSyncable = "
11056                                            + p.info.isSyncable);
11057                            }
11058                        } else {
11059                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11060                            Slog.w(TAG, "Skipping provider name " + names[j] +
11061                                    " (in package " + pkg.applicationInfo.packageName +
11062                                    "): name already used by "
11063                                    + ((other != null && other.getComponentName() != null)
11064                                            ? other.getComponentName().getPackageName() : "?"));
11065                        }
11066                    }
11067                }
11068                if (chatty) {
11069                    if (r == null) {
11070                        r = new StringBuilder(256);
11071                    } else {
11072                        r.append(' ');
11073                    }
11074                    r.append(p.info.name);
11075                }
11076            }
11077            if (r != null) {
11078                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11079            }
11080
11081            N = pkg.services.size();
11082            r = null;
11083            for (i=0; i<N; i++) {
11084                PackageParser.Service s = pkg.services.get(i);
11085                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11086                        s.info.processName);
11087                mServices.addService(s);
11088                if (chatty) {
11089                    if (r == null) {
11090                        r = new StringBuilder(256);
11091                    } else {
11092                        r.append(' ');
11093                    }
11094                    r.append(s.info.name);
11095                }
11096            }
11097            if (r != null) {
11098                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11099            }
11100
11101            N = pkg.receivers.size();
11102            r = null;
11103            for (i=0; i<N; i++) {
11104                PackageParser.Activity a = pkg.receivers.get(i);
11105                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11106                        a.info.processName);
11107                mReceivers.addActivity(a, "receiver");
11108                if (chatty) {
11109                    if (r == null) {
11110                        r = new StringBuilder(256);
11111                    } else {
11112                        r.append(' ');
11113                    }
11114                    r.append(a.info.name);
11115                }
11116            }
11117            if (r != null) {
11118                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11119            }
11120
11121            N = pkg.activities.size();
11122            r = null;
11123            for (i=0; i<N; i++) {
11124                PackageParser.Activity a = pkg.activities.get(i);
11125                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11126                        a.info.processName);
11127                mActivities.addActivity(a, "activity");
11128                if (chatty) {
11129                    if (r == null) {
11130                        r = new StringBuilder(256);
11131                    } else {
11132                        r.append(' ');
11133                    }
11134                    r.append(a.info.name);
11135                }
11136            }
11137            if (r != null) {
11138                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11139            }
11140
11141            N = pkg.permissionGroups.size();
11142            r = null;
11143            for (i=0; i<N; i++) {
11144                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11145                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11146                final String curPackageName = cur == null ? null : cur.info.packageName;
11147                // Dont allow ephemeral apps to define new permission groups.
11148                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11149                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11150                            + pg.info.packageName
11151                            + " ignored: instant apps cannot define new permission groups.");
11152                    continue;
11153                }
11154                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11155                if (cur == null || isPackageUpdate) {
11156                    mPermissionGroups.put(pg.info.name, pg);
11157                    if (chatty) {
11158                        if (r == null) {
11159                            r = new StringBuilder(256);
11160                        } else {
11161                            r.append(' ');
11162                        }
11163                        if (isPackageUpdate) {
11164                            r.append("UPD:");
11165                        }
11166                        r.append(pg.info.name);
11167                    }
11168                } else {
11169                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11170                            + pg.info.packageName + " ignored: original from "
11171                            + cur.info.packageName);
11172                    if (chatty) {
11173                        if (r == null) {
11174                            r = new StringBuilder(256);
11175                        } else {
11176                            r.append(' ');
11177                        }
11178                        r.append("DUP:");
11179                        r.append(pg.info.name);
11180                    }
11181                }
11182            }
11183            if (r != null) {
11184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11185            }
11186
11187
11188            // Dont allow ephemeral apps to define new permissions.
11189            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11190                Slog.w(TAG, "Permissions from package " + pkg.packageName
11191                        + " ignored: instant apps cannot define new permissions.");
11192            } else {
11193                mPermissionManager.addAllPermissions(pkg, chatty);
11194            }
11195
11196            N = pkg.instrumentation.size();
11197            r = null;
11198            for (i=0; i<N; i++) {
11199                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11200                a.info.packageName = pkg.applicationInfo.packageName;
11201                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11202                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11203                a.info.splitNames = pkg.splitNames;
11204                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11205                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11206                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11207                a.info.dataDir = pkg.applicationInfo.dataDir;
11208                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11209                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11210                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11211                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11212                mInstrumentation.put(a.getComponentName(), a);
11213                if (chatty) {
11214                    if (r == null) {
11215                        r = new StringBuilder(256);
11216                    } else {
11217                        r.append(' ');
11218                    }
11219                    r.append(a.info.name);
11220                }
11221            }
11222            if (r != null) {
11223                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11224            }
11225
11226            if (pkg.protectedBroadcasts != null) {
11227                N = pkg.protectedBroadcasts.size();
11228                synchronized (mProtectedBroadcasts) {
11229                    for (i = 0; i < N; i++) {
11230                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11231                    }
11232                }
11233            }
11234        }
11235
11236        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11237    }
11238
11239    /**
11240     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11241     * is derived purely on the basis of the contents of {@code scanFile} and
11242     * {@code cpuAbiOverride}.
11243     *
11244     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11245     */
11246    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11247                                 String cpuAbiOverride, boolean extractLibs,
11248                                 File appLib32InstallDir)
11249            throws PackageManagerException {
11250        // Give ourselves some initial paths; we'll come back for another
11251        // pass once we've determined ABI below.
11252        setNativeLibraryPaths(pkg, appLib32InstallDir);
11253
11254        // We would never need to extract libs for forward-locked and external packages,
11255        // since the container service will do it for us. We shouldn't attempt to
11256        // extract libs from system app when it was not updated.
11257        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11258                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11259            extractLibs = false;
11260        }
11261
11262        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11263        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11264
11265        NativeLibraryHelper.Handle handle = null;
11266        try {
11267            handle = NativeLibraryHelper.Handle.create(pkg);
11268            // TODO(multiArch): This can be null for apps that didn't go through the
11269            // usual installation process. We can calculate it again, like we
11270            // do during install time.
11271            //
11272            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11273            // unnecessary.
11274            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11275
11276            // Null out the abis so that they can be recalculated.
11277            pkg.applicationInfo.primaryCpuAbi = null;
11278            pkg.applicationInfo.secondaryCpuAbi = null;
11279            if (isMultiArch(pkg.applicationInfo)) {
11280                // Warn if we've set an abiOverride for multi-lib packages..
11281                // By definition, we need to copy both 32 and 64 bit libraries for
11282                // such packages.
11283                if (pkg.cpuAbiOverride != null
11284                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11285                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11286                }
11287
11288                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11289                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11290                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11291                    if (extractLibs) {
11292                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11293                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11294                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11295                                useIsaSpecificSubdirs);
11296                    } else {
11297                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11298                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11299                    }
11300                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11301                }
11302
11303                // Shared library native code should be in the APK zip aligned
11304                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11305                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11306                            "Shared library native lib extraction not supported");
11307                }
11308
11309                maybeThrowExceptionForMultiArchCopy(
11310                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11311
11312                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11313                    if (extractLibs) {
11314                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11315                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11316                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11317                                useIsaSpecificSubdirs);
11318                    } else {
11319                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11320                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11321                    }
11322                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11323                }
11324
11325                maybeThrowExceptionForMultiArchCopy(
11326                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11327
11328                if (abi64 >= 0) {
11329                    // Shared library native libs should be in the APK zip aligned
11330                    if (extractLibs && pkg.isLibrary()) {
11331                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11332                                "Shared library native lib extraction not supported");
11333                    }
11334                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11335                }
11336
11337                if (abi32 >= 0) {
11338                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11339                    if (abi64 >= 0) {
11340                        if (pkg.use32bitAbi) {
11341                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11342                            pkg.applicationInfo.primaryCpuAbi = abi;
11343                        } else {
11344                            pkg.applicationInfo.secondaryCpuAbi = abi;
11345                        }
11346                    } else {
11347                        pkg.applicationInfo.primaryCpuAbi = abi;
11348                    }
11349                }
11350            } else {
11351                String[] abiList = (cpuAbiOverride != null) ?
11352                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11353
11354                // Enable gross and lame hacks for apps that are built with old
11355                // SDK tools. We must scan their APKs for renderscript bitcode and
11356                // not launch them if it's present. Don't bother checking on devices
11357                // that don't have 64 bit support.
11358                boolean needsRenderScriptOverride = false;
11359                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11360                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11361                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11362                    needsRenderScriptOverride = true;
11363                }
11364
11365                final int copyRet;
11366                if (extractLibs) {
11367                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11368                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11369                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11370                } else {
11371                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11372                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11373                }
11374                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11375
11376                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11377                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11378                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11379                }
11380
11381                if (copyRet >= 0) {
11382                    // Shared libraries that have native libs must be multi-architecture
11383                    if (pkg.isLibrary()) {
11384                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11385                                "Shared library with native libs must be multiarch");
11386                    }
11387                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11388                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11389                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11390                } else if (needsRenderScriptOverride) {
11391                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11392                }
11393            }
11394        } catch (IOException ioe) {
11395            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11396        } finally {
11397            IoUtils.closeQuietly(handle);
11398        }
11399
11400        // Now that we've calculated the ABIs and determined if it's an internal app,
11401        // we will go ahead and populate the nativeLibraryPath.
11402        setNativeLibraryPaths(pkg, appLib32InstallDir);
11403    }
11404
11405    /**
11406     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11407     * i.e, so that all packages can be run inside a single process if required.
11408     *
11409     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11410     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11411     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11412     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11413     * updating a package that belongs to a shared user.
11414     *
11415     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11416     * adds unnecessary complexity.
11417     */
11418    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11419            PackageParser.Package scannedPackage) {
11420        String requiredInstructionSet = null;
11421        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11422            requiredInstructionSet = VMRuntime.getInstructionSet(
11423                     scannedPackage.applicationInfo.primaryCpuAbi);
11424        }
11425
11426        PackageSetting requirer = null;
11427        for (PackageSetting ps : packagesForUser) {
11428            // If packagesForUser contains scannedPackage, we skip it. This will happen
11429            // when scannedPackage is an update of an existing package. Without this check,
11430            // we will never be able to change the ABI of any package belonging to a shared
11431            // user, even if it's compatible with other packages.
11432            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11433                if (ps.primaryCpuAbiString == null) {
11434                    continue;
11435                }
11436
11437                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11438                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11439                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11440                    // this but there's not much we can do.
11441                    String errorMessage = "Instruction set mismatch, "
11442                            + ((requirer == null) ? "[caller]" : requirer)
11443                            + " requires " + requiredInstructionSet + " whereas " + ps
11444                            + " requires " + instructionSet;
11445                    Slog.w(TAG, errorMessage);
11446                }
11447
11448                if (requiredInstructionSet == null) {
11449                    requiredInstructionSet = instructionSet;
11450                    requirer = ps;
11451                }
11452            }
11453        }
11454
11455        if (requiredInstructionSet != null) {
11456            String adjustedAbi;
11457            if (requirer != null) {
11458                // requirer != null implies that either scannedPackage was null or that scannedPackage
11459                // did not require an ABI, in which case we have to adjust scannedPackage to match
11460                // the ABI of the set (which is the same as requirer's ABI)
11461                adjustedAbi = requirer.primaryCpuAbiString;
11462                if (scannedPackage != null) {
11463                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11464                }
11465            } else {
11466                // requirer == null implies that we're updating all ABIs in the set to
11467                // match scannedPackage.
11468                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11469            }
11470
11471            for (PackageSetting ps : packagesForUser) {
11472                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11473                    if (ps.primaryCpuAbiString != null) {
11474                        continue;
11475                    }
11476
11477                    ps.primaryCpuAbiString = adjustedAbi;
11478                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11479                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11480                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11481                        if (DEBUG_ABI_SELECTION) {
11482                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11483                                    + " (requirer="
11484                                    + (requirer != null ? requirer.pkg : "null")
11485                                    + ", scannedPackage="
11486                                    + (scannedPackage != null ? scannedPackage : "null")
11487                                    + ")");
11488                        }
11489                        try {
11490                            mInstaller.rmdex(ps.codePathString,
11491                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11492                        } catch (InstallerException ignored) {
11493                        }
11494                    }
11495                }
11496            }
11497        }
11498    }
11499
11500    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11501        synchronized (mPackages) {
11502            mResolverReplaced = true;
11503            // Set up information for custom user intent resolution activity.
11504            mResolveActivity.applicationInfo = pkg.applicationInfo;
11505            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11506            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11507            mResolveActivity.processName = pkg.applicationInfo.packageName;
11508            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11509            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11510                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11511            mResolveActivity.theme = 0;
11512            mResolveActivity.exported = true;
11513            mResolveActivity.enabled = true;
11514            mResolveInfo.activityInfo = mResolveActivity;
11515            mResolveInfo.priority = 0;
11516            mResolveInfo.preferredOrder = 0;
11517            mResolveInfo.match = 0;
11518            mResolveComponentName = mCustomResolverComponentName;
11519            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11520                    mResolveComponentName);
11521        }
11522    }
11523
11524    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11525        if (installerActivity == null) {
11526            if (DEBUG_EPHEMERAL) {
11527                Slog.d(TAG, "Clear ephemeral installer activity");
11528            }
11529            mInstantAppInstallerActivity = null;
11530            return;
11531        }
11532
11533        if (DEBUG_EPHEMERAL) {
11534            Slog.d(TAG, "Set ephemeral installer activity: "
11535                    + installerActivity.getComponentName());
11536        }
11537        // Set up information for ephemeral installer activity
11538        mInstantAppInstallerActivity = installerActivity;
11539        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11540                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11541        mInstantAppInstallerActivity.exported = true;
11542        mInstantAppInstallerActivity.enabled = true;
11543        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11544        mInstantAppInstallerInfo.priority = 0;
11545        mInstantAppInstallerInfo.preferredOrder = 1;
11546        mInstantAppInstallerInfo.isDefault = true;
11547        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11548                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11549    }
11550
11551    private static String calculateBundledApkRoot(final String codePathString) {
11552        final File codePath = new File(codePathString);
11553        final File codeRoot;
11554        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11555            codeRoot = Environment.getRootDirectory();
11556        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11557            codeRoot = Environment.getOemDirectory();
11558        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11559            codeRoot = Environment.getVendorDirectory();
11560        } else {
11561            // Unrecognized code path; take its top real segment as the apk root:
11562            // e.g. /something/app/blah.apk => /something
11563            try {
11564                File f = codePath.getCanonicalFile();
11565                File parent = f.getParentFile();    // non-null because codePath is a file
11566                File tmp;
11567                while ((tmp = parent.getParentFile()) != null) {
11568                    f = parent;
11569                    parent = tmp;
11570                }
11571                codeRoot = f;
11572                Slog.w(TAG, "Unrecognized code path "
11573                        + codePath + " - using " + codeRoot);
11574            } catch (IOException e) {
11575                // Can't canonicalize the code path -- shenanigans?
11576                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11577                return Environment.getRootDirectory().getPath();
11578            }
11579        }
11580        return codeRoot.getPath();
11581    }
11582
11583    /**
11584     * Derive and set the location of native libraries for the given package,
11585     * which varies depending on where and how the package was installed.
11586     */
11587    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11588        final ApplicationInfo info = pkg.applicationInfo;
11589        final String codePath = pkg.codePath;
11590        final File codeFile = new File(codePath);
11591        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11592        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11593
11594        info.nativeLibraryRootDir = null;
11595        info.nativeLibraryRootRequiresIsa = false;
11596        info.nativeLibraryDir = null;
11597        info.secondaryNativeLibraryDir = null;
11598
11599        if (isApkFile(codeFile)) {
11600            // Monolithic install
11601            if (bundledApp) {
11602                // If "/system/lib64/apkname" exists, assume that is the per-package
11603                // native library directory to use; otherwise use "/system/lib/apkname".
11604                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11605                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11606                        getPrimaryInstructionSet(info));
11607
11608                // This is a bundled system app so choose the path based on the ABI.
11609                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11610                // is just the default path.
11611                final String apkName = deriveCodePathName(codePath);
11612                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11613                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11614                        apkName).getAbsolutePath();
11615
11616                if (info.secondaryCpuAbi != null) {
11617                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11618                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11619                            secondaryLibDir, apkName).getAbsolutePath();
11620                }
11621            } else if (asecApp) {
11622                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11623                        .getAbsolutePath();
11624            } else {
11625                final String apkName = deriveCodePathName(codePath);
11626                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11627                        .getAbsolutePath();
11628            }
11629
11630            info.nativeLibraryRootRequiresIsa = false;
11631            info.nativeLibraryDir = info.nativeLibraryRootDir;
11632        } else {
11633            // Cluster install
11634            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11635            info.nativeLibraryRootRequiresIsa = true;
11636
11637            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11638                    getPrimaryInstructionSet(info)).getAbsolutePath();
11639
11640            if (info.secondaryCpuAbi != null) {
11641                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11642                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11643            }
11644        }
11645    }
11646
11647    /**
11648     * Calculate the abis and roots for a bundled app. These can uniquely
11649     * be determined from the contents of the system partition, i.e whether
11650     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11651     * of this information, and instead assume that the system was built
11652     * sensibly.
11653     */
11654    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11655                                           PackageSetting pkgSetting) {
11656        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11657
11658        // If "/system/lib64/apkname" exists, assume that is the per-package
11659        // native library directory to use; otherwise use "/system/lib/apkname".
11660        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11661        setBundledAppAbi(pkg, apkRoot, apkName);
11662        // pkgSetting might be null during rescan following uninstall of updates
11663        // to a bundled app, so accommodate that possibility.  The settings in
11664        // that case will be established later from the parsed package.
11665        //
11666        // If the settings aren't null, sync them up with what we've just derived.
11667        // note that apkRoot isn't stored in the package settings.
11668        if (pkgSetting != null) {
11669            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11670            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11671        }
11672    }
11673
11674    /**
11675     * Deduces the ABI of a bundled app and sets the relevant fields on the
11676     * parsed pkg object.
11677     *
11678     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11679     *        under which system libraries are installed.
11680     * @param apkName the name of the installed package.
11681     */
11682    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11683        final File codeFile = new File(pkg.codePath);
11684
11685        final boolean has64BitLibs;
11686        final boolean has32BitLibs;
11687        if (isApkFile(codeFile)) {
11688            // Monolithic install
11689            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11690            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11691        } else {
11692            // Cluster install
11693            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11694            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11695                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11696                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11697                has64BitLibs = (new File(rootDir, isa)).exists();
11698            } else {
11699                has64BitLibs = false;
11700            }
11701            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11702                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11703                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11704                has32BitLibs = (new File(rootDir, isa)).exists();
11705            } else {
11706                has32BitLibs = false;
11707            }
11708        }
11709
11710        if (has64BitLibs && !has32BitLibs) {
11711            // The package has 64 bit libs, but not 32 bit libs. Its primary
11712            // ABI should be 64 bit. We can safely assume here that the bundled
11713            // native libraries correspond to the most preferred ABI in the list.
11714
11715            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11716            pkg.applicationInfo.secondaryCpuAbi = null;
11717        } else if (has32BitLibs && !has64BitLibs) {
11718            // The package has 32 bit libs but not 64 bit libs. Its primary
11719            // ABI should be 32 bit.
11720
11721            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11722            pkg.applicationInfo.secondaryCpuAbi = null;
11723        } else if (has32BitLibs && has64BitLibs) {
11724            // The application has both 64 and 32 bit bundled libraries. We check
11725            // here that the app declares multiArch support, and warn if it doesn't.
11726            //
11727            // We will be lenient here and record both ABIs. The primary will be the
11728            // ABI that's higher on the list, i.e, a device that's configured to prefer
11729            // 64 bit apps will see a 64 bit primary ABI,
11730
11731            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11732                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11733            }
11734
11735            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11736                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11737                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11738            } else {
11739                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11740                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11741            }
11742        } else {
11743            pkg.applicationInfo.primaryCpuAbi = null;
11744            pkg.applicationInfo.secondaryCpuAbi = null;
11745        }
11746    }
11747
11748    private void killApplication(String pkgName, int appId, String reason) {
11749        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11750    }
11751
11752    private void killApplication(String pkgName, int appId, int userId, String reason) {
11753        // Request the ActivityManager to kill the process(only for existing packages)
11754        // so that we do not end up in a confused state while the user is still using the older
11755        // version of the application while the new one gets installed.
11756        final long token = Binder.clearCallingIdentity();
11757        try {
11758            IActivityManager am = ActivityManager.getService();
11759            if (am != null) {
11760                try {
11761                    am.killApplication(pkgName, appId, userId, reason);
11762                } catch (RemoteException e) {
11763                }
11764            }
11765        } finally {
11766            Binder.restoreCallingIdentity(token);
11767        }
11768    }
11769
11770    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11771        // Remove the parent package setting
11772        PackageSetting ps = (PackageSetting) pkg.mExtras;
11773        if (ps != null) {
11774            removePackageLI(ps, chatty);
11775        }
11776        // Remove the child package setting
11777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11778        for (int i = 0; i < childCount; i++) {
11779            PackageParser.Package childPkg = pkg.childPackages.get(i);
11780            ps = (PackageSetting) childPkg.mExtras;
11781            if (ps != null) {
11782                removePackageLI(ps, chatty);
11783            }
11784        }
11785    }
11786
11787    void removePackageLI(PackageSetting ps, boolean chatty) {
11788        if (DEBUG_INSTALL) {
11789            if (chatty)
11790                Log.d(TAG, "Removing package " + ps.name);
11791        }
11792
11793        // writer
11794        synchronized (mPackages) {
11795            mPackages.remove(ps.name);
11796            final PackageParser.Package pkg = ps.pkg;
11797            if (pkg != null) {
11798                cleanPackageDataStructuresLILPw(pkg, chatty);
11799            }
11800        }
11801    }
11802
11803    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11804        if (DEBUG_INSTALL) {
11805            if (chatty)
11806                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11807        }
11808
11809        // writer
11810        synchronized (mPackages) {
11811            // Remove the parent package
11812            mPackages.remove(pkg.applicationInfo.packageName);
11813            cleanPackageDataStructuresLILPw(pkg, chatty);
11814
11815            // Remove the child packages
11816            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11817            for (int i = 0; i < childCount; i++) {
11818                PackageParser.Package childPkg = pkg.childPackages.get(i);
11819                mPackages.remove(childPkg.applicationInfo.packageName);
11820                cleanPackageDataStructuresLILPw(childPkg, chatty);
11821            }
11822        }
11823    }
11824
11825    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11826        int N = pkg.providers.size();
11827        StringBuilder r = null;
11828        int i;
11829        for (i=0; i<N; i++) {
11830            PackageParser.Provider p = pkg.providers.get(i);
11831            mProviders.removeProvider(p);
11832            if (p.info.authority == null) {
11833
11834                /* There was another ContentProvider with this authority when
11835                 * this app was installed so this authority is null,
11836                 * Ignore it as we don't have to unregister the provider.
11837                 */
11838                continue;
11839            }
11840            String names[] = p.info.authority.split(";");
11841            for (int j = 0; j < names.length; j++) {
11842                if (mProvidersByAuthority.get(names[j]) == p) {
11843                    mProvidersByAuthority.remove(names[j]);
11844                    if (DEBUG_REMOVE) {
11845                        if (chatty)
11846                            Log.d(TAG, "Unregistered content provider: " + names[j]
11847                                    + ", className = " + p.info.name + ", isSyncable = "
11848                                    + p.info.isSyncable);
11849                    }
11850                }
11851            }
11852            if (DEBUG_REMOVE && chatty) {
11853                if (r == null) {
11854                    r = new StringBuilder(256);
11855                } else {
11856                    r.append(' ');
11857                }
11858                r.append(p.info.name);
11859            }
11860        }
11861        if (r != null) {
11862            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11863        }
11864
11865        N = pkg.services.size();
11866        r = null;
11867        for (i=0; i<N; i++) {
11868            PackageParser.Service s = pkg.services.get(i);
11869            mServices.removeService(s);
11870            if (chatty) {
11871                if (r == null) {
11872                    r = new StringBuilder(256);
11873                } else {
11874                    r.append(' ');
11875                }
11876                r.append(s.info.name);
11877            }
11878        }
11879        if (r != null) {
11880            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11881        }
11882
11883        N = pkg.receivers.size();
11884        r = null;
11885        for (i=0; i<N; i++) {
11886            PackageParser.Activity a = pkg.receivers.get(i);
11887            mReceivers.removeActivity(a, "receiver");
11888            if (DEBUG_REMOVE && chatty) {
11889                if (r == null) {
11890                    r = new StringBuilder(256);
11891                } else {
11892                    r.append(' ');
11893                }
11894                r.append(a.info.name);
11895            }
11896        }
11897        if (r != null) {
11898            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11899        }
11900
11901        N = pkg.activities.size();
11902        r = null;
11903        for (i=0; i<N; i++) {
11904            PackageParser.Activity a = pkg.activities.get(i);
11905            mActivities.removeActivity(a, "activity");
11906            if (DEBUG_REMOVE && chatty) {
11907                if (r == null) {
11908                    r = new StringBuilder(256);
11909                } else {
11910                    r.append(' ');
11911                }
11912                r.append(a.info.name);
11913            }
11914        }
11915        if (r != null) {
11916            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11917        }
11918
11919        mPermissionManager.removeAllPermissions(pkg, chatty);
11920
11921        N = pkg.instrumentation.size();
11922        r = null;
11923        for (i=0; i<N; i++) {
11924            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11925            mInstrumentation.remove(a.getComponentName());
11926            if (DEBUG_REMOVE && chatty) {
11927                if (r == null) {
11928                    r = new StringBuilder(256);
11929                } else {
11930                    r.append(' ');
11931                }
11932                r.append(a.info.name);
11933            }
11934        }
11935        if (r != null) {
11936            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11937        }
11938
11939        r = null;
11940        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11941            // Only system apps can hold shared libraries.
11942            if (pkg.libraryNames != null) {
11943                for (i = 0; i < pkg.libraryNames.size(); i++) {
11944                    String name = pkg.libraryNames.get(i);
11945                    if (removeSharedLibraryLPw(name, 0)) {
11946                        if (DEBUG_REMOVE && chatty) {
11947                            if (r == null) {
11948                                r = new StringBuilder(256);
11949                            } else {
11950                                r.append(' ');
11951                            }
11952                            r.append(name);
11953                        }
11954                    }
11955                }
11956            }
11957        }
11958
11959        r = null;
11960
11961        // Any package can hold static shared libraries.
11962        if (pkg.staticSharedLibName != null) {
11963            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11964                if (DEBUG_REMOVE && chatty) {
11965                    if (r == null) {
11966                        r = new StringBuilder(256);
11967                    } else {
11968                        r.append(' ');
11969                    }
11970                    r.append(pkg.staticSharedLibName);
11971                }
11972            }
11973        }
11974
11975        if (r != null) {
11976            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11977        }
11978    }
11979
11980    public static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11981    public static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11982    public static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11983
11984    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11985        // Update the parent permissions
11986        updatePermissionsLPw(pkg.packageName, pkg, flags);
11987        // Update the child permissions
11988        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11989        for (int i = 0; i < childCount; i++) {
11990            PackageParser.Package childPkg = pkg.childPackages.get(i);
11991            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11992        }
11993    }
11994
11995    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11996            int flags) {
11997        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11998        updatePermissionsLocked(changingPkg, pkgInfo, volumeUuid, flags);
11999    }
12000
12001    private void updatePermissionsLocked(String changingPkg,
12002            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12003        // TODO: Most of the methods exposing BasePermission internals [source package name,
12004        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12005        // have package settings, we should make note of it elsewhere [map between
12006        // source package name and BasePermission] and cycle through that here. Then we
12007        // define a single method on BasePermission that takes a PackageSetting, changing
12008        // package name and a package.
12009        // NOTE: With this approach, we also don't need to tree trees differently than
12010        // normal permissions. Today, we need two separate loops because these BasePermission
12011        // objects are stored separately.
12012        // Make sure there are no dangling permission trees.
12013        flags = mPermissionManager.updatePermissionTrees(changingPkg, pkgInfo, flags);
12014
12015        // Make sure all dynamic permissions have been assigned to a package,
12016        // and make sure there are no dangling permissions.
12017        flags = mPermissionManager.updatePermissions(changingPkg, pkgInfo, flags);
12018
12019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12020        // Now update the permissions for all packages, in particular
12021        // replace the granted permissions of the system packages.
12022        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12023            for (PackageParser.Package pkg : mPackages.values()) {
12024                if (pkg != pkgInfo) {
12025                    // Only replace for packages on requested volume
12026                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12027                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12028                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12029                    grantPermissionsLPw(pkg, replace, changingPkg);
12030                }
12031            }
12032        }
12033
12034        if (pkgInfo != null) {
12035            // Only replace for packages on requested volume
12036            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12037            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12038                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12039            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12040        }
12041        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12042    }
12043
12044    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12045            String packageOfInterest) {
12046        // IMPORTANT: There are two types of permissions: install and runtime.
12047        // Install time permissions are granted when the app is installed to
12048        // all device users and users added in the future. Runtime permissions
12049        // are granted at runtime explicitly to specific users. Normal and signature
12050        // protected permissions are install time permissions. Dangerous permissions
12051        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12052        // otherwise they are runtime permissions. This function does not manage
12053        // runtime permissions except for the case an app targeting Lollipop MR1
12054        // being upgraded to target a newer SDK, in which case dangerous permissions
12055        // are transformed from install time to runtime ones.
12056
12057        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12058        if (ps == null) {
12059            return;
12060        }
12061
12062        PermissionsState permissionsState = ps.getPermissionsState();
12063        PermissionsState origPermissions = permissionsState;
12064
12065        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12066
12067        boolean runtimePermissionsRevoked = false;
12068        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12069
12070        boolean changedInstallPermission = false;
12071
12072        if (replace) {
12073            ps.installPermissionsFixed = false;
12074            if (!ps.isSharedUser()) {
12075                origPermissions = new PermissionsState(permissionsState);
12076                permissionsState.reset();
12077            } else {
12078                // We need to know only about runtime permission changes since the
12079                // calling code always writes the install permissions state but
12080                // the runtime ones are written only if changed. The only cases of
12081                // changed runtime permissions here are promotion of an install to
12082                // runtime and revocation of a runtime from a shared user.
12083                changedRuntimePermissionUserIds =
12084                        mPermissionManager.revokeUnusedSharedUserPermissions(
12085                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12086                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12087                    runtimePermissionsRevoked = true;
12088                }
12089            }
12090        }
12091
12092        permissionsState.setGlobalGids(mGlobalGids);
12093
12094        final int N = pkg.requestedPermissions.size();
12095        for (int i=0; i<N; i++) {
12096            final String name = pkg.requestedPermissions.get(i);
12097            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12098            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12099                    >= Build.VERSION_CODES.M;
12100
12101            if (DEBUG_INSTALL) {
12102                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12103            }
12104
12105            if (bp == null || bp.getSourcePackageSetting() == null) {
12106                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12107                    if (DEBUG_PERMISSIONS) {
12108                        Slog.i(TAG, "Unknown permission " + name
12109                                + " in package " + pkg.packageName);
12110                    }
12111                }
12112                continue;
12113            }
12114
12115
12116            // Limit ephemeral apps to ephemeral allowed permissions.
12117            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12118                if (DEBUG_PERMISSIONS) {
12119                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12120                            + pkg.packageName);
12121                }
12122                continue;
12123            }
12124
12125            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12126                if (DEBUG_PERMISSIONS) {
12127                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12128                            + pkg.packageName);
12129                }
12130                continue;
12131            }
12132
12133            final String perm = bp.getName();
12134            boolean allowedSig = false;
12135            int grant = GRANT_DENIED;
12136
12137            // Keep track of app op permissions.
12138            if (bp.isAppOp()) {
12139                mSettings.addAppOpPackage(perm, pkg.packageName);
12140            }
12141
12142            if (bp.isNormal()) {
12143                // For all apps normal permissions are install time ones.
12144                grant = GRANT_INSTALL;
12145            } else if (bp.isRuntime()) {
12146                // If a permission review is required for legacy apps we represent
12147                // their permissions as always granted runtime ones since we need
12148                // to keep the review required permission flag per user while an
12149                // install permission's state is shared across all users.
12150                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12151                    // For legacy apps dangerous permissions are install time ones.
12152                    grant = GRANT_INSTALL;
12153                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12154                    // For legacy apps that became modern, install becomes runtime.
12155                    grant = GRANT_UPGRADE;
12156                } else if (mPromoteSystemApps
12157                        && isSystemApp(ps)
12158                        && mExistingSystemPackages.contains(ps.name)) {
12159                    // For legacy system apps, install becomes runtime.
12160                    // We cannot check hasInstallPermission() for system apps since those
12161                    // permissions were granted implicitly and not persisted pre-M.
12162                    grant = GRANT_UPGRADE;
12163                } else {
12164                    // For modern apps keep runtime permissions unchanged.
12165                    grant = GRANT_RUNTIME;
12166                }
12167            } else if (bp.isSignature()) {
12168                // For all apps signature permissions are install time ones.
12169                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12170                if (allowedSig) {
12171                    grant = GRANT_INSTALL;
12172                }
12173            }
12174
12175            if (DEBUG_PERMISSIONS) {
12176                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12177            }
12178
12179            if (grant != GRANT_DENIED) {
12180                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12181                    // If this is an existing, non-system package, then
12182                    // we can't add any new permissions to it.
12183                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12184                        // Except...  if this is a permission that was added
12185                        // to the platform (note: need to only do this when
12186                        // updating the platform).
12187                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12188                            grant = GRANT_DENIED;
12189                        }
12190                    }
12191                }
12192
12193                switch (grant) {
12194                    case GRANT_INSTALL: {
12195                        // Revoke this as runtime permission to handle the case of
12196                        // a runtime permission being downgraded to an install one.
12197                        // Also in permission review mode we keep dangerous permissions
12198                        // for legacy apps
12199                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12200                            if (origPermissions.getRuntimePermissionState(
12201                                    perm, userId) != null) {
12202                                // Revoke the runtime permission and clear the flags.
12203                                origPermissions.revokeRuntimePermission(bp, userId);
12204                                origPermissions.updatePermissionFlags(bp, userId,
12205                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12206                                // If we revoked a permission permission, we have to write.
12207                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12208                                        changedRuntimePermissionUserIds, userId);
12209                            }
12210                        }
12211                        // Grant an install permission.
12212                        if (permissionsState.grantInstallPermission(bp) !=
12213                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12214                            changedInstallPermission = true;
12215                        }
12216                    } break;
12217
12218                    case GRANT_RUNTIME: {
12219                        // Grant previously granted runtime permissions.
12220                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12221                            PermissionState permissionState = origPermissions
12222                                    .getRuntimePermissionState(perm, userId);
12223                            int flags = permissionState != null
12224                                    ? permissionState.getFlags() : 0;
12225                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12226                                // Don't propagate the permission in a permission review mode if
12227                                // the former was revoked, i.e. marked to not propagate on upgrade.
12228                                // Note that in a permission review mode install permissions are
12229                                // represented as constantly granted runtime ones since we need to
12230                                // keep a per user state associated with the permission. Also the
12231                                // revoke on upgrade flag is no longer applicable and is reset.
12232                                final boolean revokeOnUpgrade = (flags & PackageManager
12233                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12234                                if (revokeOnUpgrade) {
12235                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12236                                    // Since we changed the flags, we have to write.
12237                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12238                                            changedRuntimePermissionUserIds, userId);
12239                                }
12240                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12241                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12242                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12243                                        // If we cannot put the permission as it was,
12244                                        // we have to write.
12245                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12246                                                changedRuntimePermissionUserIds, userId);
12247                                    }
12248                                }
12249
12250                                // If the app supports runtime permissions no need for a review.
12251                                if (mPermissionReviewRequired
12252                                        && appSupportsRuntimePermissions
12253                                        && (flags & PackageManager
12254                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12255                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12256                                    // Since we changed the flags, we have to write.
12257                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12258                                            changedRuntimePermissionUserIds, userId);
12259                                }
12260                            } else if (mPermissionReviewRequired
12261                                    && !appSupportsRuntimePermissions) {
12262                                // For legacy apps that need a permission review, every new
12263                                // runtime permission is granted but it is pending a review.
12264                                // We also need to review only platform defined runtime
12265                                // permissions as these are the only ones the platform knows
12266                                // how to disable the API to simulate revocation as legacy
12267                                // apps don't expect to run with revoked permissions.
12268                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12269                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12270                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12271                                        // We changed the flags, hence have to write.
12272                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12273                                                changedRuntimePermissionUserIds, userId);
12274                                    }
12275                                }
12276                                if (permissionsState.grantRuntimePermission(bp, userId)
12277                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12278                                    // We changed the permission, hence have to write.
12279                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12280                                            changedRuntimePermissionUserIds, userId);
12281                                }
12282                            }
12283                            // Propagate the permission flags.
12284                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12285                        }
12286                    } break;
12287
12288                    case GRANT_UPGRADE: {
12289                        // Grant runtime permissions for a previously held install permission.
12290                        PermissionState permissionState = origPermissions
12291                                .getInstallPermissionState(perm);
12292                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12293
12294                        if (origPermissions.revokeInstallPermission(bp)
12295                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12296                            // We will be transferring the permission flags, so clear them.
12297                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12298                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12299                            changedInstallPermission = true;
12300                        }
12301
12302                        // If the permission is not to be promoted to runtime we ignore it and
12303                        // also its other flags as they are not applicable to install permissions.
12304                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12305                            for (int userId : currentUserIds) {
12306                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12307                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12308                                    // Transfer the permission flags.
12309                                    permissionsState.updatePermissionFlags(bp, userId,
12310                                            flags, flags);
12311                                    // If we granted the permission, we have to write.
12312                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12313                                            changedRuntimePermissionUserIds, userId);
12314                                }
12315                            }
12316                        }
12317                    } break;
12318
12319                    default: {
12320                        if (packageOfInterest == null
12321                                || packageOfInterest.equals(pkg.packageName)) {
12322                            if (DEBUG_PERMISSIONS) {
12323                                Slog.i(TAG, "Not granting permission " + perm
12324                                        + " to package " + pkg.packageName
12325                                        + " because it was previously installed without");
12326                            }
12327                        }
12328                    } break;
12329                }
12330            } else {
12331                if (permissionsState.revokeInstallPermission(bp) !=
12332                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12333                    // Also drop the permission flags.
12334                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12335                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12336                    changedInstallPermission = true;
12337                    Slog.i(TAG, "Un-granting permission " + perm
12338                            + " from package " + pkg.packageName
12339                            + " (protectionLevel=" + bp.getProtectionLevel()
12340                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12341                            + ")");
12342                } else if (bp.isAppOp()) {
12343                    // Don't print warning for app op permissions, since it is fine for them
12344                    // not to be granted, there is a UI for the user to decide.
12345                    if (DEBUG_PERMISSIONS
12346                            && (packageOfInterest == null
12347                                    || packageOfInterest.equals(pkg.packageName))) {
12348                        Slog.i(TAG, "Not granting permission " + perm
12349                                + " to package " + pkg.packageName
12350                                + " (protectionLevel=" + bp.getProtectionLevel()
12351                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12352                                + ")");
12353                    }
12354                }
12355            }
12356        }
12357
12358        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12359                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12360            // This is the first that we have heard about this package, so the
12361            // permissions we have now selected are fixed until explicitly
12362            // changed.
12363            ps.installPermissionsFixed = true;
12364        }
12365
12366        // Persist the runtime permissions state for users with changes. If permissions
12367        // were revoked because no app in the shared user declares them we have to
12368        // write synchronously to avoid losing runtime permissions state.
12369        for (int userId : changedRuntimePermissionUserIds) {
12370            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12371        }
12372    }
12373
12374    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12375        boolean allowed = false;
12376        final int NP = PackageParser.NEW_PERMISSIONS.length;
12377        for (int ip=0; ip<NP; ip++) {
12378            final PackageParser.NewPermissionInfo npi
12379                    = PackageParser.NEW_PERMISSIONS[ip];
12380            if (npi.name.equals(perm)
12381                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12382                allowed = true;
12383                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12384                        + pkg.packageName);
12385                break;
12386            }
12387        }
12388        return allowed;
12389    }
12390
12391    /**
12392     * Determines whether a package is whitelisted for a particular privapp permission.
12393     *
12394     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12395     *
12396     * <p>This handles parent/child apps.
12397     */
12398    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12399        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12400                .getPrivAppPermissions(pkg.packageName);
12401        // Let's check if this package is whitelisted...
12402        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12403        // If it's not, we'll also tail-recurse to the parent.
12404        return whitelisted ||
12405                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12406    }
12407
12408    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12409            BasePermission bp, PermissionsState origPermissions) {
12410        boolean oemPermission = bp.isOEM();
12411        boolean privilegedPermission = bp.isPrivileged();
12412        boolean privappPermissionsDisable =
12413                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12414        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12415        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12416        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12417                && !platformPackage && platformPermission) {
12418            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12419                Slog.w(TAG, "Privileged permission " + perm + " for package "
12420                        + pkg.packageName + " - not in privapp-permissions whitelist");
12421                // Only report violations for apps on system image
12422                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12423                    // it's only a reportable violation if the permission isn't explicitly denied
12424                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12425                            .getPrivAppDenyPermissions(pkg.packageName);
12426                    final boolean permissionViolation =
12427                            deniedPermissions == null || !deniedPermissions.contains(perm);
12428                    if (permissionViolation) {
12429                        if (mPrivappPermissionsViolations == null) {
12430                            mPrivappPermissionsViolations = new ArraySet<>();
12431                        }
12432                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12433                    } else {
12434                        return false;
12435                    }
12436                }
12437                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12438                    return false;
12439                }
12440            }
12441        }
12442        boolean allowed = (compareSignatures(
12443                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12444                        == PackageManager.SIGNATURE_MATCH)
12445                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12446                        == PackageManager.SIGNATURE_MATCH);
12447        if (!allowed && (privilegedPermission || oemPermission)) {
12448            if (isSystemApp(pkg)) {
12449                // For updated system applications, a privileged/oem permission
12450                // is granted only if it had been defined by the original application.
12451                if (pkg.isUpdatedSystemApp()) {
12452                    final PackageSetting sysPs = mSettings
12453                            .getDisabledSystemPkgLPr(pkg.packageName);
12454                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12455                        // If the original was granted this permission, we take
12456                        // that grant decision as read and propagate it to the
12457                        // update.
12458                        if ((privilegedPermission && sysPs.isPrivileged())
12459                                || (oemPermission && sysPs.isOem()
12460                                        && canGrantOemPermission(sysPs, perm))) {
12461                            allowed = true;
12462                        }
12463                    } else {
12464                        // The system apk may have been updated with an older
12465                        // version of the one on the data partition, but which
12466                        // granted a new system permission that it didn't have
12467                        // before.  In this case we do want to allow the app to
12468                        // now get the new permission if the ancestral apk is
12469                        // privileged to get it.
12470                        if (sysPs != null && sysPs.pkg != null
12471                                && isPackageRequestingPermission(sysPs.pkg, perm)
12472                                && ((privilegedPermission && sysPs.isPrivileged())
12473                                        || (oemPermission && sysPs.isOem()
12474                                                && canGrantOemPermission(sysPs, perm)))) {
12475                            allowed = true;
12476                        }
12477                        // Also if a privileged parent package on the system image or any of
12478                        // its children requested a privileged/oem permission, the updated child
12479                        // packages can also get the permission.
12480                        if (pkg.parentPackage != null) {
12481                            final PackageSetting disabledSysParentPs = mSettings
12482                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12483                            final PackageParser.Package disabledSysParentPkg =
12484                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12485                                    ? null : disabledSysParentPs.pkg;
12486                            if (disabledSysParentPkg != null
12487                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12488                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12489                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12490                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12491                                    allowed = true;
12492                                } else if (disabledSysParentPkg.childPackages != null) {
12493                                    final int count = disabledSysParentPkg.childPackages.size();
12494                                    for (int i = 0; i < count; i++) {
12495                                        final PackageParser.Package disabledSysChildPkg =
12496                                                disabledSysParentPkg.childPackages.get(i);
12497                                        final PackageSetting disabledSysChildPs =
12498                                                mSettings.getDisabledSystemPkgLPr(
12499                                                        disabledSysChildPkg.packageName);
12500                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12501                                                && canGrantOemPermission(
12502                                                        disabledSysChildPs, perm)) {
12503                                            allowed = true;
12504                                            break;
12505                                        }
12506                                    }
12507                                }
12508                            }
12509                        }
12510                    }
12511                } else {
12512                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12513                            || (oemPermission && isOemApp(pkg)
12514                                    && canGrantOemPermission(
12515                                            mSettings.getPackageLPr(pkg.packageName), perm));
12516                }
12517            }
12518        }
12519        if (!allowed) {
12520            if (!allowed
12521                    && bp.isPre23()
12522                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12523                // If this was a previously normal/dangerous permission that got moved
12524                // to a system permission as part of the runtime permission redesign, then
12525                // we still want to blindly grant it to old apps.
12526                allowed = true;
12527            }
12528            if (!allowed && bp.isInstaller()
12529                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12530                // If this permission is to be granted to the system installer and
12531                // this app is an installer, then it gets the permission.
12532                allowed = true;
12533            }
12534            if (!allowed && bp.isVerifier()
12535                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12536                // If this permission is to be granted to the system verifier and
12537                // this app is a verifier, then it gets the permission.
12538                allowed = true;
12539            }
12540            if (!allowed && bp.isPreInstalled()
12541                    && isSystemApp(pkg)) {
12542                // Any pre-installed system app is allowed to get this permission.
12543                allowed = true;
12544            }
12545            if (!allowed && bp.isDevelopment()) {
12546                // For development permissions, a development permission
12547                // is granted only if it was already granted.
12548                allowed = origPermissions.hasInstallPermission(perm);
12549            }
12550            if (!allowed && bp.isSetup()
12551                    && pkg.packageName.equals(mSetupWizardPackage)) {
12552                // If this permission is to be granted to the system setup wizard and
12553                // this app is a setup wizard, then it gets the permission.
12554                allowed = true;
12555            }
12556        }
12557        return allowed;
12558    }
12559
12560    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12561        if (!ps.isOem()) {
12562            return false;
12563        }
12564        // all oem permissions must explicitly be granted or denied
12565        final Boolean granted =
12566                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12567        if (granted == null) {
12568            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12569                    + ps.name + " must be explicitly declared granted or not");
12570        }
12571        return Boolean.TRUE == granted;
12572    }
12573
12574    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12575        final int permCount = pkg.requestedPermissions.size();
12576        for (int j = 0; j < permCount; j++) {
12577            String requestedPermission = pkg.requestedPermissions.get(j);
12578            if (permission.equals(requestedPermission)) {
12579                return true;
12580            }
12581        }
12582        return false;
12583    }
12584
12585    final class ActivityIntentResolver
12586            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12587        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12588                boolean defaultOnly, int userId) {
12589            if (!sUserManager.exists(userId)) return null;
12590            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12591            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12592        }
12593
12594        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12595                int userId) {
12596            if (!sUserManager.exists(userId)) return null;
12597            mFlags = flags;
12598            return super.queryIntent(intent, resolvedType,
12599                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12600                    userId);
12601        }
12602
12603        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12604                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12605            if (!sUserManager.exists(userId)) return null;
12606            if (packageActivities == null) {
12607                return null;
12608            }
12609            mFlags = flags;
12610            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12611            final int N = packageActivities.size();
12612            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12613                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12614
12615            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12616            for (int i = 0; i < N; ++i) {
12617                intentFilters = packageActivities.get(i).intents;
12618                if (intentFilters != null && intentFilters.size() > 0) {
12619                    PackageParser.ActivityIntentInfo[] array =
12620                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12621                    intentFilters.toArray(array);
12622                    listCut.add(array);
12623                }
12624            }
12625            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12626        }
12627
12628        /**
12629         * Finds a privileged activity that matches the specified activity names.
12630         */
12631        private PackageParser.Activity findMatchingActivity(
12632                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12633            for (PackageParser.Activity sysActivity : activityList) {
12634                if (sysActivity.info.name.equals(activityInfo.name)) {
12635                    return sysActivity;
12636                }
12637                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12638                    return sysActivity;
12639                }
12640                if (sysActivity.info.targetActivity != null) {
12641                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12642                        return sysActivity;
12643                    }
12644                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12645                        return sysActivity;
12646                    }
12647                }
12648            }
12649            return null;
12650        }
12651
12652        public class IterGenerator<E> {
12653            public Iterator<E> generate(ActivityIntentInfo info) {
12654                return null;
12655            }
12656        }
12657
12658        public class ActionIterGenerator extends IterGenerator<String> {
12659            @Override
12660            public Iterator<String> generate(ActivityIntentInfo info) {
12661                return info.actionsIterator();
12662            }
12663        }
12664
12665        public class CategoriesIterGenerator extends IterGenerator<String> {
12666            @Override
12667            public Iterator<String> generate(ActivityIntentInfo info) {
12668                return info.categoriesIterator();
12669            }
12670        }
12671
12672        public class SchemesIterGenerator extends IterGenerator<String> {
12673            @Override
12674            public Iterator<String> generate(ActivityIntentInfo info) {
12675                return info.schemesIterator();
12676            }
12677        }
12678
12679        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12680            @Override
12681            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12682                return info.authoritiesIterator();
12683            }
12684        }
12685
12686        /**
12687         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12688         * MODIFIED. Do not pass in a list that should not be changed.
12689         */
12690        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12691                IterGenerator<T> generator, Iterator<T> searchIterator) {
12692            // loop through the set of actions; every one must be found in the intent filter
12693            while (searchIterator.hasNext()) {
12694                // we must have at least one filter in the list to consider a match
12695                if (intentList.size() == 0) {
12696                    break;
12697                }
12698
12699                final T searchAction = searchIterator.next();
12700
12701                // loop through the set of intent filters
12702                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12703                while (intentIter.hasNext()) {
12704                    final ActivityIntentInfo intentInfo = intentIter.next();
12705                    boolean selectionFound = false;
12706
12707                    // loop through the intent filter's selection criteria; at least one
12708                    // of them must match the searched criteria
12709                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12710                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12711                        final T intentSelection = intentSelectionIter.next();
12712                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12713                            selectionFound = true;
12714                            break;
12715                        }
12716                    }
12717
12718                    // the selection criteria wasn't found in this filter's set; this filter
12719                    // is not a potential match
12720                    if (!selectionFound) {
12721                        intentIter.remove();
12722                    }
12723                }
12724            }
12725        }
12726
12727        private boolean isProtectedAction(ActivityIntentInfo filter) {
12728            final Iterator<String> actionsIter = filter.actionsIterator();
12729            while (actionsIter != null && actionsIter.hasNext()) {
12730                final String filterAction = actionsIter.next();
12731                if (PROTECTED_ACTIONS.contains(filterAction)) {
12732                    return true;
12733                }
12734            }
12735            return false;
12736        }
12737
12738        /**
12739         * Adjusts the priority of the given intent filter according to policy.
12740         * <p>
12741         * <ul>
12742         * <li>The priority for non privileged applications is capped to '0'</li>
12743         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12744         * <li>The priority for unbundled updates to privileged applications is capped to the
12745         *      priority defined on the system partition</li>
12746         * </ul>
12747         * <p>
12748         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12749         * allowed to obtain any priority on any action.
12750         */
12751        private void adjustPriority(
12752                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12753            // nothing to do; priority is fine as-is
12754            if (intent.getPriority() <= 0) {
12755                return;
12756            }
12757
12758            final ActivityInfo activityInfo = intent.activity.info;
12759            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12760
12761            final boolean privilegedApp =
12762                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12763            if (!privilegedApp) {
12764                // non-privileged applications can never define a priority >0
12765                if (DEBUG_FILTERS) {
12766                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12767                            + " package: " + applicationInfo.packageName
12768                            + " activity: " + intent.activity.className
12769                            + " origPrio: " + intent.getPriority());
12770                }
12771                intent.setPriority(0);
12772                return;
12773            }
12774
12775            if (systemActivities == null) {
12776                // the system package is not disabled; we're parsing the system partition
12777                if (isProtectedAction(intent)) {
12778                    if (mDeferProtectedFilters) {
12779                        // We can't deal with these just yet. No component should ever obtain a
12780                        // >0 priority for a protected actions, with ONE exception -- the setup
12781                        // wizard. The setup wizard, however, cannot be known until we're able to
12782                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12783                        // until all intent filters have been processed. Chicken, meet egg.
12784                        // Let the filter temporarily have a high priority and rectify the
12785                        // priorities after all system packages have been scanned.
12786                        mProtectedFilters.add(intent);
12787                        if (DEBUG_FILTERS) {
12788                            Slog.i(TAG, "Protected action; save for later;"
12789                                    + " package: " + applicationInfo.packageName
12790                                    + " activity: " + intent.activity.className
12791                                    + " origPrio: " + intent.getPriority());
12792                        }
12793                        return;
12794                    } else {
12795                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12796                            Slog.i(TAG, "No setup wizard;"
12797                                + " All protected intents capped to priority 0");
12798                        }
12799                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12800                            if (DEBUG_FILTERS) {
12801                                Slog.i(TAG, "Found setup wizard;"
12802                                    + " allow priority " + intent.getPriority() + ";"
12803                                    + " package: " + intent.activity.info.packageName
12804                                    + " activity: " + intent.activity.className
12805                                    + " priority: " + intent.getPriority());
12806                            }
12807                            // setup wizard gets whatever it wants
12808                            return;
12809                        }
12810                        if (DEBUG_FILTERS) {
12811                            Slog.i(TAG, "Protected action; cap priority to 0;"
12812                                    + " package: " + intent.activity.info.packageName
12813                                    + " activity: " + intent.activity.className
12814                                    + " origPrio: " + intent.getPriority());
12815                        }
12816                        intent.setPriority(0);
12817                        return;
12818                    }
12819                }
12820                // privileged apps on the system image get whatever priority they request
12821                return;
12822            }
12823
12824            // privileged app unbundled update ... try to find the same activity
12825            final PackageParser.Activity foundActivity =
12826                    findMatchingActivity(systemActivities, activityInfo);
12827            if (foundActivity == null) {
12828                // this is a new activity; it cannot obtain >0 priority
12829                if (DEBUG_FILTERS) {
12830                    Slog.i(TAG, "New activity; cap priority to 0;"
12831                            + " package: " + applicationInfo.packageName
12832                            + " activity: " + intent.activity.className
12833                            + " origPrio: " + intent.getPriority());
12834                }
12835                intent.setPriority(0);
12836                return;
12837            }
12838
12839            // found activity, now check for filter equivalence
12840
12841            // a shallow copy is enough; we modify the list, not its contents
12842            final List<ActivityIntentInfo> intentListCopy =
12843                    new ArrayList<>(foundActivity.intents);
12844            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12845
12846            // find matching action subsets
12847            final Iterator<String> actionsIterator = intent.actionsIterator();
12848            if (actionsIterator != null) {
12849                getIntentListSubset(
12850                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12851                if (intentListCopy.size() == 0) {
12852                    // no more intents to match; we're not equivalent
12853                    if (DEBUG_FILTERS) {
12854                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12855                                + " package: " + applicationInfo.packageName
12856                                + " activity: " + intent.activity.className
12857                                + " origPrio: " + intent.getPriority());
12858                    }
12859                    intent.setPriority(0);
12860                    return;
12861                }
12862            }
12863
12864            // find matching category subsets
12865            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12866            if (categoriesIterator != null) {
12867                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12868                        categoriesIterator);
12869                if (intentListCopy.size() == 0) {
12870                    // no more intents to match; we're not equivalent
12871                    if (DEBUG_FILTERS) {
12872                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12873                                + " package: " + applicationInfo.packageName
12874                                + " activity: " + intent.activity.className
12875                                + " origPrio: " + intent.getPriority());
12876                    }
12877                    intent.setPriority(0);
12878                    return;
12879                }
12880            }
12881
12882            // find matching schemes subsets
12883            final Iterator<String> schemesIterator = intent.schemesIterator();
12884            if (schemesIterator != null) {
12885                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12886                        schemesIterator);
12887                if (intentListCopy.size() == 0) {
12888                    // no more intents to match; we're not equivalent
12889                    if (DEBUG_FILTERS) {
12890                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12891                                + " package: " + applicationInfo.packageName
12892                                + " activity: " + intent.activity.className
12893                                + " origPrio: " + intent.getPriority());
12894                    }
12895                    intent.setPriority(0);
12896                    return;
12897                }
12898            }
12899
12900            // find matching authorities subsets
12901            final Iterator<IntentFilter.AuthorityEntry>
12902                    authoritiesIterator = intent.authoritiesIterator();
12903            if (authoritiesIterator != null) {
12904                getIntentListSubset(intentListCopy,
12905                        new AuthoritiesIterGenerator(),
12906                        authoritiesIterator);
12907                if (intentListCopy.size() == 0) {
12908                    // no more intents to match; we're not equivalent
12909                    if (DEBUG_FILTERS) {
12910                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12911                                + " package: " + applicationInfo.packageName
12912                                + " activity: " + intent.activity.className
12913                                + " origPrio: " + intent.getPriority());
12914                    }
12915                    intent.setPriority(0);
12916                    return;
12917                }
12918            }
12919
12920            // we found matching filter(s); app gets the max priority of all intents
12921            int cappedPriority = 0;
12922            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12923                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12924            }
12925            if (intent.getPriority() > cappedPriority) {
12926                if (DEBUG_FILTERS) {
12927                    Slog.i(TAG, "Found matching filter(s);"
12928                            + " cap priority to " + cappedPriority + ";"
12929                            + " package: " + applicationInfo.packageName
12930                            + " activity: " + intent.activity.className
12931                            + " origPrio: " + intent.getPriority());
12932                }
12933                intent.setPriority(cappedPriority);
12934                return;
12935            }
12936            // all this for nothing; the requested priority was <= what was on the system
12937        }
12938
12939        public final void addActivity(PackageParser.Activity a, String type) {
12940            mActivities.put(a.getComponentName(), a);
12941            if (DEBUG_SHOW_INFO)
12942                Log.v(
12943                TAG, "  " + type + " " +
12944                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12945            if (DEBUG_SHOW_INFO)
12946                Log.v(TAG, "    Class=" + a.info.name);
12947            final int NI = a.intents.size();
12948            for (int j=0; j<NI; j++) {
12949                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12950                if ("activity".equals(type)) {
12951                    final PackageSetting ps =
12952                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12953                    final List<PackageParser.Activity> systemActivities =
12954                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12955                    adjustPriority(systemActivities, intent);
12956                }
12957                if (DEBUG_SHOW_INFO) {
12958                    Log.v(TAG, "    IntentFilter:");
12959                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12960                }
12961                if (!intent.debugCheck()) {
12962                    Log.w(TAG, "==> For Activity " + a.info.name);
12963                }
12964                addFilter(intent);
12965            }
12966        }
12967
12968        public final void removeActivity(PackageParser.Activity a, String type) {
12969            mActivities.remove(a.getComponentName());
12970            if (DEBUG_SHOW_INFO) {
12971                Log.v(TAG, "  " + type + " "
12972                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12973                                : a.info.name) + ":");
12974                Log.v(TAG, "    Class=" + a.info.name);
12975            }
12976            final int NI = a.intents.size();
12977            for (int j=0; j<NI; j++) {
12978                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12979                if (DEBUG_SHOW_INFO) {
12980                    Log.v(TAG, "    IntentFilter:");
12981                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12982                }
12983                removeFilter(intent);
12984            }
12985        }
12986
12987        @Override
12988        protected boolean allowFilterResult(
12989                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12990            ActivityInfo filterAi = filter.activity.info;
12991            for (int i=dest.size()-1; i>=0; i--) {
12992                ActivityInfo destAi = dest.get(i).activityInfo;
12993                if (destAi.name == filterAi.name
12994                        && destAi.packageName == filterAi.packageName) {
12995                    return false;
12996                }
12997            }
12998            return true;
12999        }
13000
13001        @Override
13002        protected ActivityIntentInfo[] newArray(int size) {
13003            return new ActivityIntentInfo[size];
13004        }
13005
13006        @Override
13007        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13008            if (!sUserManager.exists(userId)) return true;
13009            PackageParser.Package p = filter.activity.owner;
13010            if (p != null) {
13011                PackageSetting ps = (PackageSetting)p.mExtras;
13012                if (ps != null) {
13013                    // System apps are never considered stopped for purposes of
13014                    // filtering, because there may be no way for the user to
13015                    // actually re-launch them.
13016                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13017                            && ps.getStopped(userId);
13018                }
13019            }
13020            return false;
13021        }
13022
13023        @Override
13024        protected boolean isPackageForFilter(String packageName,
13025                PackageParser.ActivityIntentInfo info) {
13026            return packageName.equals(info.activity.owner.packageName);
13027        }
13028
13029        @Override
13030        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13031                int match, int userId) {
13032            if (!sUserManager.exists(userId)) return null;
13033            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13034                return null;
13035            }
13036            final PackageParser.Activity activity = info.activity;
13037            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13038            if (ps == null) {
13039                return null;
13040            }
13041            final PackageUserState userState = ps.readUserState(userId);
13042            ActivityInfo ai =
13043                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13044            if (ai == null) {
13045                return null;
13046            }
13047            final boolean matchExplicitlyVisibleOnly =
13048                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13049            final boolean matchVisibleToInstantApp =
13050                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13051            final boolean componentVisible =
13052                    matchVisibleToInstantApp
13053                    && info.isVisibleToInstantApp()
13054                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13055            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13056            // throw out filters that aren't visible to ephemeral apps
13057            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13058                return null;
13059            }
13060            // throw out instant app filters if we're not explicitly requesting them
13061            if (!matchInstantApp && userState.instantApp) {
13062                return null;
13063            }
13064            // throw out instant app filters if updates are available; will trigger
13065            // instant app resolution
13066            if (userState.instantApp && ps.isUpdateAvailable()) {
13067                return null;
13068            }
13069            final ResolveInfo res = new ResolveInfo();
13070            res.activityInfo = ai;
13071            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13072                res.filter = info;
13073            }
13074            if (info != null) {
13075                res.handleAllWebDataURI = info.handleAllWebDataURI();
13076            }
13077            res.priority = info.getPriority();
13078            res.preferredOrder = activity.owner.mPreferredOrder;
13079            //System.out.println("Result: " + res.activityInfo.className +
13080            //                   " = " + res.priority);
13081            res.match = match;
13082            res.isDefault = info.hasDefault;
13083            res.labelRes = info.labelRes;
13084            res.nonLocalizedLabel = info.nonLocalizedLabel;
13085            if (userNeedsBadging(userId)) {
13086                res.noResourceId = true;
13087            } else {
13088                res.icon = info.icon;
13089            }
13090            res.iconResourceId = info.icon;
13091            res.system = res.activityInfo.applicationInfo.isSystemApp();
13092            res.isInstantAppAvailable = userState.instantApp;
13093            return res;
13094        }
13095
13096        @Override
13097        protected void sortResults(List<ResolveInfo> results) {
13098            Collections.sort(results, mResolvePrioritySorter);
13099        }
13100
13101        @Override
13102        protected void dumpFilter(PrintWriter out, String prefix,
13103                PackageParser.ActivityIntentInfo filter) {
13104            out.print(prefix); out.print(
13105                    Integer.toHexString(System.identityHashCode(filter.activity)));
13106                    out.print(' ');
13107                    filter.activity.printComponentShortName(out);
13108                    out.print(" filter ");
13109                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13110        }
13111
13112        @Override
13113        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13114            return filter.activity;
13115        }
13116
13117        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13118            PackageParser.Activity activity = (PackageParser.Activity)label;
13119            out.print(prefix); out.print(
13120                    Integer.toHexString(System.identityHashCode(activity)));
13121                    out.print(' ');
13122                    activity.printComponentShortName(out);
13123            if (count > 1) {
13124                out.print(" ("); out.print(count); out.print(" filters)");
13125            }
13126            out.println();
13127        }
13128
13129        // Keys are String (activity class name), values are Activity.
13130        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13131                = new ArrayMap<ComponentName, PackageParser.Activity>();
13132        private int mFlags;
13133    }
13134
13135    private final class ServiceIntentResolver
13136            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13137        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13138                boolean defaultOnly, int userId) {
13139            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13140            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13141        }
13142
13143        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13144                int userId) {
13145            if (!sUserManager.exists(userId)) return null;
13146            mFlags = flags;
13147            return super.queryIntent(intent, resolvedType,
13148                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13149                    userId);
13150        }
13151
13152        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13153                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13154            if (!sUserManager.exists(userId)) return null;
13155            if (packageServices == null) {
13156                return null;
13157            }
13158            mFlags = flags;
13159            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13160            final int N = packageServices.size();
13161            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13162                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13163
13164            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13165            for (int i = 0; i < N; ++i) {
13166                intentFilters = packageServices.get(i).intents;
13167                if (intentFilters != null && intentFilters.size() > 0) {
13168                    PackageParser.ServiceIntentInfo[] array =
13169                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13170                    intentFilters.toArray(array);
13171                    listCut.add(array);
13172                }
13173            }
13174            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13175        }
13176
13177        public final void addService(PackageParser.Service s) {
13178            mServices.put(s.getComponentName(), s);
13179            if (DEBUG_SHOW_INFO) {
13180                Log.v(TAG, "  "
13181                        + (s.info.nonLocalizedLabel != null
13182                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13183                Log.v(TAG, "    Class=" + s.info.name);
13184            }
13185            final int NI = s.intents.size();
13186            int j;
13187            for (j=0; j<NI; j++) {
13188                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13189                if (DEBUG_SHOW_INFO) {
13190                    Log.v(TAG, "    IntentFilter:");
13191                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13192                }
13193                if (!intent.debugCheck()) {
13194                    Log.w(TAG, "==> For Service " + s.info.name);
13195                }
13196                addFilter(intent);
13197            }
13198        }
13199
13200        public final void removeService(PackageParser.Service s) {
13201            mServices.remove(s.getComponentName());
13202            if (DEBUG_SHOW_INFO) {
13203                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13204                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13205                Log.v(TAG, "    Class=" + s.info.name);
13206            }
13207            final int NI = s.intents.size();
13208            int j;
13209            for (j=0; j<NI; j++) {
13210                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13211                if (DEBUG_SHOW_INFO) {
13212                    Log.v(TAG, "    IntentFilter:");
13213                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13214                }
13215                removeFilter(intent);
13216            }
13217        }
13218
13219        @Override
13220        protected boolean allowFilterResult(
13221                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13222            ServiceInfo filterSi = filter.service.info;
13223            for (int i=dest.size()-1; i>=0; i--) {
13224                ServiceInfo destAi = dest.get(i).serviceInfo;
13225                if (destAi.name == filterSi.name
13226                        && destAi.packageName == filterSi.packageName) {
13227                    return false;
13228                }
13229            }
13230            return true;
13231        }
13232
13233        @Override
13234        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13235            return new PackageParser.ServiceIntentInfo[size];
13236        }
13237
13238        @Override
13239        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13240            if (!sUserManager.exists(userId)) return true;
13241            PackageParser.Package p = filter.service.owner;
13242            if (p != null) {
13243                PackageSetting ps = (PackageSetting)p.mExtras;
13244                if (ps != null) {
13245                    // System apps are never considered stopped for purposes of
13246                    // filtering, because there may be no way for the user to
13247                    // actually re-launch them.
13248                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13249                            && ps.getStopped(userId);
13250                }
13251            }
13252            return false;
13253        }
13254
13255        @Override
13256        protected boolean isPackageForFilter(String packageName,
13257                PackageParser.ServiceIntentInfo info) {
13258            return packageName.equals(info.service.owner.packageName);
13259        }
13260
13261        @Override
13262        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13263                int match, int userId) {
13264            if (!sUserManager.exists(userId)) return null;
13265            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13266            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13267                return null;
13268            }
13269            final PackageParser.Service service = info.service;
13270            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13271            if (ps == null) {
13272                return null;
13273            }
13274            final PackageUserState userState = ps.readUserState(userId);
13275            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13276                    userState, userId);
13277            if (si == null) {
13278                return null;
13279            }
13280            final boolean matchVisibleToInstantApp =
13281                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13282            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13283            // throw out filters that aren't visible to ephemeral apps
13284            if (matchVisibleToInstantApp
13285                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13286                return null;
13287            }
13288            // throw out ephemeral filters if we're not explicitly requesting them
13289            if (!isInstantApp && userState.instantApp) {
13290                return null;
13291            }
13292            // throw out instant app filters if updates are available; will trigger
13293            // instant app resolution
13294            if (userState.instantApp && ps.isUpdateAvailable()) {
13295                return null;
13296            }
13297            final ResolveInfo res = new ResolveInfo();
13298            res.serviceInfo = si;
13299            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13300                res.filter = filter;
13301            }
13302            res.priority = info.getPriority();
13303            res.preferredOrder = service.owner.mPreferredOrder;
13304            res.match = match;
13305            res.isDefault = info.hasDefault;
13306            res.labelRes = info.labelRes;
13307            res.nonLocalizedLabel = info.nonLocalizedLabel;
13308            res.icon = info.icon;
13309            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13310            return res;
13311        }
13312
13313        @Override
13314        protected void sortResults(List<ResolveInfo> results) {
13315            Collections.sort(results, mResolvePrioritySorter);
13316        }
13317
13318        @Override
13319        protected void dumpFilter(PrintWriter out, String prefix,
13320                PackageParser.ServiceIntentInfo filter) {
13321            out.print(prefix); out.print(
13322                    Integer.toHexString(System.identityHashCode(filter.service)));
13323                    out.print(' ');
13324                    filter.service.printComponentShortName(out);
13325                    out.print(" filter ");
13326                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13327        }
13328
13329        @Override
13330        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13331            return filter.service;
13332        }
13333
13334        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13335            PackageParser.Service service = (PackageParser.Service)label;
13336            out.print(prefix); out.print(
13337                    Integer.toHexString(System.identityHashCode(service)));
13338                    out.print(' ');
13339                    service.printComponentShortName(out);
13340            if (count > 1) {
13341                out.print(" ("); out.print(count); out.print(" filters)");
13342            }
13343            out.println();
13344        }
13345
13346//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13347//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13348//            final List<ResolveInfo> retList = Lists.newArrayList();
13349//            while (i.hasNext()) {
13350//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13351//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13352//                    retList.add(resolveInfo);
13353//                }
13354//            }
13355//            return retList;
13356//        }
13357
13358        // Keys are String (activity class name), values are Activity.
13359        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13360                = new ArrayMap<ComponentName, PackageParser.Service>();
13361        private int mFlags;
13362    }
13363
13364    private final class ProviderIntentResolver
13365            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13367                boolean defaultOnly, int userId) {
13368            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13369            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13370        }
13371
13372        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13373                int userId) {
13374            if (!sUserManager.exists(userId))
13375                return null;
13376            mFlags = flags;
13377            return super.queryIntent(intent, resolvedType,
13378                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13379                    userId);
13380        }
13381
13382        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13383                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13384            if (!sUserManager.exists(userId))
13385                return null;
13386            if (packageProviders == null) {
13387                return null;
13388            }
13389            mFlags = flags;
13390            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13391            final int N = packageProviders.size();
13392            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13393                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13394
13395            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13396            for (int i = 0; i < N; ++i) {
13397                intentFilters = packageProviders.get(i).intents;
13398                if (intentFilters != null && intentFilters.size() > 0) {
13399                    PackageParser.ProviderIntentInfo[] array =
13400                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13401                    intentFilters.toArray(array);
13402                    listCut.add(array);
13403                }
13404            }
13405            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13406        }
13407
13408        public final void addProvider(PackageParser.Provider p) {
13409            if (mProviders.containsKey(p.getComponentName())) {
13410                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13411                return;
13412            }
13413
13414            mProviders.put(p.getComponentName(), p);
13415            if (DEBUG_SHOW_INFO) {
13416                Log.v(TAG, "  "
13417                        + (p.info.nonLocalizedLabel != null
13418                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13419                Log.v(TAG, "    Class=" + p.info.name);
13420            }
13421            final int NI = p.intents.size();
13422            int j;
13423            for (j = 0; j < NI; j++) {
13424                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13425                if (DEBUG_SHOW_INFO) {
13426                    Log.v(TAG, "    IntentFilter:");
13427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13428                }
13429                if (!intent.debugCheck()) {
13430                    Log.w(TAG, "==> For Provider " + p.info.name);
13431                }
13432                addFilter(intent);
13433            }
13434        }
13435
13436        public final void removeProvider(PackageParser.Provider p) {
13437            mProviders.remove(p.getComponentName());
13438            if (DEBUG_SHOW_INFO) {
13439                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13440                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13441                Log.v(TAG, "    Class=" + p.info.name);
13442            }
13443            final int NI = p.intents.size();
13444            int j;
13445            for (j = 0; j < NI; j++) {
13446                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13447                if (DEBUG_SHOW_INFO) {
13448                    Log.v(TAG, "    IntentFilter:");
13449                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13450                }
13451                removeFilter(intent);
13452            }
13453        }
13454
13455        @Override
13456        protected boolean allowFilterResult(
13457                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13458            ProviderInfo filterPi = filter.provider.info;
13459            for (int i = dest.size() - 1; i >= 0; i--) {
13460                ProviderInfo destPi = dest.get(i).providerInfo;
13461                if (destPi.name == filterPi.name
13462                        && destPi.packageName == filterPi.packageName) {
13463                    return false;
13464                }
13465            }
13466            return true;
13467        }
13468
13469        @Override
13470        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13471            return new PackageParser.ProviderIntentInfo[size];
13472        }
13473
13474        @Override
13475        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13476            if (!sUserManager.exists(userId))
13477                return true;
13478            PackageParser.Package p = filter.provider.owner;
13479            if (p != null) {
13480                PackageSetting ps = (PackageSetting) p.mExtras;
13481                if (ps != null) {
13482                    // System apps are never considered stopped for purposes of
13483                    // filtering, because there may be no way for the user to
13484                    // actually re-launch them.
13485                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13486                            && ps.getStopped(userId);
13487                }
13488            }
13489            return false;
13490        }
13491
13492        @Override
13493        protected boolean isPackageForFilter(String packageName,
13494                PackageParser.ProviderIntentInfo info) {
13495            return packageName.equals(info.provider.owner.packageName);
13496        }
13497
13498        @Override
13499        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13500                int match, int userId) {
13501            if (!sUserManager.exists(userId))
13502                return null;
13503            final PackageParser.ProviderIntentInfo info = filter;
13504            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13505                return null;
13506            }
13507            final PackageParser.Provider provider = info.provider;
13508            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13509            if (ps == null) {
13510                return null;
13511            }
13512            final PackageUserState userState = ps.readUserState(userId);
13513            final boolean matchVisibleToInstantApp =
13514                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13515            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13516            // throw out filters that aren't visible to instant applications
13517            if (matchVisibleToInstantApp
13518                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13519                return null;
13520            }
13521            // throw out instant application filters if we're not explicitly requesting them
13522            if (!isInstantApp && userState.instantApp) {
13523                return null;
13524            }
13525            // throw out instant application filters if updates are available; will trigger
13526            // instant application resolution
13527            if (userState.instantApp && ps.isUpdateAvailable()) {
13528                return null;
13529            }
13530            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13531                    userState, userId);
13532            if (pi == null) {
13533                return null;
13534            }
13535            final ResolveInfo res = new ResolveInfo();
13536            res.providerInfo = pi;
13537            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13538                res.filter = filter;
13539            }
13540            res.priority = info.getPriority();
13541            res.preferredOrder = provider.owner.mPreferredOrder;
13542            res.match = match;
13543            res.isDefault = info.hasDefault;
13544            res.labelRes = info.labelRes;
13545            res.nonLocalizedLabel = info.nonLocalizedLabel;
13546            res.icon = info.icon;
13547            res.system = res.providerInfo.applicationInfo.isSystemApp();
13548            return res;
13549        }
13550
13551        @Override
13552        protected void sortResults(List<ResolveInfo> results) {
13553            Collections.sort(results, mResolvePrioritySorter);
13554        }
13555
13556        @Override
13557        protected void dumpFilter(PrintWriter out, String prefix,
13558                PackageParser.ProviderIntentInfo filter) {
13559            out.print(prefix);
13560            out.print(
13561                    Integer.toHexString(System.identityHashCode(filter.provider)));
13562            out.print(' ');
13563            filter.provider.printComponentShortName(out);
13564            out.print(" filter ");
13565            out.println(Integer.toHexString(System.identityHashCode(filter)));
13566        }
13567
13568        @Override
13569        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13570            return filter.provider;
13571        }
13572
13573        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13574            PackageParser.Provider provider = (PackageParser.Provider)label;
13575            out.print(prefix); out.print(
13576                    Integer.toHexString(System.identityHashCode(provider)));
13577                    out.print(' ');
13578                    provider.printComponentShortName(out);
13579            if (count > 1) {
13580                out.print(" ("); out.print(count); out.print(" filters)");
13581            }
13582            out.println();
13583        }
13584
13585        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13586                = new ArrayMap<ComponentName, PackageParser.Provider>();
13587        private int mFlags;
13588    }
13589
13590    static final class EphemeralIntentResolver
13591            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13592        /**
13593         * The result that has the highest defined order. Ordering applies on a
13594         * per-package basis. Mapping is from package name to Pair of order and
13595         * EphemeralResolveInfo.
13596         * <p>
13597         * NOTE: This is implemented as a field variable for convenience and efficiency.
13598         * By having a field variable, we're able to track filter ordering as soon as
13599         * a non-zero order is defined. Otherwise, multiple loops across the result set
13600         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13601         * this needs to be contained entirely within {@link #filterResults}.
13602         */
13603        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13604
13605        @Override
13606        protected AuxiliaryResolveInfo[] newArray(int size) {
13607            return new AuxiliaryResolveInfo[size];
13608        }
13609
13610        @Override
13611        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13612            return true;
13613        }
13614
13615        @Override
13616        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13617                int userId) {
13618            if (!sUserManager.exists(userId)) {
13619                return null;
13620            }
13621            final String packageName = responseObj.resolveInfo.getPackageName();
13622            final Integer order = responseObj.getOrder();
13623            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13624                    mOrderResult.get(packageName);
13625            // ordering is enabled and this item's order isn't high enough
13626            if (lastOrderResult != null && lastOrderResult.first >= order) {
13627                return null;
13628            }
13629            final InstantAppResolveInfo res = responseObj.resolveInfo;
13630            if (order > 0) {
13631                // non-zero order, enable ordering
13632                mOrderResult.put(packageName, new Pair<>(order, res));
13633            }
13634            return responseObj;
13635        }
13636
13637        @Override
13638        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13639            // only do work if ordering is enabled [most of the time it won't be]
13640            if (mOrderResult.size() == 0) {
13641                return;
13642            }
13643            int resultSize = results.size();
13644            for (int i = 0; i < resultSize; i++) {
13645                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13646                final String packageName = info.getPackageName();
13647                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13648                if (savedInfo == null) {
13649                    // package doesn't having ordering
13650                    continue;
13651                }
13652                if (savedInfo.second == info) {
13653                    // circled back to the highest ordered item; remove from order list
13654                    mOrderResult.remove(packageName);
13655                    if (mOrderResult.size() == 0) {
13656                        // no more ordered items
13657                        break;
13658                    }
13659                    continue;
13660                }
13661                // item has a worse order, remove it from the result list
13662                results.remove(i);
13663                resultSize--;
13664                i--;
13665            }
13666        }
13667    }
13668
13669    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13670            new Comparator<ResolveInfo>() {
13671        public int compare(ResolveInfo r1, ResolveInfo r2) {
13672            int v1 = r1.priority;
13673            int v2 = r2.priority;
13674            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13675            if (v1 != v2) {
13676                return (v1 > v2) ? -1 : 1;
13677            }
13678            v1 = r1.preferredOrder;
13679            v2 = r2.preferredOrder;
13680            if (v1 != v2) {
13681                return (v1 > v2) ? -1 : 1;
13682            }
13683            if (r1.isDefault != r2.isDefault) {
13684                return r1.isDefault ? -1 : 1;
13685            }
13686            v1 = r1.match;
13687            v2 = r2.match;
13688            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13689            if (v1 != v2) {
13690                return (v1 > v2) ? -1 : 1;
13691            }
13692            if (r1.system != r2.system) {
13693                return r1.system ? -1 : 1;
13694            }
13695            if (r1.activityInfo != null) {
13696                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13697            }
13698            if (r1.serviceInfo != null) {
13699                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13700            }
13701            if (r1.providerInfo != null) {
13702                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13703            }
13704            return 0;
13705        }
13706    };
13707
13708    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13709            new Comparator<ProviderInfo>() {
13710        public int compare(ProviderInfo p1, ProviderInfo p2) {
13711            final int v1 = p1.initOrder;
13712            final int v2 = p2.initOrder;
13713            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13714        }
13715    };
13716
13717    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13718            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13719            final int[] userIds) {
13720        mHandler.post(new Runnable() {
13721            @Override
13722            public void run() {
13723                try {
13724                    final IActivityManager am = ActivityManager.getService();
13725                    if (am == null) return;
13726                    final int[] resolvedUserIds;
13727                    if (userIds == null) {
13728                        resolvedUserIds = am.getRunningUserIds();
13729                    } else {
13730                        resolvedUserIds = userIds;
13731                    }
13732                    for (int id : resolvedUserIds) {
13733                        final Intent intent = new Intent(action,
13734                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13735                        if (extras != null) {
13736                            intent.putExtras(extras);
13737                        }
13738                        if (targetPkg != null) {
13739                            intent.setPackage(targetPkg);
13740                        }
13741                        // Modify the UID when posting to other users
13742                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13743                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13744                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13745                            intent.putExtra(Intent.EXTRA_UID, uid);
13746                        }
13747                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13748                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13749                        if (DEBUG_BROADCASTS) {
13750                            RuntimeException here = new RuntimeException("here");
13751                            here.fillInStackTrace();
13752                            Slog.d(TAG, "Sending to user " + id + ": "
13753                                    + intent.toShortString(false, true, false, false)
13754                                    + " " + intent.getExtras(), here);
13755                        }
13756                        am.broadcastIntent(null, intent, null, finishedReceiver,
13757                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13758                                null, finishedReceiver != null, false, id);
13759                    }
13760                } catch (RemoteException ex) {
13761                }
13762            }
13763        });
13764    }
13765
13766    /**
13767     * Check if the external storage media is available. This is true if there
13768     * is a mounted external storage medium or if the external storage is
13769     * emulated.
13770     */
13771    private boolean isExternalMediaAvailable() {
13772        return mMediaMounted || Environment.isExternalStorageEmulated();
13773    }
13774
13775    @Override
13776    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13777        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13778            return null;
13779        }
13780        // writer
13781        synchronized (mPackages) {
13782            if (!isExternalMediaAvailable()) {
13783                // If the external storage is no longer mounted at this point,
13784                // the caller may not have been able to delete all of this
13785                // packages files and can not delete any more.  Bail.
13786                return null;
13787            }
13788            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13789            if (lastPackage != null) {
13790                pkgs.remove(lastPackage);
13791            }
13792            if (pkgs.size() > 0) {
13793                return pkgs.get(0);
13794            }
13795        }
13796        return null;
13797    }
13798
13799    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13800        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13801                userId, andCode ? 1 : 0, packageName);
13802        if (mSystemReady) {
13803            msg.sendToTarget();
13804        } else {
13805            if (mPostSystemReadyMessages == null) {
13806                mPostSystemReadyMessages = new ArrayList<>();
13807            }
13808            mPostSystemReadyMessages.add(msg);
13809        }
13810    }
13811
13812    void startCleaningPackages() {
13813        // reader
13814        if (!isExternalMediaAvailable()) {
13815            return;
13816        }
13817        synchronized (mPackages) {
13818            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13819                return;
13820            }
13821        }
13822        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13823        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13824        IActivityManager am = ActivityManager.getService();
13825        if (am != null) {
13826            int dcsUid = -1;
13827            synchronized (mPackages) {
13828                if (!mDefaultContainerWhitelisted) {
13829                    mDefaultContainerWhitelisted = true;
13830                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13831                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13832                }
13833            }
13834            try {
13835                if (dcsUid > 0) {
13836                    am.backgroundWhitelistUid(dcsUid);
13837                }
13838                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13839                        UserHandle.USER_SYSTEM);
13840            } catch (RemoteException e) {
13841            }
13842        }
13843    }
13844
13845    @Override
13846    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13847            int installFlags, String installerPackageName, int userId) {
13848        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13849
13850        final int callingUid = Binder.getCallingUid();
13851        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13852                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13853
13854        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13855            try {
13856                if (observer != null) {
13857                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13858                }
13859            } catch (RemoteException re) {
13860            }
13861            return;
13862        }
13863
13864        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13865            installFlags |= PackageManager.INSTALL_FROM_ADB;
13866
13867        } else {
13868            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13869            // about installerPackageName.
13870
13871            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13872            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13873        }
13874
13875        UserHandle user;
13876        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13877            user = UserHandle.ALL;
13878        } else {
13879            user = new UserHandle(userId);
13880        }
13881
13882        // Only system components can circumvent runtime permissions when installing.
13883        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13884                && mContext.checkCallingOrSelfPermission(Manifest.permission
13885                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13886            throw new SecurityException("You need the "
13887                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13888                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13889        }
13890
13891        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13892                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13893            throw new IllegalArgumentException(
13894                    "New installs into ASEC containers no longer supported");
13895        }
13896
13897        final File originFile = new File(originPath);
13898        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13899
13900        final Message msg = mHandler.obtainMessage(INIT_COPY);
13901        final VerificationInfo verificationInfo = new VerificationInfo(
13902                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13903        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13904                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13905                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13906                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13907        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13908        msg.obj = params;
13909
13910        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13911                System.identityHashCode(msg.obj));
13912        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13913                System.identityHashCode(msg.obj));
13914
13915        mHandler.sendMessage(msg);
13916    }
13917
13918
13919    /**
13920     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13921     * it is acting on behalf on an enterprise or the user).
13922     *
13923     * Note that the ordering of the conditionals in this method is important. The checks we perform
13924     * are as follows, in this order:
13925     *
13926     * 1) If the install is being performed by a system app, we can trust the app to have set the
13927     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13928     *    what it is.
13929     * 2) If the install is being performed by a device or profile owner app, the install reason
13930     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13931     *    set the install reason correctly. If the app targets an older SDK version where install
13932     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13933     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13934     * 3) In all other cases, the install is being performed by a regular app that is neither part
13935     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13936     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13937     *    set to enterprise policy and if so, change it to unknown instead.
13938     */
13939    private int fixUpInstallReason(String installerPackageName, int installerUid,
13940            int installReason) {
13941        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13942                == PERMISSION_GRANTED) {
13943            // If the install is being performed by a system app, we trust that app to have set the
13944            // install reason correctly.
13945            return installReason;
13946        }
13947
13948        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13949            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13950        if (dpm != null) {
13951            ComponentName owner = null;
13952            try {
13953                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13954                if (owner == null) {
13955                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13956                }
13957            } catch (RemoteException e) {
13958            }
13959            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13960                // If the install is being performed by a device or profile owner, the install
13961                // reason should be enterprise policy.
13962                return PackageManager.INSTALL_REASON_POLICY;
13963            }
13964        }
13965
13966        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13967            // If the install is being performed by a regular app (i.e. neither system app nor
13968            // device or profile owner), we have no reason to believe that the app is acting on
13969            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13970            // change it to unknown instead.
13971            return PackageManager.INSTALL_REASON_UNKNOWN;
13972        }
13973
13974        // If the install is being performed by a regular app and the install reason was set to any
13975        // value but enterprise policy, leave the install reason unchanged.
13976        return installReason;
13977    }
13978
13979    void installStage(String packageName, File stagedDir,
13980            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13981            String installerPackageName, int installerUid, UserHandle user,
13982            Certificate[][] certificates) {
13983        if (DEBUG_EPHEMERAL) {
13984            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13985                Slog.d(TAG, "Ephemeral install of " + packageName);
13986            }
13987        }
13988        final VerificationInfo verificationInfo = new VerificationInfo(
13989                sessionParams.originatingUri, sessionParams.referrerUri,
13990                sessionParams.originatingUid, installerUid);
13991
13992        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13993
13994        final Message msg = mHandler.obtainMessage(INIT_COPY);
13995        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13996                sessionParams.installReason);
13997        final InstallParams params = new InstallParams(origin, null, observer,
13998                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13999                verificationInfo, user, sessionParams.abiOverride,
14000                sessionParams.grantedRuntimePermissions, certificates, installReason);
14001        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14002        msg.obj = params;
14003
14004        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14005                System.identityHashCode(msg.obj));
14006        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14007                System.identityHashCode(msg.obj));
14008
14009        mHandler.sendMessage(msg);
14010    }
14011
14012    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14013            int userId) {
14014        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14015        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14016                false /*startReceiver*/, pkgSetting.appId, userId);
14017
14018        // Send a session commit broadcast
14019        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14020        info.installReason = pkgSetting.getInstallReason(userId);
14021        info.appPackageName = packageName;
14022        sendSessionCommitBroadcast(info, userId);
14023    }
14024
14025    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14026            boolean includeStopped, int appId, int... userIds) {
14027        if (ArrayUtils.isEmpty(userIds)) {
14028            return;
14029        }
14030        Bundle extras = new Bundle(1);
14031        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14032        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14033
14034        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14035                packageName, extras, 0, null, null, userIds);
14036        if (sendBootCompleted) {
14037            mHandler.post(() -> {
14038                        for (int userId : userIds) {
14039                            sendBootCompletedBroadcastToSystemApp(
14040                                    packageName, includeStopped, userId);
14041                        }
14042                    }
14043            );
14044        }
14045    }
14046
14047    /**
14048     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14049     * automatically without needing an explicit launch.
14050     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14051     */
14052    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14053            int userId) {
14054        // If user is not running, the app didn't miss any broadcast
14055        if (!mUserManagerInternal.isUserRunning(userId)) {
14056            return;
14057        }
14058        final IActivityManager am = ActivityManager.getService();
14059        try {
14060            // Deliver LOCKED_BOOT_COMPLETED first
14061            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14062                    .setPackage(packageName);
14063            if (includeStopped) {
14064                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14065            }
14066            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14067            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14068                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14069
14070            // Deliver BOOT_COMPLETED only if user is unlocked
14071            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14072                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14073                if (includeStopped) {
14074                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14075                }
14076                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14077                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14078            }
14079        } catch (RemoteException e) {
14080            throw e.rethrowFromSystemServer();
14081        }
14082    }
14083
14084    @Override
14085    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14086            int userId) {
14087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14088        PackageSetting pkgSetting;
14089        final int callingUid = Binder.getCallingUid();
14090        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14091                true /* requireFullPermission */, true /* checkShell */,
14092                "setApplicationHiddenSetting for user " + userId);
14093
14094        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14095            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14096            return false;
14097        }
14098
14099        long callingId = Binder.clearCallingIdentity();
14100        try {
14101            boolean sendAdded = false;
14102            boolean sendRemoved = false;
14103            // writer
14104            synchronized (mPackages) {
14105                pkgSetting = mSettings.mPackages.get(packageName);
14106                if (pkgSetting == null) {
14107                    return false;
14108                }
14109                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14110                    return false;
14111                }
14112                // Do not allow "android" is being disabled
14113                if ("android".equals(packageName)) {
14114                    Slog.w(TAG, "Cannot hide package: android");
14115                    return false;
14116                }
14117                // Cannot hide static shared libs as they are considered
14118                // a part of the using app (emulating static linking). Also
14119                // static libs are installed always on internal storage.
14120                PackageParser.Package pkg = mPackages.get(packageName);
14121                if (pkg != null && pkg.staticSharedLibName != null) {
14122                    Slog.w(TAG, "Cannot hide package: " + packageName
14123                            + " providing static shared library: "
14124                            + pkg.staticSharedLibName);
14125                    return false;
14126                }
14127                // Only allow protected packages to hide themselves.
14128                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14129                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14130                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14131                    return false;
14132                }
14133
14134                if (pkgSetting.getHidden(userId) != hidden) {
14135                    pkgSetting.setHidden(hidden, userId);
14136                    mSettings.writePackageRestrictionsLPr(userId);
14137                    if (hidden) {
14138                        sendRemoved = true;
14139                    } else {
14140                        sendAdded = true;
14141                    }
14142                }
14143            }
14144            if (sendAdded) {
14145                sendPackageAddedForUser(packageName, pkgSetting, userId);
14146                return true;
14147            }
14148            if (sendRemoved) {
14149                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14150                        "hiding pkg");
14151                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14152                return true;
14153            }
14154        } finally {
14155            Binder.restoreCallingIdentity(callingId);
14156        }
14157        return false;
14158    }
14159
14160    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14161            int userId) {
14162        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14163        info.removedPackage = packageName;
14164        info.installerPackageName = pkgSetting.installerPackageName;
14165        info.removedUsers = new int[] {userId};
14166        info.broadcastUsers = new int[] {userId};
14167        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14168        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14169    }
14170
14171    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14172        if (pkgList.length > 0) {
14173            Bundle extras = new Bundle(1);
14174            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14175
14176            sendPackageBroadcast(
14177                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14178                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14179                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14180                    new int[] {userId});
14181        }
14182    }
14183
14184    /**
14185     * Returns true if application is not found or there was an error. Otherwise it returns
14186     * the hidden state of the package for the given user.
14187     */
14188    @Override
14189    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14190        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14191        final int callingUid = Binder.getCallingUid();
14192        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14193                true /* requireFullPermission */, false /* checkShell */,
14194                "getApplicationHidden for user " + userId);
14195        PackageSetting ps;
14196        long callingId = Binder.clearCallingIdentity();
14197        try {
14198            // writer
14199            synchronized (mPackages) {
14200                ps = mSettings.mPackages.get(packageName);
14201                if (ps == null) {
14202                    return true;
14203                }
14204                if (filterAppAccessLPr(ps, callingUid, userId)) {
14205                    return true;
14206                }
14207                return ps.getHidden(userId);
14208            }
14209        } finally {
14210            Binder.restoreCallingIdentity(callingId);
14211        }
14212    }
14213
14214    /**
14215     * @hide
14216     */
14217    @Override
14218    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14219            int installReason) {
14220        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14221                null);
14222        PackageSetting pkgSetting;
14223        final int callingUid = Binder.getCallingUid();
14224        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14225                true /* requireFullPermission */, true /* checkShell */,
14226                "installExistingPackage for user " + userId);
14227        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14228            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14229        }
14230
14231        long callingId = Binder.clearCallingIdentity();
14232        try {
14233            boolean installed = false;
14234            final boolean instantApp =
14235                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14236            final boolean fullApp =
14237                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14238
14239            // writer
14240            synchronized (mPackages) {
14241                pkgSetting = mSettings.mPackages.get(packageName);
14242                if (pkgSetting == null) {
14243                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14244                }
14245                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14246                    // only allow the existing package to be used if it's installed as a full
14247                    // application for at least one user
14248                    boolean installAllowed = false;
14249                    for (int checkUserId : sUserManager.getUserIds()) {
14250                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14251                        if (installAllowed) {
14252                            break;
14253                        }
14254                    }
14255                    if (!installAllowed) {
14256                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14257                    }
14258                }
14259                if (!pkgSetting.getInstalled(userId)) {
14260                    pkgSetting.setInstalled(true, userId);
14261                    pkgSetting.setHidden(false, userId);
14262                    pkgSetting.setInstallReason(installReason, userId);
14263                    mSettings.writePackageRestrictionsLPr(userId);
14264                    mSettings.writeKernelMappingLPr(pkgSetting);
14265                    installed = true;
14266                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14267                    // upgrade app from instant to full; we don't allow app downgrade
14268                    installed = true;
14269                }
14270                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14271            }
14272
14273            if (installed) {
14274                if (pkgSetting.pkg != null) {
14275                    synchronized (mInstallLock) {
14276                        // We don't need to freeze for a brand new install
14277                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14278                    }
14279                }
14280                sendPackageAddedForUser(packageName, pkgSetting, userId);
14281                synchronized (mPackages) {
14282                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14283                }
14284            }
14285        } finally {
14286            Binder.restoreCallingIdentity(callingId);
14287        }
14288
14289        return PackageManager.INSTALL_SUCCEEDED;
14290    }
14291
14292    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14293            boolean instantApp, boolean fullApp) {
14294        // no state specified; do nothing
14295        if (!instantApp && !fullApp) {
14296            return;
14297        }
14298        if (userId != UserHandle.USER_ALL) {
14299            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14300                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14301            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14302                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14303            }
14304        } else {
14305            for (int currentUserId : sUserManager.getUserIds()) {
14306                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14307                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14308                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14309                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14310                }
14311            }
14312        }
14313    }
14314
14315    boolean isUserRestricted(int userId, String restrictionKey) {
14316        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14317        if (restrictions.getBoolean(restrictionKey, false)) {
14318            Log.w(TAG, "User is restricted: " + restrictionKey);
14319            return true;
14320        }
14321        return false;
14322    }
14323
14324    @Override
14325    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14326            int userId) {
14327        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14328        final int callingUid = Binder.getCallingUid();
14329        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14330                true /* requireFullPermission */, true /* checkShell */,
14331                "setPackagesSuspended for user " + userId);
14332
14333        if (ArrayUtils.isEmpty(packageNames)) {
14334            return packageNames;
14335        }
14336
14337        // List of package names for whom the suspended state has changed.
14338        List<String> changedPackages = new ArrayList<>(packageNames.length);
14339        // List of package names for whom the suspended state is not set as requested in this
14340        // method.
14341        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14342        long callingId = Binder.clearCallingIdentity();
14343        try {
14344            for (int i = 0; i < packageNames.length; i++) {
14345                String packageName = packageNames[i];
14346                boolean changed = false;
14347                final int appId;
14348                synchronized (mPackages) {
14349                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14350                    if (pkgSetting == null
14351                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14352                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14353                                + "\". Skipping suspending/un-suspending.");
14354                        unactionedPackages.add(packageName);
14355                        continue;
14356                    }
14357                    appId = pkgSetting.appId;
14358                    if (pkgSetting.getSuspended(userId) != suspended) {
14359                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14360                            unactionedPackages.add(packageName);
14361                            continue;
14362                        }
14363                        pkgSetting.setSuspended(suspended, userId);
14364                        mSettings.writePackageRestrictionsLPr(userId);
14365                        changed = true;
14366                        changedPackages.add(packageName);
14367                    }
14368                }
14369
14370                if (changed && suspended) {
14371                    killApplication(packageName, UserHandle.getUid(userId, appId),
14372                            "suspending package");
14373                }
14374            }
14375        } finally {
14376            Binder.restoreCallingIdentity(callingId);
14377        }
14378
14379        if (!changedPackages.isEmpty()) {
14380            sendPackagesSuspendedForUser(changedPackages.toArray(
14381                    new String[changedPackages.size()]), userId, suspended);
14382        }
14383
14384        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14385    }
14386
14387    @Override
14388    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14389        final int callingUid = Binder.getCallingUid();
14390        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14391                true /* requireFullPermission */, false /* checkShell */,
14392                "isPackageSuspendedForUser for user " + userId);
14393        synchronized (mPackages) {
14394            final PackageSetting ps = mSettings.mPackages.get(packageName);
14395            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14396                throw new IllegalArgumentException("Unknown target package: " + packageName);
14397            }
14398            return ps.getSuspended(userId);
14399        }
14400    }
14401
14402    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14403        if (isPackageDeviceAdmin(packageName, userId)) {
14404            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14405                    + "\": has an active device admin");
14406            return false;
14407        }
14408
14409        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14410        if (packageName.equals(activeLauncherPackageName)) {
14411            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14412                    + "\": contains the active launcher");
14413            return false;
14414        }
14415
14416        if (packageName.equals(mRequiredInstallerPackage)) {
14417            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14418                    + "\": required for package installation");
14419            return false;
14420        }
14421
14422        if (packageName.equals(mRequiredUninstallerPackage)) {
14423            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14424                    + "\": required for package uninstallation");
14425            return false;
14426        }
14427
14428        if (packageName.equals(mRequiredVerifierPackage)) {
14429            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14430                    + "\": required for package verification");
14431            return false;
14432        }
14433
14434        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14435            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14436                    + "\": is the default dialer");
14437            return false;
14438        }
14439
14440        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14441            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14442                    + "\": protected package");
14443            return false;
14444        }
14445
14446        // Cannot suspend static shared libs as they are considered
14447        // a part of the using app (emulating static linking). Also
14448        // static libs are installed always on internal storage.
14449        PackageParser.Package pkg = mPackages.get(packageName);
14450        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14451            Slog.w(TAG, "Cannot suspend package: " + packageName
14452                    + " providing static shared library: "
14453                    + pkg.staticSharedLibName);
14454            return false;
14455        }
14456
14457        return true;
14458    }
14459
14460    private String getActiveLauncherPackageName(int userId) {
14461        Intent intent = new Intent(Intent.ACTION_MAIN);
14462        intent.addCategory(Intent.CATEGORY_HOME);
14463        ResolveInfo resolveInfo = resolveIntent(
14464                intent,
14465                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14466                PackageManager.MATCH_DEFAULT_ONLY,
14467                userId);
14468
14469        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14470    }
14471
14472    private String getDefaultDialerPackageName(int userId) {
14473        synchronized (mPackages) {
14474            return mSettings.getDefaultDialerPackageNameLPw(userId);
14475        }
14476    }
14477
14478    @Override
14479    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14480        mContext.enforceCallingOrSelfPermission(
14481                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14482                "Only package verification agents can verify applications");
14483
14484        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14485        final PackageVerificationResponse response = new PackageVerificationResponse(
14486                verificationCode, Binder.getCallingUid());
14487        msg.arg1 = id;
14488        msg.obj = response;
14489        mHandler.sendMessage(msg);
14490    }
14491
14492    @Override
14493    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14494            long millisecondsToDelay) {
14495        mContext.enforceCallingOrSelfPermission(
14496                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14497                "Only package verification agents can extend verification timeouts");
14498
14499        final PackageVerificationState state = mPendingVerification.get(id);
14500        final PackageVerificationResponse response = new PackageVerificationResponse(
14501                verificationCodeAtTimeout, Binder.getCallingUid());
14502
14503        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14504            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14505        }
14506        if (millisecondsToDelay < 0) {
14507            millisecondsToDelay = 0;
14508        }
14509        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14510                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14511            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14512        }
14513
14514        if ((state != null) && !state.timeoutExtended()) {
14515            state.extendTimeout();
14516
14517            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14518            msg.arg1 = id;
14519            msg.obj = response;
14520            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14521        }
14522    }
14523
14524    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14525            int verificationCode, UserHandle user) {
14526        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14527        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14528        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14529        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14530        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14531
14532        mContext.sendBroadcastAsUser(intent, user,
14533                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14534    }
14535
14536    private ComponentName matchComponentForVerifier(String packageName,
14537            List<ResolveInfo> receivers) {
14538        ActivityInfo targetReceiver = null;
14539
14540        final int NR = receivers.size();
14541        for (int i = 0; i < NR; i++) {
14542            final ResolveInfo info = receivers.get(i);
14543            if (info.activityInfo == null) {
14544                continue;
14545            }
14546
14547            if (packageName.equals(info.activityInfo.packageName)) {
14548                targetReceiver = info.activityInfo;
14549                break;
14550            }
14551        }
14552
14553        if (targetReceiver == null) {
14554            return null;
14555        }
14556
14557        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14558    }
14559
14560    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14561            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14562        if (pkgInfo.verifiers.length == 0) {
14563            return null;
14564        }
14565
14566        final int N = pkgInfo.verifiers.length;
14567        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14568        for (int i = 0; i < N; i++) {
14569            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14570
14571            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14572                    receivers);
14573            if (comp == null) {
14574                continue;
14575            }
14576
14577            final int verifierUid = getUidForVerifier(verifierInfo);
14578            if (verifierUid == -1) {
14579                continue;
14580            }
14581
14582            if (DEBUG_VERIFY) {
14583                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14584                        + " with the correct signature");
14585            }
14586            sufficientVerifiers.add(comp);
14587            verificationState.addSufficientVerifier(verifierUid);
14588        }
14589
14590        return sufficientVerifiers;
14591    }
14592
14593    private int getUidForVerifier(VerifierInfo verifierInfo) {
14594        synchronized (mPackages) {
14595            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14596            if (pkg == null) {
14597                return -1;
14598            } else if (pkg.mSignatures.length != 1) {
14599                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14600                        + " has more than one signature; ignoring");
14601                return -1;
14602            }
14603
14604            /*
14605             * If the public key of the package's signature does not match
14606             * our expected public key, then this is a different package and
14607             * we should skip.
14608             */
14609
14610            final byte[] expectedPublicKey;
14611            try {
14612                final Signature verifierSig = pkg.mSignatures[0];
14613                final PublicKey publicKey = verifierSig.getPublicKey();
14614                expectedPublicKey = publicKey.getEncoded();
14615            } catch (CertificateException e) {
14616                return -1;
14617            }
14618
14619            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14620
14621            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14622                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14623                        + " does not have the expected public key; ignoring");
14624                return -1;
14625            }
14626
14627            return pkg.applicationInfo.uid;
14628        }
14629    }
14630
14631    @Override
14632    public void finishPackageInstall(int token, boolean didLaunch) {
14633        enforceSystemOrRoot("Only the system is allowed to finish installs");
14634
14635        if (DEBUG_INSTALL) {
14636            Slog.v(TAG, "BM finishing package install for " + token);
14637        }
14638        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14639
14640        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14641        mHandler.sendMessage(msg);
14642    }
14643
14644    /**
14645     * Get the verification agent timeout.  Used for both the APK verifier and the
14646     * intent filter verifier.
14647     *
14648     * @return verification timeout in milliseconds
14649     */
14650    private long getVerificationTimeout() {
14651        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14652                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14653                DEFAULT_VERIFICATION_TIMEOUT);
14654    }
14655
14656    /**
14657     * Get the default verification agent response code.
14658     *
14659     * @return default verification response code
14660     */
14661    private int getDefaultVerificationResponse(UserHandle user) {
14662        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14663            return PackageManager.VERIFICATION_REJECT;
14664        }
14665        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14666                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14667                DEFAULT_VERIFICATION_RESPONSE);
14668    }
14669
14670    /**
14671     * Check whether or not package verification has been enabled.
14672     *
14673     * @return true if verification should be performed
14674     */
14675    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14676        if (!DEFAULT_VERIFY_ENABLE) {
14677            return false;
14678        }
14679
14680        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14681
14682        // Check if installing from ADB
14683        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14684            // Do not run verification in a test harness environment
14685            if (ActivityManager.isRunningInTestHarness()) {
14686                return false;
14687            }
14688            if (ensureVerifyAppsEnabled) {
14689                return true;
14690            }
14691            // Check if the developer does not want package verification for ADB installs
14692            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14693                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14694                return false;
14695            }
14696        } else {
14697            // only when not installed from ADB, skip verification for instant apps when
14698            // the installer and verifier are the same.
14699            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14700                if (mInstantAppInstallerActivity != null
14701                        && mInstantAppInstallerActivity.packageName.equals(
14702                                mRequiredVerifierPackage)) {
14703                    try {
14704                        mContext.getSystemService(AppOpsManager.class)
14705                                .checkPackage(installerUid, mRequiredVerifierPackage);
14706                        if (DEBUG_VERIFY) {
14707                            Slog.i(TAG, "disable verification for instant app");
14708                        }
14709                        return false;
14710                    } catch (SecurityException ignore) { }
14711                }
14712            }
14713        }
14714
14715        if (ensureVerifyAppsEnabled) {
14716            return true;
14717        }
14718
14719        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14720                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14721    }
14722
14723    @Override
14724    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14725            throws RemoteException {
14726        mContext.enforceCallingOrSelfPermission(
14727                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14728                "Only intentfilter verification agents can verify applications");
14729
14730        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14731        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14732                Binder.getCallingUid(), verificationCode, failedDomains);
14733        msg.arg1 = id;
14734        msg.obj = response;
14735        mHandler.sendMessage(msg);
14736    }
14737
14738    @Override
14739    public int getIntentVerificationStatus(String packageName, int userId) {
14740        final int callingUid = Binder.getCallingUid();
14741        if (UserHandle.getUserId(callingUid) != userId) {
14742            mContext.enforceCallingOrSelfPermission(
14743                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14744                    "getIntentVerificationStatus" + userId);
14745        }
14746        if (getInstantAppPackageName(callingUid) != null) {
14747            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14748        }
14749        synchronized (mPackages) {
14750            final PackageSetting ps = mSettings.mPackages.get(packageName);
14751            if (ps == null
14752                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14753                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14754            }
14755            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14756        }
14757    }
14758
14759    @Override
14760    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14761        mContext.enforceCallingOrSelfPermission(
14762                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14763
14764        boolean result = false;
14765        synchronized (mPackages) {
14766            final PackageSetting ps = mSettings.mPackages.get(packageName);
14767            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14768                return false;
14769            }
14770            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14771        }
14772        if (result) {
14773            scheduleWritePackageRestrictionsLocked(userId);
14774        }
14775        return result;
14776    }
14777
14778    @Override
14779    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14780            String packageName) {
14781        final int callingUid = Binder.getCallingUid();
14782        if (getInstantAppPackageName(callingUid) != null) {
14783            return ParceledListSlice.emptyList();
14784        }
14785        synchronized (mPackages) {
14786            final PackageSetting ps = mSettings.mPackages.get(packageName);
14787            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14788                return ParceledListSlice.emptyList();
14789            }
14790            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14791        }
14792    }
14793
14794    @Override
14795    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14796        if (TextUtils.isEmpty(packageName)) {
14797            return ParceledListSlice.emptyList();
14798        }
14799        final int callingUid = Binder.getCallingUid();
14800        final int callingUserId = UserHandle.getUserId(callingUid);
14801        synchronized (mPackages) {
14802            PackageParser.Package pkg = mPackages.get(packageName);
14803            if (pkg == null || pkg.activities == null) {
14804                return ParceledListSlice.emptyList();
14805            }
14806            if (pkg.mExtras == null) {
14807                return ParceledListSlice.emptyList();
14808            }
14809            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14810            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14811                return ParceledListSlice.emptyList();
14812            }
14813            final int count = pkg.activities.size();
14814            ArrayList<IntentFilter> result = new ArrayList<>();
14815            for (int n=0; n<count; n++) {
14816                PackageParser.Activity activity = pkg.activities.get(n);
14817                if (activity.intents != null && activity.intents.size() > 0) {
14818                    result.addAll(activity.intents);
14819                }
14820            }
14821            return new ParceledListSlice<>(result);
14822        }
14823    }
14824
14825    @Override
14826    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14827        mContext.enforceCallingOrSelfPermission(
14828                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14829        if (UserHandle.getCallingUserId() != userId) {
14830            mContext.enforceCallingOrSelfPermission(
14831                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14832        }
14833
14834        synchronized (mPackages) {
14835            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14836            if (packageName != null) {
14837                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14838                        packageName, userId);
14839            }
14840            return result;
14841        }
14842    }
14843
14844    @Override
14845    public String getDefaultBrowserPackageName(int userId) {
14846        if (UserHandle.getCallingUserId() != userId) {
14847            mContext.enforceCallingOrSelfPermission(
14848                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14849        }
14850        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14851            return null;
14852        }
14853        synchronized (mPackages) {
14854            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14855        }
14856    }
14857
14858    /**
14859     * Get the "allow unknown sources" setting.
14860     *
14861     * @return the current "allow unknown sources" setting
14862     */
14863    private int getUnknownSourcesSettings() {
14864        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14865                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14866                -1);
14867    }
14868
14869    @Override
14870    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14871        final int callingUid = Binder.getCallingUid();
14872        if (getInstantAppPackageName(callingUid) != null) {
14873            return;
14874        }
14875        // writer
14876        synchronized (mPackages) {
14877            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14878            if (targetPackageSetting == null
14879                    || filterAppAccessLPr(
14880                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14881                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14882            }
14883
14884            PackageSetting installerPackageSetting;
14885            if (installerPackageName != null) {
14886                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14887                if (installerPackageSetting == null) {
14888                    throw new IllegalArgumentException("Unknown installer package: "
14889                            + installerPackageName);
14890                }
14891            } else {
14892                installerPackageSetting = null;
14893            }
14894
14895            Signature[] callerSignature;
14896            Object obj = mSettings.getUserIdLPr(callingUid);
14897            if (obj != null) {
14898                if (obj instanceof SharedUserSetting) {
14899                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14900                } else if (obj instanceof PackageSetting) {
14901                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14902                } else {
14903                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14904                }
14905            } else {
14906                throw new SecurityException("Unknown calling UID: " + callingUid);
14907            }
14908
14909            // Verify: can't set installerPackageName to a package that is
14910            // not signed with the same cert as the caller.
14911            if (installerPackageSetting != null) {
14912                if (compareSignatures(callerSignature,
14913                        installerPackageSetting.signatures.mSignatures)
14914                        != PackageManager.SIGNATURE_MATCH) {
14915                    throw new SecurityException(
14916                            "Caller does not have same cert as new installer package "
14917                            + installerPackageName);
14918                }
14919            }
14920
14921            // Verify: if target already has an installer package, it must
14922            // be signed with the same cert as the caller.
14923            if (targetPackageSetting.installerPackageName != null) {
14924                PackageSetting setting = mSettings.mPackages.get(
14925                        targetPackageSetting.installerPackageName);
14926                // If the currently set package isn't valid, then it's always
14927                // okay to change it.
14928                if (setting != null) {
14929                    if (compareSignatures(callerSignature,
14930                            setting.signatures.mSignatures)
14931                            != PackageManager.SIGNATURE_MATCH) {
14932                        throw new SecurityException(
14933                                "Caller does not have same cert as old installer package "
14934                                + targetPackageSetting.installerPackageName);
14935                    }
14936                }
14937            }
14938
14939            // Okay!
14940            targetPackageSetting.installerPackageName = installerPackageName;
14941            if (installerPackageName != null) {
14942                mSettings.mInstallerPackages.add(installerPackageName);
14943            }
14944            scheduleWriteSettingsLocked();
14945        }
14946    }
14947
14948    @Override
14949    public void setApplicationCategoryHint(String packageName, int categoryHint,
14950            String callerPackageName) {
14951        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14952            throw new SecurityException("Instant applications don't have access to this method");
14953        }
14954        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14955                callerPackageName);
14956        synchronized (mPackages) {
14957            PackageSetting ps = mSettings.mPackages.get(packageName);
14958            if (ps == null) {
14959                throw new IllegalArgumentException("Unknown target package " + packageName);
14960            }
14961            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14962                throw new IllegalArgumentException("Unknown target package " + packageName);
14963            }
14964            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14965                throw new IllegalArgumentException("Calling package " + callerPackageName
14966                        + " is not installer for " + packageName);
14967            }
14968
14969            if (ps.categoryHint != categoryHint) {
14970                ps.categoryHint = categoryHint;
14971                scheduleWriteSettingsLocked();
14972            }
14973        }
14974    }
14975
14976    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14977        // Queue up an async operation since the package installation may take a little while.
14978        mHandler.post(new Runnable() {
14979            public void run() {
14980                mHandler.removeCallbacks(this);
14981                 // Result object to be returned
14982                PackageInstalledInfo res = new PackageInstalledInfo();
14983                res.setReturnCode(currentStatus);
14984                res.uid = -1;
14985                res.pkg = null;
14986                res.removedInfo = null;
14987                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14988                    args.doPreInstall(res.returnCode);
14989                    synchronized (mInstallLock) {
14990                        installPackageTracedLI(args, res);
14991                    }
14992                    args.doPostInstall(res.returnCode, res.uid);
14993                }
14994
14995                // A restore should be performed at this point if (a) the install
14996                // succeeded, (b) the operation is not an update, and (c) the new
14997                // package has not opted out of backup participation.
14998                final boolean update = res.removedInfo != null
14999                        && res.removedInfo.removedPackage != null;
15000                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15001                boolean doRestore = !update
15002                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15003
15004                // Set up the post-install work request bookkeeping.  This will be used
15005                // and cleaned up by the post-install event handling regardless of whether
15006                // there's a restore pass performed.  Token values are >= 1.
15007                int token;
15008                if (mNextInstallToken < 0) mNextInstallToken = 1;
15009                token = mNextInstallToken++;
15010
15011                PostInstallData data = new PostInstallData(args, res);
15012                mRunningInstalls.put(token, data);
15013                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15014
15015                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15016                    // Pass responsibility to the Backup Manager.  It will perform a
15017                    // restore if appropriate, then pass responsibility back to the
15018                    // Package Manager to run the post-install observer callbacks
15019                    // and broadcasts.
15020                    IBackupManager bm = IBackupManager.Stub.asInterface(
15021                            ServiceManager.getService(Context.BACKUP_SERVICE));
15022                    if (bm != null) {
15023                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15024                                + " to BM for possible restore");
15025                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15026                        try {
15027                            // TODO: http://b/22388012
15028                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15029                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15030                            } else {
15031                                doRestore = false;
15032                            }
15033                        } catch (RemoteException e) {
15034                            // can't happen; the backup manager is local
15035                        } catch (Exception e) {
15036                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15037                            doRestore = false;
15038                        }
15039                    } else {
15040                        Slog.e(TAG, "Backup Manager not found!");
15041                        doRestore = false;
15042                    }
15043                }
15044
15045                if (!doRestore) {
15046                    // No restore possible, or the Backup Manager was mysteriously not
15047                    // available -- just fire the post-install work request directly.
15048                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15049
15050                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15051
15052                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15053                    mHandler.sendMessage(msg);
15054                }
15055            }
15056        });
15057    }
15058
15059    /**
15060     * Callback from PackageSettings whenever an app is first transitioned out of the
15061     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15062     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15063     * here whether the app is the target of an ongoing install, and only send the
15064     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15065     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15066     * handling.
15067     */
15068    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15069        // Serialize this with the rest of the install-process message chain.  In the
15070        // restore-at-install case, this Runnable will necessarily run before the
15071        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15072        // are coherent.  In the non-restore case, the app has already completed install
15073        // and been launched through some other means, so it is not in a problematic
15074        // state for observers to see the FIRST_LAUNCH signal.
15075        mHandler.post(new Runnable() {
15076            @Override
15077            public void run() {
15078                for (int i = 0; i < mRunningInstalls.size(); i++) {
15079                    final PostInstallData data = mRunningInstalls.valueAt(i);
15080                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15081                        continue;
15082                    }
15083                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15084                        // right package; but is it for the right user?
15085                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15086                            if (userId == data.res.newUsers[uIndex]) {
15087                                if (DEBUG_BACKUP) {
15088                                    Slog.i(TAG, "Package " + pkgName
15089                                            + " being restored so deferring FIRST_LAUNCH");
15090                                }
15091                                return;
15092                            }
15093                        }
15094                    }
15095                }
15096                // didn't find it, so not being restored
15097                if (DEBUG_BACKUP) {
15098                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15099                }
15100                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15101            }
15102        });
15103    }
15104
15105    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15106        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15107                installerPkg, null, userIds);
15108    }
15109
15110    private abstract class HandlerParams {
15111        private static final int MAX_RETRIES = 4;
15112
15113        /**
15114         * Number of times startCopy() has been attempted and had a non-fatal
15115         * error.
15116         */
15117        private int mRetries = 0;
15118
15119        /** User handle for the user requesting the information or installation. */
15120        private final UserHandle mUser;
15121        String traceMethod;
15122        int traceCookie;
15123
15124        HandlerParams(UserHandle user) {
15125            mUser = user;
15126        }
15127
15128        UserHandle getUser() {
15129            return mUser;
15130        }
15131
15132        HandlerParams setTraceMethod(String traceMethod) {
15133            this.traceMethod = traceMethod;
15134            return this;
15135        }
15136
15137        HandlerParams setTraceCookie(int traceCookie) {
15138            this.traceCookie = traceCookie;
15139            return this;
15140        }
15141
15142        final boolean startCopy() {
15143            boolean res;
15144            try {
15145                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15146
15147                if (++mRetries > MAX_RETRIES) {
15148                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15149                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15150                    handleServiceError();
15151                    return false;
15152                } else {
15153                    handleStartCopy();
15154                    res = true;
15155                }
15156            } catch (RemoteException e) {
15157                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15158                mHandler.sendEmptyMessage(MCS_RECONNECT);
15159                res = false;
15160            }
15161            handleReturnCode();
15162            return res;
15163        }
15164
15165        final void serviceError() {
15166            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15167            handleServiceError();
15168            handleReturnCode();
15169        }
15170
15171        abstract void handleStartCopy() throws RemoteException;
15172        abstract void handleServiceError();
15173        abstract void handleReturnCode();
15174    }
15175
15176    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15177        for (File path : paths) {
15178            try {
15179                mcs.clearDirectory(path.getAbsolutePath());
15180            } catch (RemoteException e) {
15181            }
15182        }
15183    }
15184
15185    static class OriginInfo {
15186        /**
15187         * Location where install is coming from, before it has been
15188         * copied/renamed into place. This could be a single monolithic APK
15189         * file, or a cluster directory. This location may be untrusted.
15190         */
15191        final File file;
15192
15193        /**
15194         * Flag indicating that {@link #file} or {@link #cid} has already been
15195         * staged, meaning downstream users don't need to defensively copy the
15196         * contents.
15197         */
15198        final boolean staged;
15199
15200        /**
15201         * Flag indicating that {@link #file} or {@link #cid} is an already
15202         * installed app that is being moved.
15203         */
15204        final boolean existing;
15205
15206        final String resolvedPath;
15207        final File resolvedFile;
15208
15209        static OriginInfo fromNothing() {
15210            return new OriginInfo(null, false, false);
15211        }
15212
15213        static OriginInfo fromUntrustedFile(File file) {
15214            return new OriginInfo(file, false, false);
15215        }
15216
15217        static OriginInfo fromExistingFile(File file) {
15218            return new OriginInfo(file, false, true);
15219        }
15220
15221        static OriginInfo fromStagedFile(File file) {
15222            return new OriginInfo(file, true, false);
15223        }
15224
15225        private OriginInfo(File file, boolean staged, boolean existing) {
15226            this.file = file;
15227            this.staged = staged;
15228            this.existing = existing;
15229
15230            if (file != null) {
15231                resolvedPath = file.getAbsolutePath();
15232                resolvedFile = file;
15233            } else {
15234                resolvedPath = null;
15235                resolvedFile = null;
15236            }
15237        }
15238    }
15239
15240    static class MoveInfo {
15241        final int moveId;
15242        final String fromUuid;
15243        final String toUuid;
15244        final String packageName;
15245        final String dataAppName;
15246        final int appId;
15247        final String seinfo;
15248        final int targetSdkVersion;
15249
15250        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15251                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15252            this.moveId = moveId;
15253            this.fromUuid = fromUuid;
15254            this.toUuid = toUuid;
15255            this.packageName = packageName;
15256            this.dataAppName = dataAppName;
15257            this.appId = appId;
15258            this.seinfo = seinfo;
15259            this.targetSdkVersion = targetSdkVersion;
15260        }
15261    }
15262
15263    static class VerificationInfo {
15264        /** A constant used to indicate that a uid value is not present. */
15265        public static final int NO_UID = -1;
15266
15267        /** URI referencing where the package was downloaded from. */
15268        final Uri originatingUri;
15269
15270        /** HTTP referrer URI associated with the originatingURI. */
15271        final Uri referrer;
15272
15273        /** UID of the application that the install request originated from. */
15274        final int originatingUid;
15275
15276        /** UID of application requesting the install */
15277        final int installerUid;
15278
15279        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15280            this.originatingUri = originatingUri;
15281            this.referrer = referrer;
15282            this.originatingUid = originatingUid;
15283            this.installerUid = installerUid;
15284        }
15285    }
15286
15287    class InstallParams extends HandlerParams {
15288        final OriginInfo origin;
15289        final MoveInfo move;
15290        final IPackageInstallObserver2 observer;
15291        int installFlags;
15292        final String installerPackageName;
15293        final String volumeUuid;
15294        private InstallArgs mArgs;
15295        private int mRet;
15296        final String packageAbiOverride;
15297        final String[] grantedRuntimePermissions;
15298        final VerificationInfo verificationInfo;
15299        final Certificate[][] certificates;
15300        final int installReason;
15301
15302        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15303                int installFlags, String installerPackageName, String volumeUuid,
15304                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15305                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15306            super(user);
15307            this.origin = origin;
15308            this.move = move;
15309            this.observer = observer;
15310            this.installFlags = installFlags;
15311            this.installerPackageName = installerPackageName;
15312            this.volumeUuid = volumeUuid;
15313            this.verificationInfo = verificationInfo;
15314            this.packageAbiOverride = packageAbiOverride;
15315            this.grantedRuntimePermissions = grantedPermissions;
15316            this.certificates = certificates;
15317            this.installReason = installReason;
15318        }
15319
15320        @Override
15321        public String toString() {
15322            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15323                    + " file=" + origin.file + "}";
15324        }
15325
15326        private int installLocationPolicy(PackageInfoLite pkgLite) {
15327            String packageName = pkgLite.packageName;
15328            int installLocation = pkgLite.installLocation;
15329            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15330            // reader
15331            synchronized (mPackages) {
15332                // Currently installed package which the new package is attempting to replace or
15333                // null if no such package is installed.
15334                PackageParser.Package installedPkg = mPackages.get(packageName);
15335                // Package which currently owns the data which the new package will own if installed.
15336                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15337                // will be null whereas dataOwnerPkg will contain information about the package
15338                // which was uninstalled while keeping its data.
15339                PackageParser.Package dataOwnerPkg = installedPkg;
15340                if (dataOwnerPkg  == null) {
15341                    PackageSetting ps = mSettings.mPackages.get(packageName);
15342                    if (ps != null) {
15343                        dataOwnerPkg = ps.pkg;
15344                    }
15345                }
15346
15347                if (dataOwnerPkg != null) {
15348                    // If installed, the package will get access to data left on the device by its
15349                    // predecessor. As a security measure, this is permited only if this is not a
15350                    // version downgrade or if the predecessor package is marked as debuggable and
15351                    // a downgrade is explicitly requested.
15352                    //
15353                    // On debuggable platform builds, downgrades are permitted even for
15354                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15355                    // not offer security guarantees and thus it's OK to disable some security
15356                    // mechanisms to make debugging/testing easier on those builds. However, even on
15357                    // debuggable builds downgrades of packages are permitted only if requested via
15358                    // installFlags. This is because we aim to keep the behavior of debuggable
15359                    // platform builds as close as possible to the behavior of non-debuggable
15360                    // platform builds.
15361                    final boolean downgradeRequested =
15362                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15363                    final boolean packageDebuggable =
15364                                (dataOwnerPkg.applicationInfo.flags
15365                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15366                    final boolean downgradePermitted =
15367                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15368                    if (!downgradePermitted) {
15369                        try {
15370                            checkDowngrade(dataOwnerPkg, pkgLite);
15371                        } catch (PackageManagerException e) {
15372                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15373                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15374                        }
15375                    }
15376                }
15377
15378                if (installedPkg != null) {
15379                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15380                        // Check for updated system application.
15381                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15382                            if (onSd) {
15383                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15384                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15385                            }
15386                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15387                        } else {
15388                            if (onSd) {
15389                                // Install flag overrides everything.
15390                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15391                            }
15392                            // If current upgrade specifies particular preference
15393                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15394                                // Application explicitly specified internal.
15395                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15396                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15397                                // App explictly prefers external. Let policy decide
15398                            } else {
15399                                // Prefer previous location
15400                                if (isExternal(installedPkg)) {
15401                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15402                                }
15403                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15404                            }
15405                        }
15406                    } else {
15407                        // Invalid install. Return error code
15408                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15409                    }
15410                }
15411            }
15412            // All the special cases have been taken care of.
15413            // Return result based on recommended install location.
15414            if (onSd) {
15415                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15416            }
15417            return pkgLite.recommendedInstallLocation;
15418        }
15419
15420        /*
15421         * Invoke remote method to get package information and install
15422         * location values. Override install location based on default
15423         * policy if needed and then create install arguments based
15424         * on the install location.
15425         */
15426        public void handleStartCopy() throws RemoteException {
15427            int ret = PackageManager.INSTALL_SUCCEEDED;
15428
15429            // If we're already staged, we've firmly committed to an install location
15430            if (origin.staged) {
15431                if (origin.file != null) {
15432                    installFlags |= PackageManager.INSTALL_INTERNAL;
15433                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15434                } else {
15435                    throw new IllegalStateException("Invalid stage location");
15436                }
15437            }
15438
15439            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15440            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15441            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15442            PackageInfoLite pkgLite = null;
15443
15444            if (onInt && onSd) {
15445                // Check if both bits are set.
15446                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15447                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15448            } else if (onSd && ephemeral) {
15449                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15450                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15451            } else {
15452                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15453                        packageAbiOverride);
15454
15455                if (DEBUG_EPHEMERAL && ephemeral) {
15456                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15457                }
15458
15459                /*
15460                 * If we have too little free space, try to free cache
15461                 * before giving up.
15462                 */
15463                if (!origin.staged && pkgLite.recommendedInstallLocation
15464                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15465                    // TODO: focus freeing disk space on the target device
15466                    final StorageManager storage = StorageManager.from(mContext);
15467                    final long lowThreshold = storage.getStorageLowBytes(
15468                            Environment.getDataDirectory());
15469
15470                    final long sizeBytes = mContainerService.calculateInstalledSize(
15471                            origin.resolvedPath, packageAbiOverride);
15472
15473                    try {
15474                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15475                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15476                                installFlags, packageAbiOverride);
15477                    } catch (InstallerException e) {
15478                        Slog.w(TAG, "Failed to free cache", e);
15479                    }
15480
15481                    /*
15482                     * The cache free must have deleted the file we
15483                     * downloaded to install.
15484                     *
15485                     * TODO: fix the "freeCache" call to not delete
15486                     *       the file we care about.
15487                     */
15488                    if (pkgLite.recommendedInstallLocation
15489                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15490                        pkgLite.recommendedInstallLocation
15491                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15492                    }
15493                }
15494            }
15495
15496            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15497                int loc = pkgLite.recommendedInstallLocation;
15498                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15499                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15500                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15501                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15502                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15503                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15504                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15505                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15506                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15507                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15508                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15509                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15510                } else {
15511                    // Override with defaults if needed.
15512                    loc = installLocationPolicy(pkgLite);
15513                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15514                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15515                    } else if (!onSd && !onInt) {
15516                        // Override install location with flags
15517                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15518                            // Set the flag to install on external media.
15519                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15520                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15521                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15522                            if (DEBUG_EPHEMERAL) {
15523                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15524                            }
15525                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15526                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15527                                    |PackageManager.INSTALL_INTERNAL);
15528                        } else {
15529                            // Make sure the flag for installing on external
15530                            // media is unset
15531                            installFlags |= PackageManager.INSTALL_INTERNAL;
15532                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15533                        }
15534                    }
15535                }
15536            }
15537
15538            final InstallArgs args = createInstallArgs(this);
15539            mArgs = args;
15540
15541            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15542                // TODO: http://b/22976637
15543                // Apps installed for "all" users use the device owner to verify the app
15544                UserHandle verifierUser = getUser();
15545                if (verifierUser == UserHandle.ALL) {
15546                    verifierUser = UserHandle.SYSTEM;
15547                }
15548
15549                /*
15550                 * Determine if we have any installed package verifiers. If we
15551                 * do, then we'll defer to them to verify the packages.
15552                 */
15553                final int requiredUid = mRequiredVerifierPackage == null ? -1
15554                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15555                                verifierUser.getIdentifier());
15556                final int installerUid =
15557                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15558                if (!origin.existing && requiredUid != -1
15559                        && isVerificationEnabled(
15560                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15561                    final Intent verification = new Intent(
15562                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15563                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15564                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15565                            PACKAGE_MIME_TYPE);
15566                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15567
15568                    // Query all live verifiers based on current user state
15569                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15570                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15571                            false /*allowDynamicSplits*/);
15572
15573                    if (DEBUG_VERIFY) {
15574                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15575                                + verification.toString() + " with " + pkgLite.verifiers.length
15576                                + " optional verifiers");
15577                    }
15578
15579                    final int verificationId = mPendingVerificationToken++;
15580
15581                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15582
15583                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15584                            installerPackageName);
15585
15586                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15587                            installFlags);
15588
15589                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15590                            pkgLite.packageName);
15591
15592                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15593                            pkgLite.versionCode);
15594
15595                    if (verificationInfo != null) {
15596                        if (verificationInfo.originatingUri != null) {
15597                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15598                                    verificationInfo.originatingUri);
15599                        }
15600                        if (verificationInfo.referrer != null) {
15601                            verification.putExtra(Intent.EXTRA_REFERRER,
15602                                    verificationInfo.referrer);
15603                        }
15604                        if (verificationInfo.originatingUid >= 0) {
15605                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15606                                    verificationInfo.originatingUid);
15607                        }
15608                        if (verificationInfo.installerUid >= 0) {
15609                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15610                                    verificationInfo.installerUid);
15611                        }
15612                    }
15613
15614                    final PackageVerificationState verificationState = new PackageVerificationState(
15615                            requiredUid, args);
15616
15617                    mPendingVerification.append(verificationId, verificationState);
15618
15619                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15620                            receivers, verificationState);
15621
15622                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15623                    final long idleDuration = getVerificationTimeout();
15624
15625                    /*
15626                     * If any sufficient verifiers were listed in the package
15627                     * manifest, attempt to ask them.
15628                     */
15629                    if (sufficientVerifiers != null) {
15630                        final int N = sufficientVerifiers.size();
15631                        if (N == 0) {
15632                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15633                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15634                        } else {
15635                            for (int i = 0; i < N; i++) {
15636                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15637                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15638                                        verifierComponent.getPackageName(), idleDuration,
15639                                        verifierUser.getIdentifier(), false, "package verifier");
15640
15641                                final Intent sufficientIntent = new Intent(verification);
15642                                sufficientIntent.setComponent(verifierComponent);
15643                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15644                            }
15645                        }
15646                    }
15647
15648                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15649                            mRequiredVerifierPackage, receivers);
15650                    if (ret == PackageManager.INSTALL_SUCCEEDED
15651                            && mRequiredVerifierPackage != null) {
15652                        Trace.asyncTraceBegin(
15653                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15654                        /*
15655                         * Send the intent to the required verification agent,
15656                         * but only start the verification timeout after the
15657                         * target BroadcastReceivers have run.
15658                         */
15659                        verification.setComponent(requiredVerifierComponent);
15660                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15661                                mRequiredVerifierPackage, idleDuration,
15662                                verifierUser.getIdentifier(), false, "package verifier");
15663                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15664                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15665                                new BroadcastReceiver() {
15666                                    @Override
15667                                    public void onReceive(Context context, Intent intent) {
15668                                        final Message msg = mHandler
15669                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15670                                        msg.arg1 = verificationId;
15671                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15672                                    }
15673                                }, null, 0, null, null);
15674
15675                        /*
15676                         * We don't want the copy to proceed until verification
15677                         * succeeds, so null out this field.
15678                         */
15679                        mArgs = null;
15680                    }
15681                } else {
15682                    /*
15683                     * No package verification is enabled, so immediately start
15684                     * the remote call to initiate copy using temporary file.
15685                     */
15686                    ret = args.copyApk(mContainerService, true);
15687                }
15688            }
15689
15690            mRet = ret;
15691        }
15692
15693        @Override
15694        void handleReturnCode() {
15695            // If mArgs is null, then MCS couldn't be reached. When it
15696            // reconnects, it will try again to install. At that point, this
15697            // will succeed.
15698            if (mArgs != null) {
15699                processPendingInstall(mArgs, mRet);
15700            }
15701        }
15702
15703        @Override
15704        void handleServiceError() {
15705            mArgs = createInstallArgs(this);
15706            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15707        }
15708    }
15709
15710    private InstallArgs createInstallArgs(InstallParams params) {
15711        if (params.move != null) {
15712            return new MoveInstallArgs(params);
15713        } else {
15714            return new FileInstallArgs(params);
15715        }
15716    }
15717
15718    /**
15719     * Create args that describe an existing installed package. Typically used
15720     * when cleaning up old installs, or used as a move source.
15721     */
15722    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15723            String resourcePath, String[] instructionSets) {
15724        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15725    }
15726
15727    static abstract class InstallArgs {
15728        /** @see InstallParams#origin */
15729        final OriginInfo origin;
15730        /** @see InstallParams#move */
15731        final MoveInfo move;
15732
15733        final IPackageInstallObserver2 observer;
15734        // Always refers to PackageManager flags only
15735        final int installFlags;
15736        final String installerPackageName;
15737        final String volumeUuid;
15738        final UserHandle user;
15739        final String abiOverride;
15740        final String[] installGrantPermissions;
15741        /** If non-null, drop an async trace when the install completes */
15742        final String traceMethod;
15743        final int traceCookie;
15744        final Certificate[][] certificates;
15745        final int installReason;
15746
15747        // The list of instruction sets supported by this app. This is currently
15748        // only used during the rmdex() phase to clean up resources. We can get rid of this
15749        // if we move dex files under the common app path.
15750        /* nullable */ String[] instructionSets;
15751
15752        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15753                int installFlags, String installerPackageName, String volumeUuid,
15754                UserHandle user, String[] instructionSets,
15755                String abiOverride, String[] installGrantPermissions,
15756                String traceMethod, int traceCookie, Certificate[][] certificates,
15757                int installReason) {
15758            this.origin = origin;
15759            this.move = move;
15760            this.installFlags = installFlags;
15761            this.observer = observer;
15762            this.installerPackageName = installerPackageName;
15763            this.volumeUuid = volumeUuid;
15764            this.user = user;
15765            this.instructionSets = instructionSets;
15766            this.abiOverride = abiOverride;
15767            this.installGrantPermissions = installGrantPermissions;
15768            this.traceMethod = traceMethod;
15769            this.traceCookie = traceCookie;
15770            this.certificates = certificates;
15771            this.installReason = installReason;
15772        }
15773
15774        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15775        abstract int doPreInstall(int status);
15776
15777        /**
15778         * Rename package into final resting place. All paths on the given
15779         * scanned package should be updated to reflect the rename.
15780         */
15781        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15782        abstract int doPostInstall(int status, int uid);
15783
15784        /** @see PackageSettingBase#codePathString */
15785        abstract String getCodePath();
15786        /** @see PackageSettingBase#resourcePathString */
15787        abstract String getResourcePath();
15788
15789        // Need installer lock especially for dex file removal.
15790        abstract void cleanUpResourcesLI();
15791        abstract boolean doPostDeleteLI(boolean delete);
15792
15793        /**
15794         * Called before the source arguments are copied. This is used mostly
15795         * for MoveParams when it needs to read the source file to put it in the
15796         * destination.
15797         */
15798        int doPreCopy() {
15799            return PackageManager.INSTALL_SUCCEEDED;
15800        }
15801
15802        /**
15803         * Called after the source arguments are copied. This is used mostly for
15804         * MoveParams when it needs to read the source file to put it in the
15805         * destination.
15806         */
15807        int doPostCopy(int uid) {
15808            return PackageManager.INSTALL_SUCCEEDED;
15809        }
15810
15811        protected boolean isFwdLocked() {
15812            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15813        }
15814
15815        protected boolean isExternalAsec() {
15816            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15817        }
15818
15819        protected boolean isEphemeral() {
15820            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15821        }
15822
15823        UserHandle getUser() {
15824            return user;
15825        }
15826    }
15827
15828    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15829        if (!allCodePaths.isEmpty()) {
15830            if (instructionSets == null) {
15831                throw new IllegalStateException("instructionSet == null");
15832            }
15833            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15834            for (String codePath : allCodePaths) {
15835                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15836                    try {
15837                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15838                    } catch (InstallerException ignored) {
15839                    }
15840                }
15841            }
15842        }
15843    }
15844
15845    /**
15846     * Logic to handle installation of non-ASEC applications, including copying
15847     * and renaming logic.
15848     */
15849    class FileInstallArgs extends InstallArgs {
15850        private File codeFile;
15851        private File resourceFile;
15852
15853        // Example topology:
15854        // /data/app/com.example/base.apk
15855        // /data/app/com.example/split_foo.apk
15856        // /data/app/com.example/lib/arm/libfoo.so
15857        // /data/app/com.example/lib/arm64/libfoo.so
15858        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15859
15860        /** New install */
15861        FileInstallArgs(InstallParams params) {
15862            super(params.origin, params.move, params.observer, params.installFlags,
15863                    params.installerPackageName, params.volumeUuid,
15864                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15865                    params.grantedRuntimePermissions,
15866                    params.traceMethod, params.traceCookie, params.certificates,
15867                    params.installReason);
15868            if (isFwdLocked()) {
15869                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15870            }
15871        }
15872
15873        /** Existing install */
15874        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15875            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15876                    null, null, null, 0, null /*certificates*/,
15877                    PackageManager.INSTALL_REASON_UNKNOWN);
15878            this.codeFile = (codePath != null) ? new File(codePath) : null;
15879            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15880        }
15881
15882        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15883            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15884            try {
15885                return doCopyApk(imcs, temp);
15886            } finally {
15887                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15888            }
15889        }
15890
15891        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15892            if (origin.staged) {
15893                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15894                codeFile = origin.file;
15895                resourceFile = origin.file;
15896                return PackageManager.INSTALL_SUCCEEDED;
15897            }
15898
15899            try {
15900                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15901                final File tempDir =
15902                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15903                codeFile = tempDir;
15904                resourceFile = tempDir;
15905            } catch (IOException e) {
15906                Slog.w(TAG, "Failed to create copy file: " + e);
15907                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15908            }
15909
15910            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15911                @Override
15912                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15913                    if (!FileUtils.isValidExtFilename(name)) {
15914                        throw new IllegalArgumentException("Invalid filename: " + name);
15915                    }
15916                    try {
15917                        final File file = new File(codeFile, name);
15918                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15919                                O_RDWR | O_CREAT, 0644);
15920                        Os.chmod(file.getAbsolutePath(), 0644);
15921                        return new ParcelFileDescriptor(fd);
15922                    } catch (ErrnoException e) {
15923                        throw new RemoteException("Failed to open: " + e.getMessage());
15924                    }
15925                }
15926            };
15927
15928            int ret = PackageManager.INSTALL_SUCCEEDED;
15929            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15930            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15931                Slog.e(TAG, "Failed to copy package");
15932                return ret;
15933            }
15934
15935            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15936            NativeLibraryHelper.Handle handle = null;
15937            try {
15938                handle = NativeLibraryHelper.Handle.create(codeFile);
15939                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15940                        abiOverride);
15941            } catch (IOException e) {
15942                Slog.e(TAG, "Copying native libraries failed", e);
15943                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15944            } finally {
15945                IoUtils.closeQuietly(handle);
15946            }
15947
15948            return ret;
15949        }
15950
15951        int doPreInstall(int status) {
15952            if (status != PackageManager.INSTALL_SUCCEEDED) {
15953                cleanUp();
15954            }
15955            return status;
15956        }
15957
15958        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15959            if (status != PackageManager.INSTALL_SUCCEEDED) {
15960                cleanUp();
15961                return false;
15962            }
15963
15964            final File targetDir = codeFile.getParentFile();
15965            final File beforeCodeFile = codeFile;
15966            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15967
15968            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15969            try {
15970                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15971            } catch (ErrnoException e) {
15972                Slog.w(TAG, "Failed to rename", e);
15973                return false;
15974            }
15975
15976            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15977                Slog.w(TAG, "Failed to restorecon");
15978                return false;
15979            }
15980
15981            // Reflect the rename internally
15982            codeFile = afterCodeFile;
15983            resourceFile = afterCodeFile;
15984
15985            // Reflect the rename in scanned details
15986            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15987            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15988                    afterCodeFile, pkg.baseCodePath));
15989            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15990                    afterCodeFile, pkg.splitCodePaths));
15991
15992            // Reflect the rename in app info
15993            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15994            pkg.setApplicationInfoCodePath(pkg.codePath);
15995            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15996            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15997            pkg.setApplicationInfoResourcePath(pkg.codePath);
15998            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15999            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16000
16001            return true;
16002        }
16003
16004        int doPostInstall(int status, int uid) {
16005            if (status != PackageManager.INSTALL_SUCCEEDED) {
16006                cleanUp();
16007            }
16008            return status;
16009        }
16010
16011        @Override
16012        String getCodePath() {
16013            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16014        }
16015
16016        @Override
16017        String getResourcePath() {
16018            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16019        }
16020
16021        private boolean cleanUp() {
16022            if (codeFile == null || !codeFile.exists()) {
16023                return false;
16024            }
16025
16026            removeCodePathLI(codeFile);
16027
16028            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16029                resourceFile.delete();
16030            }
16031
16032            return true;
16033        }
16034
16035        void cleanUpResourcesLI() {
16036            // Try enumerating all code paths before deleting
16037            List<String> allCodePaths = Collections.EMPTY_LIST;
16038            if (codeFile != null && codeFile.exists()) {
16039                try {
16040                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16041                    allCodePaths = pkg.getAllCodePaths();
16042                } catch (PackageParserException e) {
16043                    // Ignored; we tried our best
16044                }
16045            }
16046
16047            cleanUp();
16048            removeDexFiles(allCodePaths, instructionSets);
16049        }
16050
16051        boolean doPostDeleteLI(boolean delete) {
16052            // XXX err, shouldn't we respect the delete flag?
16053            cleanUpResourcesLI();
16054            return true;
16055        }
16056    }
16057
16058    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16059            PackageManagerException {
16060        if (copyRet < 0) {
16061            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16062                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16063                throw new PackageManagerException(copyRet, message);
16064            }
16065        }
16066    }
16067
16068    /**
16069     * Extract the StorageManagerService "container ID" from the full code path of an
16070     * .apk.
16071     */
16072    static String cidFromCodePath(String fullCodePath) {
16073        int eidx = fullCodePath.lastIndexOf("/");
16074        String subStr1 = fullCodePath.substring(0, eidx);
16075        int sidx = subStr1.lastIndexOf("/");
16076        return subStr1.substring(sidx+1, eidx);
16077    }
16078
16079    /**
16080     * Logic to handle movement of existing installed applications.
16081     */
16082    class MoveInstallArgs extends InstallArgs {
16083        private File codeFile;
16084        private File resourceFile;
16085
16086        /** New install */
16087        MoveInstallArgs(InstallParams params) {
16088            super(params.origin, params.move, params.observer, params.installFlags,
16089                    params.installerPackageName, params.volumeUuid,
16090                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16091                    params.grantedRuntimePermissions,
16092                    params.traceMethod, params.traceCookie, params.certificates,
16093                    params.installReason);
16094        }
16095
16096        int copyApk(IMediaContainerService imcs, boolean temp) {
16097            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16098                    + move.fromUuid + " to " + move.toUuid);
16099            synchronized (mInstaller) {
16100                try {
16101                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16102                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16103                } catch (InstallerException e) {
16104                    Slog.w(TAG, "Failed to move app", e);
16105                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16106                }
16107            }
16108
16109            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16110            resourceFile = codeFile;
16111            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16112
16113            return PackageManager.INSTALL_SUCCEEDED;
16114        }
16115
16116        int doPreInstall(int status) {
16117            if (status != PackageManager.INSTALL_SUCCEEDED) {
16118                cleanUp(move.toUuid);
16119            }
16120            return status;
16121        }
16122
16123        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16124            if (status != PackageManager.INSTALL_SUCCEEDED) {
16125                cleanUp(move.toUuid);
16126                return false;
16127            }
16128
16129            // Reflect the move in app info
16130            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16131            pkg.setApplicationInfoCodePath(pkg.codePath);
16132            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16133            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16134            pkg.setApplicationInfoResourcePath(pkg.codePath);
16135            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16136            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16137
16138            return true;
16139        }
16140
16141        int doPostInstall(int status, int uid) {
16142            if (status == PackageManager.INSTALL_SUCCEEDED) {
16143                cleanUp(move.fromUuid);
16144            } else {
16145                cleanUp(move.toUuid);
16146            }
16147            return status;
16148        }
16149
16150        @Override
16151        String getCodePath() {
16152            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16153        }
16154
16155        @Override
16156        String getResourcePath() {
16157            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16158        }
16159
16160        private boolean cleanUp(String volumeUuid) {
16161            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16162                    move.dataAppName);
16163            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16164            final int[] userIds = sUserManager.getUserIds();
16165            synchronized (mInstallLock) {
16166                // Clean up both app data and code
16167                // All package moves are frozen until finished
16168                for (int userId : userIds) {
16169                    try {
16170                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16171                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16172                    } catch (InstallerException e) {
16173                        Slog.w(TAG, String.valueOf(e));
16174                    }
16175                }
16176                removeCodePathLI(codeFile);
16177            }
16178            return true;
16179        }
16180
16181        void cleanUpResourcesLI() {
16182            throw new UnsupportedOperationException();
16183        }
16184
16185        boolean doPostDeleteLI(boolean delete) {
16186            throw new UnsupportedOperationException();
16187        }
16188    }
16189
16190    static String getAsecPackageName(String packageCid) {
16191        int idx = packageCid.lastIndexOf("-");
16192        if (idx == -1) {
16193            return packageCid;
16194        }
16195        return packageCid.substring(0, idx);
16196    }
16197
16198    // Utility method used to create code paths based on package name and available index.
16199    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16200        String idxStr = "";
16201        int idx = 1;
16202        // Fall back to default value of idx=1 if prefix is not
16203        // part of oldCodePath
16204        if (oldCodePath != null) {
16205            String subStr = oldCodePath;
16206            // Drop the suffix right away
16207            if (suffix != null && subStr.endsWith(suffix)) {
16208                subStr = subStr.substring(0, subStr.length() - suffix.length());
16209            }
16210            // If oldCodePath already contains prefix find out the
16211            // ending index to either increment or decrement.
16212            int sidx = subStr.lastIndexOf(prefix);
16213            if (sidx != -1) {
16214                subStr = subStr.substring(sidx + prefix.length());
16215                if (subStr != null) {
16216                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16217                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16218                    }
16219                    try {
16220                        idx = Integer.parseInt(subStr);
16221                        if (idx <= 1) {
16222                            idx++;
16223                        } else {
16224                            idx--;
16225                        }
16226                    } catch(NumberFormatException e) {
16227                    }
16228                }
16229            }
16230        }
16231        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16232        return prefix + idxStr;
16233    }
16234
16235    private File getNextCodePath(File targetDir, String packageName) {
16236        File result;
16237        SecureRandom random = new SecureRandom();
16238        byte[] bytes = new byte[16];
16239        do {
16240            random.nextBytes(bytes);
16241            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16242            result = new File(targetDir, packageName + "-" + suffix);
16243        } while (result.exists());
16244        return result;
16245    }
16246
16247    // Utility method that returns the relative package path with respect
16248    // to the installation directory. Like say for /data/data/com.test-1.apk
16249    // string com.test-1 is returned.
16250    static String deriveCodePathName(String codePath) {
16251        if (codePath == null) {
16252            return null;
16253        }
16254        final File codeFile = new File(codePath);
16255        final String name = codeFile.getName();
16256        if (codeFile.isDirectory()) {
16257            return name;
16258        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16259            final int lastDot = name.lastIndexOf('.');
16260            return name.substring(0, lastDot);
16261        } else {
16262            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16263            return null;
16264        }
16265    }
16266
16267    static class PackageInstalledInfo {
16268        String name;
16269        int uid;
16270        // The set of users that originally had this package installed.
16271        int[] origUsers;
16272        // The set of users that now have this package installed.
16273        int[] newUsers;
16274        PackageParser.Package pkg;
16275        int returnCode;
16276        String returnMsg;
16277        String installerPackageName;
16278        PackageRemovedInfo removedInfo;
16279        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16280
16281        public void setError(int code, String msg) {
16282            setReturnCode(code);
16283            setReturnMessage(msg);
16284            Slog.w(TAG, msg);
16285        }
16286
16287        public void setError(String msg, PackageParserException e) {
16288            setReturnCode(e.error);
16289            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16290            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16291            for (int i = 0; i < childCount; i++) {
16292                addedChildPackages.valueAt(i).setError(msg, e);
16293            }
16294            Slog.w(TAG, msg, e);
16295        }
16296
16297        public void setError(String msg, PackageManagerException e) {
16298            returnCode = e.error;
16299            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16300            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16301            for (int i = 0; i < childCount; i++) {
16302                addedChildPackages.valueAt(i).setError(msg, e);
16303            }
16304            Slog.w(TAG, msg, e);
16305        }
16306
16307        public void setReturnCode(int returnCode) {
16308            this.returnCode = returnCode;
16309            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16310            for (int i = 0; i < childCount; i++) {
16311                addedChildPackages.valueAt(i).returnCode = returnCode;
16312            }
16313        }
16314
16315        private void setReturnMessage(String returnMsg) {
16316            this.returnMsg = returnMsg;
16317            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16318            for (int i = 0; i < childCount; i++) {
16319                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16320            }
16321        }
16322
16323        // In some error cases we want to convey more info back to the observer
16324        String origPackage;
16325        String origPermission;
16326    }
16327
16328    /*
16329     * Install a non-existing package.
16330     */
16331    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16332            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16333            PackageInstalledInfo res, int installReason) {
16334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16335
16336        // Remember this for later, in case we need to rollback this install
16337        String pkgName = pkg.packageName;
16338
16339        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16340
16341        synchronized(mPackages) {
16342            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16343            if (renamedPackage != null) {
16344                // A package with the same name is already installed, though
16345                // it has been renamed to an older name.  The package we
16346                // are trying to install should be installed as an update to
16347                // the existing one, but that has not been requested, so bail.
16348                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16349                        + " without first uninstalling package running as "
16350                        + renamedPackage);
16351                return;
16352            }
16353            if (mPackages.containsKey(pkgName)) {
16354                // Don't allow installation over an existing package with the same name.
16355                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16356                        + " without first uninstalling.");
16357                return;
16358            }
16359        }
16360
16361        try {
16362            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16363                    System.currentTimeMillis(), user);
16364
16365            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16366
16367            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16368                prepareAppDataAfterInstallLIF(newPackage);
16369
16370            } else {
16371                // Remove package from internal structures, but keep around any
16372                // data that might have already existed
16373                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16374                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16375            }
16376        } catch (PackageManagerException e) {
16377            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16378        }
16379
16380        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16381    }
16382
16383    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16384        // Can't rotate keys during boot or if sharedUser.
16385        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16386                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16387            return false;
16388        }
16389        // app is using upgradeKeySets; make sure all are valid
16390        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16391        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16392        for (int i = 0; i < upgradeKeySets.length; i++) {
16393            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16394                Slog.wtf(TAG, "Package "
16395                         + (oldPs.name != null ? oldPs.name : "<null>")
16396                         + " contains upgrade-key-set reference to unknown key-set: "
16397                         + upgradeKeySets[i]
16398                         + " reverting to signatures check.");
16399                return false;
16400            }
16401        }
16402        return true;
16403    }
16404
16405    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16406        // Upgrade keysets are being used.  Determine if new package has a superset of the
16407        // required keys.
16408        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16409        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16410        for (int i = 0; i < upgradeKeySets.length; i++) {
16411            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16412            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16413                return true;
16414            }
16415        }
16416        return false;
16417    }
16418
16419    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16420        try (DigestInputStream digestStream =
16421                new DigestInputStream(new FileInputStream(file), digest)) {
16422            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16423        }
16424    }
16425
16426    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16427            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16428            int installReason) {
16429        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16430
16431        final PackageParser.Package oldPackage;
16432        final PackageSetting ps;
16433        final String pkgName = pkg.packageName;
16434        final int[] allUsers;
16435        final int[] installedUsers;
16436
16437        synchronized(mPackages) {
16438            oldPackage = mPackages.get(pkgName);
16439            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16440
16441            // don't allow upgrade to target a release SDK from a pre-release SDK
16442            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16443                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16444            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16445                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16446            if (oldTargetsPreRelease
16447                    && !newTargetsPreRelease
16448                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16449                Slog.w(TAG, "Can't install package targeting released sdk");
16450                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16451                return;
16452            }
16453
16454            ps = mSettings.mPackages.get(pkgName);
16455
16456            // verify signatures are valid
16457            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16458                if (!checkUpgradeKeySetLP(ps, pkg)) {
16459                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16460                            "New package not signed by keys specified by upgrade-keysets: "
16461                                    + pkgName);
16462                    return;
16463                }
16464            } else {
16465                // default to original signature matching
16466                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16467                        != PackageManager.SIGNATURE_MATCH) {
16468                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16469                            "New package has a different signature: " + pkgName);
16470                    return;
16471                }
16472            }
16473
16474            // don't allow a system upgrade unless the upgrade hash matches
16475            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16476                byte[] digestBytes = null;
16477                try {
16478                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16479                    updateDigest(digest, new File(pkg.baseCodePath));
16480                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16481                        for (String path : pkg.splitCodePaths) {
16482                            updateDigest(digest, new File(path));
16483                        }
16484                    }
16485                    digestBytes = digest.digest();
16486                } catch (NoSuchAlgorithmException | IOException e) {
16487                    res.setError(INSTALL_FAILED_INVALID_APK,
16488                            "Could not compute hash: " + pkgName);
16489                    return;
16490                }
16491                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16492                    res.setError(INSTALL_FAILED_INVALID_APK,
16493                            "New package fails restrict-update check: " + pkgName);
16494                    return;
16495                }
16496                // retain upgrade restriction
16497                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16498            }
16499
16500            // Check for shared user id changes
16501            String invalidPackageName =
16502                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16503            if (invalidPackageName != null) {
16504                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16505                        "Package " + invalidPackageName + " tried to change user "
16506                                + oldPackage.mSharedUserId);
16507                return;
16508            }
16509
16510            // In case of rollback, remember per-user/profile install state
16511            allUsers = sUserManager.getUserIds();
16512            installedUsers = ps.queryInstalledUsers(allUsers, true);
16513
16514            // don't allow an upgrade from full to ephemeral
16515            if (isInstantApp) {
16516                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16517                    for (int currentUser : allUsers) {
16518                        if (!ps.getInstantApp(currentUser)) {
16519                            // can't downgrade from full to instant
16520                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16521                                    + " for user: " + currentUser);
16522                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16523                            return;
16524                        }
16525                    }
16526                } else if (!ps.getInstantApp(user.getIdentifier())) {
16527                    // can't downgrade from full to instant
16528                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16529                            + " for user: " + user.getIdentifier());
16530                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16531                    return;
16532                }
16533            }
16534        }
16535
16536        // Update what is removed
16537        res.removedInfo = new PackageRemovedInfo(this);
16538        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16539        res.removedInfo.removedPackage = oldPackage.packageName;
16540        res.removedInfo.installerPackageName = ps.installerPackageName;
16541        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16542        res.removedInfo.isUpdate = true;
16543        res.removedInfo.origUsers = installedUsers;
16544        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16545        for (int i = 0; i < installedUsers.length; i++) {
16546            final int userId = installedUsers[i];
16547            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16548        }
16549
16550        final int childCount = (oldPackage.childPackages != null)
16551                ? oldPackage.childPackages.size() : 0;
16552        for (int i = 0; i < childCount; i++) {
16553            boolean childPackageUpdated = false;
16554            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16555            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16556            if (res.addedChildPackages != null) {
16557                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16558                if (childRes != null) {
16559                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16560                    childRes.removedInfo.removedPackage = childPkg.packageName;
16561                    if (childPs != null) {
16562                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16563                    }
16564                    childRes.removedInfo.isUpdate = true;
16565                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16566                    childPackageUpdated = true;
16567                }
16568            }
16569            if (!childPackageUpdated) {
16570                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16571                childRemovedRes.removedPackage = childPkg.packageName;
16572                if (childPs != null) {
16573                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16574                }
16575                childRemovedRes.isUpdate = false;
16576                childRemovedRes.dataRemoved = true;
16577                synchronized (mPackages) {
16578                    if (childPs != null) {
16579                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16580                    }
16581                }
16582                if (res.removedInfo.removedChildPackages == null) {
16583                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16584                }
16585                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16586            }
16587        }
16588
16589        boolean sysPkg = (isSystemApp(oldPackage));
16590        if (sysPkg) {
16591            // Set the system/privileged/oem flags as needed
16592            final boolean privileged =
16593                    (oldPackage.applicationInfo.privateFlags
16594                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16595            final boolean oem =
16596                    (oldPackage.applicationInfo.privateFlags
16597                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16598            final int systemPolicyFlags = policyFlags
16599                    | PackageParser.PARSE_IS_SYSTEM
16600                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16601                    | (oem ? PARSE_IS_OEM : 0);
16602
16603            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16604                    user, allUsers, installerPackageName, res, installReason);
16605        } else {
16606            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16607                    user, allUsers, installerPackageName, res, installReason);
16608        }
16609    }
16610
16611    @Override
16612    public List<String> getPreviousCodePaths(String packageName) {
16613        final int callingUid = Binder.getCallingUid();
16614        final List<String> result = new ArrayList<>();
16615        if (getInstantAppPackageName(callingUid) != null) {
16616            return result;
16617        }
16618        final PackageSetting ps = mSettings.mPackages.get(packageName);
16619        if (ps != null
16620                && ps.oldCodePaths != null
16621                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16622            result.addAll(ps.oldCodePaths);
16623        }
16624        return result;
16625    }
16626
16627    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16628            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16629            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16630            int installReason) {
16631        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16632                + deletedPackage);
16633
16634        String pkgName = deletedPackage.packageName;
16635        boolean deletedPkg = true;
16636        boolean addedPkg = false;
16637        boolean updatedSettings = false;
16638        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16639        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16640                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16641
16642        final long origUpdateTime = (pkg.mExtras != null)
16643                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16644
16645        // First delete the existing package while retaining the data directory
16646        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16647                res.removedInfo, true, pkg)) {
16648            // If the existing package wasn't successfully deleted
16649            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16650            deletedPkg = false;
16651        } else {
16652            // Successfully deleted the old package; proceed with replace.
16653
16654            // If deleted package lived in a container, give users a chance to
16655            // relinquish resources before killing.
16656            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16657                if (DEBUG_INSTALL) {
16658                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16659                }
16660                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16661                final ArrayList<String> pkgList = new ArrayList<String>(1);
16662                pkgList.add(deletedPackage.applicationInfo.packageName);
16663                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16664            }
16665
16666            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16667                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16668            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16669
16670            try {
16671                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16672                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16673                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16674                        installReason);
16675
16676                // Update the in-memory copy of the previous code paths.
16677                PackageSetting ps = mSettings.mPackages.get(pkgName);
16678                if (!killApp) {
16679                    if (ps.oldCodePaths == null) {
16680                        ps.oldCodePaths = new ArraySet<>();
16681                    }
16682                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16683                    if (deletedPackage.splitCodePaths != null) {
16684                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16685                    }
16686                } else {
16687                    ps.oldCodePaths = null;
16688                }
16689                if (ps.childPackageNames != null) {
16690                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16691                        final String childPkgName = ps.childPackageNames.get(i);
16692                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16693                        childPs.oldCodePaths = ps.oldCodePaths;
16694                    }
16695                }
16696                // set instant app status, but, only if it's explicitly specified
16697                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16698                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16699                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16700                prepareAppDataAfterInstallLIF(newPackage);
16701                addedPkg = true;
16702                mDexManager.notifyPackageUpdated(newPackage.packageName,
16703                        newPackage.baseCodePath, newPackage.splitCodePaths);
16704            } catch (PackageManagerException e) {
16705                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16706            }
16707        }
16708
16709        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16710            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16711
16712            // Revert all internal state mutations and added folders for the failed install
16713            if (addedPkg) {
16714                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16715                        res.removedInfo, true, null);
16716            }
16717
16718            // Restore the old package
16719            if (deletedPkg) {
16720                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16721                File restoreFile = new File(deletedPackage.codePath);
16722                // Parse old package
16723                boolean oldExternal = isExternal(deletedPackage);
16724                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16725                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16726                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16727                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16728                try {
16729                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16730                            null);
16731                } catch (PackageManagerException e) {
16732                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16733                            + e.getMessage());
16734                    return;
16735                }
16736
16737                synchronized (mPackages) {
16738                    // Ensure the installer package name up to date
16739                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16740
16741                    // Update permissions for restored package
16742                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16743
16744                    mSettings.writeLPr();
16745                }
16746
16747                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16748            }
16749        } else {
16750            synchronized (mPackages) {
16751                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16752                if (ps != null) {
16753                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16754                    if (res.removedInfo.removedChildPackages != null) {
16755                        final int childCount = res.removedInfo.removedChildPackages.size();
16756                        // Iterate in reverse as we may modify the collection
16757                        for (int i = childCount - 1; i >= 0; i--) {
16758                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16759                            if (res.addedChildPackages.containsKey(childPackageName)) {
16760                                res.removedInfo.removedChildPackages.removeAt(i);
16761                            } else {
16762                                PackageRemovedInfo childInfo = res.removedInfo
16763                                        .removedChildPackages.valueAt(i);
16764                                childInfo.removedForAllUsers = mPackages.get(
16765                                        childInfo.removedPackage) == null;
16766                            }
16767                        }
16768                    }
16769                }
16770            }
16771        }
16772    }
16773
16774    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16775            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16776            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16777            int installReason) {
16778        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16779                + ", old=" + deletedPackage);
16780
16781        final boolean disabledSystem;
16782
16783        // Remove existing system package
16784        removePackageLI(deletedPackage, true);
16785
16786        synchronized (mPackages) {
16787            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16788        }
16789        if (!disabledSystem) {
16790            // We didn't need to disable the .apk as a current system package,
16791            // which means we are replacing another update that is already
16792            // installed.  We need to make sure to delete the older one's .apk.
16793            res.removedInfo.args = createInstallArgsForExisting(0,
16794                    deletedPackage.applicationInfo.getCodePath(),
16795                    deletedPackage.applicationInfo.getResourcePath(),
16796                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16797        } else {
16798            res.removedInfo.args = null;
16799        }
16800
16801        // Successfully disabled the old package. Now proceed with re-installation
16802        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16803                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16804        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16805
16806        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16807        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16808                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16809
16810        PackageParser.Package newPackage = null;
16811        try {
16812            // Add the package to the internal data structures
16813            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16814
16815            // Set the update and install times
16816            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16817            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16818                    System.currentTimeMillis());
16819
16820            // Update the package dynamic state if succeeded
16821            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16822                // Now that the install succeeded make sure we remove data
16823                // directories for any child package the update removed.
16824                final int deletedChildCount = (deletedPackage.childPackages != null)
16825                        ? deletedPackage.childPackages.size() : 0;
16826                final int newChildCount = (newPackage.childPackages != null)
16827                        ? newPackage.childPackages.size() : 0;
16828                for (int i = 0; i < deletedChildCount; i++) {
16829                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16830                    boolean childPackageDeleted = true;
16831                    for (int j = 0; j < newChildCount; j++) {
16832                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16833                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16834                            childPackageDeleted = false;
16835                            break;
16836                        }
16837                    }
16838                    if (childPackageDeleted) {
16839                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16840                                deletedChildPkg.packageName);
16841                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16842                            PackageRemovedInfo removedChildRes = res.removedInfo
16843                                    .removedChildPackages.get(deletedChildPkg.packageName);
16844                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16845                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16846                        }
16847                    }
16848                }
16849
16850                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16851                        installReason);
16852                prepareAppDataAfterInstallLIF(newPackage);
16853
16854                mDexManager.notifyPackageUpdated(newPackage.packageName,
16855                            newPackage.baseCodePath, newPackage.splitCodePaths);
16856            }
16857        } catch (PackageManagerException e) {
16858            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16859            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16860        }
16861
16862        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16863            // Re installation failed. Restore old information
16864            // Remove new pkg information
16865            if (newPackage != null) {
16866                removeInstalledPackageLI(newPackage, true);
16867            }
16868            // Add back the old system package
16869            try {
16870                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16871            } catch (PackageManagerException e) {
16872                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16873            }
16874
16875            synchronized (mPackages) {
16876                if (disabledSystem) {
16877                    enableSystemPackageLPw(deletedPackage);
16878                }
16879
16880                // Ensure the installer package name up to date
16881                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16882
16883                // Update permissions for restored package
16884                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16885
16886                mSettings.writeLPr();
16887            }
16888
16889            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16890                    + " after failed upgrade");
16891        }
16892    }
16893
16894    /**
16895     * Checks whether the parent or any of the child packages have a change shared
16896     * user. For a package to be a valid update the shred users of the parent and
16897     * the children should match. We may later support changing child shared users.
16898     * @param oldPkg The updated package.
16899     * @param newPkg The update package.
16900     * @return The shared user that change between the versions.
16901     */
16902    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16903            PackageParser.Package newPkg) {
16904        // Check parent shared user
16905        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16906            return newPkg.packageName;
16907        }
16908        // Check child shared users
16909        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16910        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16911        for (int i = 0; i < newChildCount; i++) {
16912            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16913            // If this child was present, did it have the same shared user?
16914            for (int j = 0; j < oldChildCount; j++) {
16915                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16916                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16917                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16918                    return newChildPkg.packageName;
16919                }
16920            }
16921        }
16922        return null;
16923    }
16924
16925    private void removeNativeBinariesLI(PackageSetting ps) {
16926        // Remove the lib path for the parent package
16927        if (ps != null) {
16928            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16929            // Remove the lib path for the child packages
16930            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16931            for (int i = 0; i < childCount; i++) {
16932                PackageSetting childPs = null;
16933                synchronized (mPackages) {
16934                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16935                }
16936                if (childPs != null) {
16937                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16938                            .legacyNativeLibraryPathString);
16939                }
16940            }
16941        }
16942    }
16943
16944    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16945        // Enable the parent package
16946        mSettings.enableSystemPackageLPw(pkg.packageName);
16947        // Enable the child packages
16948        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16949        for (int i = 0; i < childCount; i++) {
16950            PackageParser.Package childPkg = pkg.childPackages.get(i);
16951            mSettings.enableSystemPackageLPw(childPkg.packageName);
16952        }
16953    }
16954
16955    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16956            PackageParser.Package newPkg) {
16957        // Disable the parent package (parent always replaced)
16958        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16959        // Disable the child packages
16960        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16961        for (int i = 0; i < childCount; i++) {
16962            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16963            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16964            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16965        }
16966        return disabled;
16967    }
16968
16969    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16970            String installerPackageName) {
16971        // Enable the parent package
16972        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16973        // Enable the child packages
16974        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16975        for (int i = 0; i < childCount; i++) {
16976            PackageParser.Package childPkg = pkg.childPackages.get(i);
16977            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16978        }
16979    }
16980
16981    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16982            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16983        // Update the parent package setting
16984        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16985                res, user, installReason);
16986        // Update the child packages setting
16987        final int childCount = (newPackage.childPackages != null)
16988                ? newPackage.childPackages.size() : 0;
16989        for (int i = 0; i < childCount; i++) {
16990            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16991            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16992            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16993                    childRes.origUsers, childRes, user, installReason);
16994        }
16995    }
16996
16997    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16998            String installerPackageName, int[] allUsers, int[] installedForUsers,
16999            PackageInstalledInfo res, UserHandle user, int installReason) {
17000        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17001
17002        String pkgName = newPackage.packageName;
17003        synchronized (mPackages) {
17004            //write settings. the installStatus will be incomplete at this stage.
17005            //note that the new package setting would have already been
17006            //added to mPackages. It hasn't been persisted yet.
17007            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17008            // TODO: Remove this write? It's also written at the end of this method
17009            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17010            mSettings.writeLPr();
17011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17012        }
17013
17014        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17015        synchronized (mPackages) {
17016            updatePermissionsLPw(newPackage.packageName, newPackage,
17017                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17018                            ? UPDATE_PERMISSIONS_ALL : 0));
17019            // For system-bundled packages, we assume that installing an upgraded version
17020            // of the package implies that the user actually wants to run that new code,
17021            // so we enable the package.
17022            PackageSetting ps = mSettings.mPackages.get(pkgName);
17023            final int userId = user.getIdentifier();
17024            if (ps != null) {
17025                if (isSystemApp(newPackage)) {
17026                    if (DEBUG_INSTALL) {
17027                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17028                    }
17029                    // Enable system package for requested users
17030                    if (res.origUsers != null) {
17031                        for (int origUserId : res.origUsers) {
17032                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17033                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17034                                        origUserId, installerPackageName);
17035                            }
17036                        }
17037                    }
17038                    // Also convey the prior install/uninstall state
17039                    if (allUsers != null && installedForUsers != null) {
17040                        for (int currentUserId : allUsers) {
17041                            final boolean installed = ArrayUtils.contains(
17042                                    installedForUsers, currentUserId);
17043                            if (DEBUG_INSTALL) {
17044                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17045                            }
17046                            ps.setInstalled(installed, currentUserId);
17047                        }
17048                        // these install state changes will be persisted in the
17049                        // upcoming call to mSettings.writeLPr().
17050                    }
17051                }
17052                // It's implied that when a user requests installation, they want the app to be
17053                // installed and enabled.
17054                if (userId != UserHandle.USER_ALL) {
17055                    ps.setInstalled(true, userId);
17056                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17057                }
17058
17059                // When replacing an existing package, preserve the original install reason for all
17060                // users that had the package installed before.
17061                final Set<Integer> previousUserIds = new ArraySet<>();
17062                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17063                    final int installReasonCount = res.removedInfo.installReasons.size();
17064                    for (int i = 0; i < installReasonCount; i++) {
17065                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17066                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17067                        ps.setInstallReason(previousInstallReason, previousUserId);
17068                        previousUserIds.add(previousUserId);
17069                    }
17070                }
17071
17072                // Set install reason for users that are having the package newly installed.
17073                if (userId == UserHandle.USER_ALL) {
17074                    for (int currentUserId : sUserManager.getUserIds()) {
17075                        if (!previousUserIds.contains(currentUserId)) {
17076                            ps.setInstallReason(installReason, currentUserId);
17077                        }
17078                    }
17079                } else if (!previousUserIds.contains(userId)) {
17080                    ps.setInstallReason(installReason, userId);
17081                }
17082                mSettings.writeKernelMappingLPr(ps);
17083            }
17084            res.name = pkgName;
17085            res.uid = newPackage.applicationInfo.uid;
17086            res.pkg = newPackage;
17087            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17088            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17089            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17090            //to update install status
17091            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17092            mSettings.writeLPr();
17093            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17094        }
17095
17096        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17097    }
17098
17099    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17100        try {
17101            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17102            installPackageLI(args, res);
17103        } finally {
17104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17105        }
17106    }
17107
17108    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17109        final int installFlags = args.installFlags;
17110        final String installerPackageName = args.installerPackageName;
17111        final String volumeUuid = args.volumeUuid;
17112        final File tmpPackageFile = new File(args.getCodePath());
17113        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17114        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17115                || (args.volumeUuid != null));
17116        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17117        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17118        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17119        final boolean virtualPreload =
17120                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17121        boolean replace = false;
17122        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17123        if (args.move != null) {
17124            // moving a complete application; perform an initial scan on the new install location
17125            scanFlags |= SCAN_INITIAL;
17126        }
17127        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17128            scanFlags |= SCAN_DONT_KILL_APP;
17129        }
17130        if (instantApp) {
17131            scanFlags |= SCAN_AS_INSTANT_APP;
17132        }
17133        if (fullApp) {
17134            scanFlags |= SCAN_AS_FULL_APP;
17135        }
17136        if (virtualPreload) {
17137            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17138        }
17139
17140        // Result object to be returned
17141        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17142        res.installerPackageName = installerPackageName;
17143
17144        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17145
17146        // Sanity check
17147        if (instantApp && (forwardLocked || onExternal)) {
17148            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17149                    + " external=" + onExternal);
17150            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17151            return;
17152        }
17153
17154        // Retrieve PackageSettings and parse package
17155        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17156                | PackageParser.PARSE_ENFORCE_CODE
17157                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17158                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17159                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17160                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17161        PackageParser pp = new PackageParser();
17162        pp.setSeparateProcesses(mSeparateProcesses);
17163        pp.setDisplayMetrics(mMetrics);
17164        pp.setCallback(mPackageParserCallback);
17165
17166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17167        final PackageParser.Package pkg;
17168        try {
17169            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17170        } catch (PackageParserException e) {
17171            res.setError("Failed parse during installPackageLI", e);
17172            return;
17173        } finally {
17174            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17175        }
17176
17177        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17178        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17179            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17180            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17181                    "Instant app package must target O");
17182            return;
17183        }
17184        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17185            Slog.w(TAG, "Instant app package " + pkg.packageName
17186                    + " does not target targetSandboxVersion 2");
17187            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17188                    "Instant app package must use targetSanboxVersion 2");
17189            return;
17190        }
17191
17192        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17193            // Static shared libraries have synthetic package names
17194            renameStaticSharedLibraryPackage(pkg);
17195
17196            // No static shared libs on external storage
17197            if (onExternal) {
17198                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17199                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17200                        "Packages declaring static-shared libs cannot be updated");
17201                return;
17202            }
17203        }
17204
17205        // If we are installing a clustered package add results for the children
17206        if (pkg.childPackages != null) {
17207            synchronized (mPackages) {
17208                final int childCount = pkg.childPackages.size();
17209                for (int i = 0; i < childCount; i++) {
17210                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17211                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17212                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17213                    childRes.pkg = childPkg;
17214                    childRes.name = childPkg.packageName;
17215                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17216                    if (childPs != null) {
17217                        childRes.origUsers = childPs.queryInstalledUsers(
17218                                sUserManager.getUserIds(), true);
17219                    }
17220                    if ((mPackages.containsKey(childPkg.packageName))) {
17221                        childRes.removedInfo = new PackageRemovedInfo(this);
17222                        childRes.removedInfo.removedPackage = childPkg.packageName;
17223                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17224                    }
17225                    if (res.addedChildPackages == null) {
17226                        res.addedChildPackages = new ArrayMap<>();
17227                    }
17228                    res.addedChildPackages.put(childPkg.packageName, childRes);
17229                }
17230            }
17231        }
17232
17233        // If package doesn't declare API override, mark that we have an install
17234        // time CPU ABI override.
17235        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17236            pkg.cpuAbiOverride = args.abiOverride;
17237        }
17238
17239        String pkgName = res.name = pkg.packageName;
17240        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17241            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17242                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17243                return;
17244            }
17245        }
17246
17247        try {
17248            // either use what we've been given or parse directly from the APK
17249            if (args.certificates != null) {
17250                try {
17251                    PackageParser.populateCertificates(pkg, args.certificates);
17252                } catch (PackageParserException e) {
17253                    // there was something wrong with the certificates we were given;
17254                    // try to pull them from the APK
17255                    PackageParser.collectCertificates(pkg, parseFlags);
17256                }
17257            } else {
17258                PackageParser.collectCertificates(pkg, parseFlags);
17259            }
17260        } catch (PackageParserException e) {
17261            res.setError("Failed collect during installPackageLI", e);
17262            return;
17263        }
17264
17265        // Get rid of all references to package scan path via parser.
17266        pp = null;
17267        String oldCodePath = null;
17268        boolean systemApp = false;
17269        synchronized (mPackages) {
17270            // Check if installing already existing package
17271            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17272                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17273                if (pkg.mOriginalPackages != null
17274                        && pkg.mOriginalPackages.contains(oldName)
17275                        && mPackages.containsKey(oldName)) {
17276                    // This package is derived from an original package,
17277                    // and this device has been updating from that original
17278                    // name.  We must continue using the original name, so
17279                    // rename the new package here.
17280                    pkg.setPackageName(oldName);
17281                    pkgName = pkg.packageName;
17282                    replace = true;
17283                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17284                            + oldName + " pkgName=" + pkgName);
17285                } else if (mPackages.containsKey(pkgName)) {
17286                    // This package, under its official name, already exists
17287                    // on the device; we should replace it.
17288                    replace = true;
17289                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17290                }
17291
17292                // Child packages are installed through the parent package
17293                if (pkg.parentPackage != null) {
17294                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17295                            "Package " + pkg.packageName + " is child of package "
17296                                    + pkg.parentPackage.parentPackage + ". Child packages "
17297                                    + "can be updated only through the parent package.");
17298                    return;
17299                }
17300
17301                if (replace) {
17302                    // Prevent apps opting out from runtime permissions
17303                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17304                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17305                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17306                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17307                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17308                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17309                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17310                                        + " doesn't support runtime permissions but the old"
17311                                        + " target SDK " + oldTargetSdk + " does.");
17312                        return;
17313                    }
17314                    // Prevent apps from downgrading their targetSandbox.
17315                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17316                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17317                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17318                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17319                                "Package " + pkg.packageName + " new target sandbox "
17320                                + newTargetSandbox + " is incompatible with the previous value of"
17321                                + oldTargetSandbox + ".");
17322                        return;
17323                    }
17324
17325                    // Prevent installing of child packages
17326                    if (oldPackage.parentPackage != null) {
17327                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17328                                "Package " + pkg.packageName + " is child of package "
17329                                        + oldPackage.parentPackage + ". Child packages "
17330                                        + "can be updated only through the parent package.");
17331                        return;
17332                    }
17333                }
17334            }
17335
17336            PackageSetting ps = mSettings.mPackages.get(pkgName);
17337            if (ps != null) {
17338                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17339
17340                // Static shared libs have same package with different versions where
17341                // we internally use a synthetic package name to allow multiple versions
17342                // of the same package, therefore we need to compare signatures against
17343                // the package setting for the latest library version.
17344                PackageSetting signatureCheckPs = ps;
17345                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17346                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17347                    if (libraryEntry != null) {
17348                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17349                    }
17350                }
17351
17352                // Quick sanity check that we're signed correctly if updating;
17353                // we'll check this again later when scanning, but we want to
17354                // bail early here before tripping over redefined permissions.
17355                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17356                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17357                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17358                                + pkg.packageName + " upgrade keys do not match the "
17359                                + "previously installed version");
17360                        return;
17361                    }
17362                } else {
17363                    try {
17364                        verifySignaturesLP(signatureCheckPs, pkg);
17365                    } catch (PackageManagerException e) {
17366                        res.setError(e.error, e.getMessage());
17367                        return;
17368                    }
17369                }
17370
17371                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17372                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17373                    systemApp = (ps.pkg.applicationInfo.flags &
17374                            ApplicationInfo.FLAG_SYSTEM) != 0;
17375                }
17376                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17377            }
17378
17379            int N = pkg.permissions.size();
17380            for (int i = N-1; i >= 0; i--) {
17381                final PackageParser.Permission perm = pkg.permissions.get(i);
17382                final BasePermission bp =
17383                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17384
17385                // Don't allow anyone but the system to define ephemeral permissions.
17386                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17387                        && !systemApp) {
17388                    Slog.w(TAG, "Non-System package " + pkg.packageName
17389                            + " attempting to delcare ephemeral permission "
17390                            + perm.info.name + "; Removing ephemeral.");
17391                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17392                }
17393
17394                // Check whether the newly-scanned package wants to define an already-defined perm
17395                if (bp != null) {
17396                    // If the defining package is signed with our cert, it's okay.  This
17397                    // also includes the "updating the same package" case, of course.
17398                    // "updating same package" could also involve key-rotation.
17399                    final boolean sigsOk;
17400                    final String sourcePackageName = bp.getSourcePackageName();
17401                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17402                    if (sourcePackageName.equals(pkg.packageName)
17403                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17404                                    scanFlags))) {
17405                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17406                    } else {
17407                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17408                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17409                    }
17410                    if (!sigsOk) {
17411                        // If the owning package is the system itself, we log but allow
17412                        // install to proceed; we fail the install on all other permission
17413                        // redefinitions.
17414                        if (!sourcePackageName.equals("android")) {
17415                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17416                                    + pkg.packageName + " attempting to redeclare permission "
17417                                    + perm.info.name + " already owned by " + sourcePackageName);
17418                            res.origPermission = perm.info.name;
17419                            res.origPackage = sourcePackageName;
17420                            return;
17421                        } else {
17422                            Slog.w(TAG, "Package " + pkg.packageName
17423                                    + " attempting to redeclare system permission "
17424                                    + perm.info.name + "; ignoring new declaration");
17425                            pkg.permissions.remove(i);
17426                        }
17427                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17428                        // Prevent apps to change protection level to dangerous from any other
17429                        // type as this would allow a privilege escalation where an app adds a
17430                        // normal/signature permission in other app's group and later redefines
17431                        // it as dangerous leading to the group auto-grant.
17432                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17433                                == PermissionInfo.PROTECTION_DANGEROUS) {
17434                            if (bp != null && !bp.isRuntime()) {
17435                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17436                                        + "non-runtime permission " + perm.info.name
17437                                        + " to runtime; keeping old protection level");
17438                                perm.info.protectionLevel = bp.getProtectionLevel();
17439                            }
17440                        }
17441                    }
17442                }
17443            }
17444        }
17445
17446        if (systemApp) {
17447            if (onExternal) {
17448                // Abort update; system app can't be replaced with app on sdcard
17449                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17450                        "Cannot install updates to system apps on sdcard");
17451                return;
17452            } else if (instantApp) {
17453                // Abort update; system app can't be replaced with an instant app
17454                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17455                        "Cannot update a system app with an instant app");
17456                return;
17457            }
17458        }
17459
17460        if (args.move != null) {
17461            // We did an in-place move, so dex is ready to roll
17462            scanFlags |= SCAN_NO_DEX;
17463            scanFlags |= SCAN_MOVE;
17464
17465            synchronized (mPackages) {
17466                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17467                if (ps == null) {
17468                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17469                            "Missing settings for moved package " + pkgName);
17470                }
17471
17472                // We moved the entire application as-is, so bring over the
17473                // previously derived ABI information.
17474                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17475                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17476            }
17477
17478        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17479            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17480            scanFlags |= SCAN_NO_DEX;
17481
17482            try {
17483                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17484                    args.abiOverride : pkg.cpuAbiOverride);
17485                final boolean extractNativeLibs = !pkg.isLibrary();
17486                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17487                        extractNativeLibs, mAppLib32InstallDir);
17488            } catch (PackageManagerException pme) {
17489                Slog.e(TAG, "Error deriving application ABI", pme);
17490                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17491                return;
17492            }
17493
17494            // Shared libraries for the package need to be updated.
17495            synchronized (mPackages) {
17496                try {
17497                    updateSharedLibrariesLPr(pkg, null);
17498                } catch (PackageManagerException e) {
17499                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17500                }
17501            }
17502        }
17503
17504        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17505            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17506            return;
17507        }
17508
17509        // Verify if we need to dexopt the app.
17510        //
17511        // NOTE: it is *important* to call dexopt after doRename which will sync the
17512        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17513        //
17514        // We only need to dexopt if the package meets ALL of the following conditions:
17515        //   1) it is not forward locked.
17516        //   2) it is not on on an external ASEC container.
17517        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17518        //
17519        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17520        // complete, so we skip this step during installation. Instead, we'll take extra time
17521        // the first time the instant app starts. It's preferred to do it this way to provide
17522        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17523        // middle of running an instant app. The default behaviour can be overridden
17524        // via gservices.
17525        final boolean performDexopt = !forwardLocked
17526            && !pkg.applicationInfo.isExternalAsec()
17527            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17528                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17529
17530        if (performDexopt) {
17531            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17532            // Do not run PackageDexOptimizer through the local performDexOpt
17533            // method because `pkg` may not be in `mPackages` yet.
17534            //
17535            // Also, don't fail application installs if the dexopt step fails.
17536            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17537                REASON_INSTALL,
17538                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17539            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17540                null /* instructionSets */,
17541                getOrCreateCompilerPackageStats(pkg),
17542                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17543                dexoptOptions);
17544            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17545        }
17546
17547        // Notify BackgroundDexOptService that the package has been changed.
17548        // If this is an update of a package which used to fail to compile,
17549        // BackgroundDexOptService will remove it from its blacklist.
17550        // TODO: Layering violation
17551        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17552
17553        if (!instantApp) {
17554            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17555        } else {
17556            if (DEBUG_DOMAIN_VERIFICATION) {
17557                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17558            }
17559        }
17560
17561        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17562                "installPackageLI")) {
17563            if (replace) {
17564                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17565                    // Static libs have a synthetic package name containing the version
17566                    // and cannot be updated as an update would get a new package name,
17567                    // unless this is the exact same version code which is useful for
17568                    // development.
17569                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17570                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17571                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17572                                + "static-shared libs cannot be updated");
17573                        return;
17574                    }
17575                }
17576                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17577                        installerPackageName, res, args.installReason);
17578            } else {
17579                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17580                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17581            }
17582        }
17583
17584        synchronized (mPackages) {
17585            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17586            if (ps != null) {
17587                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17588                ps.setUpdateAvailable(false /*updateAvailable*/);
17589            }
17590
17591            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17592            for (int i = 0; i < childCount; i++) {
17593                PackageParser.Package childPkg = pkg.childPackages.get(i);
17594                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17595                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17596                if (childPs != null) {
17597                    childRes.newUsers = childPs.queryInstalledUsers(
17598                            sUserManager.getUserIds(), true);
17599                }
17600            }
17601
17602            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17603                updateSequenceNumberLP(ps, res.newUsers);
17604                updateInstantAppInstallerLocked(pkgName);
17605            }
17606        }
17607    }
17608
17609    private void startIntentFilterVerifications(int userId, boolean replacing,
17610            PackageParser.Package pkg) {
17611        if (mIntentFilterVerifierComponent == null) {
17612            Slog.w(TAG, "No IntentFilter verification will not be done as "
17613                    + "there is no IntentFilterVerifier available!");
17614            return;
17615        }
17616
17617        final int verifierUid = getPackageUid(
17618                mIntentFilterVerifierComponent.getPackageName(),
17619                MATCH_DEBUG_TRIAGED_MISSING,
17620                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17621
17622        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17623        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17624        mHandler.sendMessage(msg);
17625
17626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17627        for (int i = 0; i < childCount; i++) {
17628            PackageParser.Package childPkg = pkg.childPackages.get(i);
17629            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17630            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17631            mHandler.sendMessage(msg);
17632        }
17633    }
17634
17635    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17636            PackageParser.Package pkg) {
17637        int size = pkg.activities.size();
17638        if (size == 0) {
17639            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17640                    "No activity, so no need to verify any IntentFilter!");
17641            return;
17642        }
17643
17644        final boolean hasDomainURLs = hasDomainURLs(pkg);
17645        if (!hasDomainURLs) {
17646            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17647                    "No domain URLs, so no need to verify any IntentFilter!");
17648            return;
17649        }
17650
17651        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17652                + " if any IntentFilter from the " + size
17653                + " Activities needs verification ...");
17654
17655        int count = 0;
17656        final String packageName = pkg.packageName;
17657
17658        synchronized (mPackages) {
17659            // If this is a new install and we see that we've already run verification for this
17660            // package, we have nothing to do: it means the state was restored from backup.
17661            if (!replacing) {
17662                IntentFilterVerificationInfo ivi =
17663                        mSettings.getIntentFilterVerificationLPr(packageName);
17664                if (ivi != null) {
17665                    if (DEBUG_DOMAIN_VERIFICATION) {
17666                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17667                                + ivi.getStatusString());
17668                    }
17669                    return;
17670                }
17671            }
17672
17673            // If any filters need to be verified, then all need to be.
17674            boolean needToVerify = false;
17675            for (PackageParser.Activity a : pkg.activities) {
17676                for (ActivityIntentInfo filter : a.intents) {
17677                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17678                        if (DEBUG_DOMAIN_VERIFICATION) {
17679                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17680                        }
17681                        needToVerify = true;
17682                        break;
17683                    }
17684                }
17685            }
17686
17687            if (needToVerify) {
17688                final int verificationId = mIntentFilterVerificationToken++;
17689                for (PackageParser.Activity a : pkg.activities) {
17690                    for (ActivityIntentInfo filter : a.intents) {
17691                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17692                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17693                                    "Verification needed for IntentFilter:" + filter.toString());
17694                            mIntentFilterVerifier.addOneIntentFilterVerification(
17695                                    verifierUid, userId, verificationId, filter, packageName);
17696                            count++;
17697                        }
17698                    }
17699                }
17700            }
17701        }
17702
17703        if (count > 0) {
17704            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17705                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17706                    +  " for userId:" + userId);
17707            mIntentFilterVerifier.startVerifications(userId);
17708        } else {
17709            if (DEBUG_DOMAIN_VERIFICATION) {
17710                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17711            }
17712        }
17713    }
17714
17715    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17716        final ComponentName cn  = filter.activity.getComponentName();
17717        final String packageName = cn.getPackageName();
17718
17719        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17720                packageName);
17721        if (ivi == null) {
17722            return true;
17723        }
17724        int status = ivi.getStatus();
17725        switch (status) {
17726            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17727            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17728                return true;
17729
17730            default:
17731                // Nothing to do
17732                return false;
17733        }
17734    }
17735
17736    private static boolean isMultiArch(ApplicationInfo info) {
17737        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17738    }
17739
17740    private static boolean isExternal(PackageParser.Package pkg) {
17741        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17742    }
17743
17744    private static boolean isExternal(PackageSetting ps) {
17745        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17746    }
17747
17748    private static boolean isSystemApp(PackageParser.Package pkg) {
17749        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17750    }
17751
17752    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17753        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17754    }
17755
17756    private static boolean isOemApp(PackageParser.Package pkg) {
17757        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17758    }
17759
17760    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17761        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17762    }
17763
17764    private static boolean isSystemApp(PackageSetting ps) {
17765        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17766    }
17767
17768    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17769        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17770    }
17771
17772    private int packageFlagsToInstallFlags(PackageSetting ps) {
17773        int installFlags = 0;
17774        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17775            // This existing package was an external ASEC install when we have
17776            // the external flag without a UUID
17777            installFlags |= PackageManager.INSTALL_EXTERNAL;
17778        }
17779        if (ps.isForwardLocked()) {
17780            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17781        }
17782        return installFlags;
17783    }
17784
17785    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17786        if (isExternal(pkg)) {
17787            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17788                return StorageManager.UUID_PRIMARY_PHYSICAL;
17789            } else {
17790                return pkg.volumeUuid;
17791            }
17792        } else {
17793            return StorageManager.UUID_PRIVATE_INTERNAL;
17794        }
17795    }
17796
17797    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17798        if (isExternal(pkg)) {
17799            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17800                return mSettings.getExternalVersion();
17801            } else {
17802                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17803            }
17804        } else {
17805            return mSettings.getInternalVersion();
17806        }
17807    }
17808
17809    private void deleteTempPackageFiles() {
17810        final FilenameFilter filter = new FilenameFilter() {
17811            public boolean accept(File dir, String name) {
17812                return name.startsWith("vmdl") && name.endsWith(".tmp");
17813            }
17814        };
17815        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17816            file.delete();
17817        }
17818    }
17819
17820    @Override
17821    public void deletePackageAsUser(String packageName, int versionCode,
17822            IPackageDeleteObserver observer, int userId, int flags) {
17823        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17824                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17825    }
17826
17827    @Override
17828    public void deletePackageVersioned(VersionedPackage versionedPackage,
17829            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17830        final int callingUid = Binder.getCallingUid();
17831        mContext.enforceCallingOrSelfPermission(
17832                android.Manifest.permission.DELETE_PACKAGES, null);
17833        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17834        Preconditions.checkNotNull(versionedPackage);
17835        Preconditions.checkNotNull(observer);
17836        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17837                PackageManager.VERSION_CODE_HIGHEST,
17838                Integer.MAX_VALUE, "versionCode must be >= -1");
17839
17840        final String packageName = versionedPackage.getPackageName();
17841        final int versionCode = versionedPackage.getVersionCode();
17842        final String internalPackageName;
17843        synchronized (mPackages) {
17844            // Normalize package name to handle renamed packages and static libs
17845            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17846                    versionedPackage.getVersionCode());
17847        }
17848
17849        final int uid = Binder.getCallingUid();
17850        if (!isOrphaned(internalPackageName)
17851                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17852            try {
17853                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17854                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17855                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17856                observer.onUserActionRequired(intent);
17857            } catch (RemoteException re) {
17858            }
17859            return;
17860        }
17861        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17862        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17863        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17864            mContext.enforceCallingOrSelfPermission(
17865                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17866                    "deletePackage for user " + userId);
17867        }
17868
17869        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17870            try {
17871                observer.onPackageDeleted(packageName,
17872                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17873            } catch (RemoteException re) {
17874            }
17875            return;
17876        }
17877
17878        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17879            try {
17880                observer.onPackageDeleted(packageName,
17881                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17882            } catch (RemoteException re) {
17883            }
17884            return;
17885        }
17886
17887        if (DEBUG_REMOVE) {
17888            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17889                    + " deleteAllUsers: " + deleteAllUsers + " version="
17890                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17891                    ? "VERSION_CODE_HIGHEST" : versionCode));
17892        }
17893        // Queue up an async operation since the package deletion may take a little while.
17894        mHandler.post(new Runnable() {
17895            public void run() {
17896                mHandler.removeCallbacks(this);
17897                int returnCode;
17898                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17899                boolean doDeletePackage = true;
17900                if (ps != null) {
17901                    final boolean targetIsInstantApp =
17902                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17903                    doDeletePackage = !targetIsInstantApp
17904                            || canViewInstantApps;
17905                }
17906                if (doDeletePackage) {
17907                    if (!deleteAllUsers) {
17908                        returnCode = deletePackageX(internalPackageName, versionCode,
17909                                userId, deleteFlags);
17910                    } else {
17911                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17912                                internalPackageName, users);
17913                        // If nobody is blocking uninstall, proceed with delete for all users
17914                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17915                            returnCode = deletePackageX(internalPackageName, versionCode,
17916                                    userId, deleteFlags);
17917                        } else {
17918                            // Otherwise uninstall individually for users with blockUninstalls=false
17919                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17920                            for (int userId : users) {
17921                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17922                                    returnCode = deletePackageX(internalPackageName, versionCode,
17923                                            userId, userFlags);
17924                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17925                                        Slog.w(TAG, "Package delete failed for user " + userId
17926                                                + ", returnCode " + returnCode);
17927                                    }
17928                                }
17929                            }
17930                            // The app has only been marked uninstalled for certain users.
17931                            // We still need to report that delete was blocked
17932                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17933                        }
17934                    }
17935                } else {
17936                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17937                }
17938                try {
17939                    observer.onPackageDeleted(packageName, returnCode, null);
17940                } catch (RemoteException e) {
17941                    Log.i(TAG, "Observer no longer exists.");
17942                } //end catch
17943            } //end run
17944        });
17945    }
17946
17947    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17948        if (pkg.staticSharedLibName != null) {
17949            return pkg.manifestPackageName;
17950        }
17951        return pkg.packageName;
17952    }
17953
17954    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17955        // Handle renamed packages
17956        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17957        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17958
17959        // Is this a static library?
17960        SparseArray<SharedLibraryEntry> versionedLib =
17961                mStaticLibsByDeclaringPackage.get(packageName);
17962        if (versionedLib == null || versionedLib.size() <= 0) {
17963            return packageName;
17964        }
17965
17966        // Figure out which lib versions the caller can see
17967        SparseIntArray versionsCallerCanSee = null;
17968        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17969        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17970                && callingAppId != Process.ROOT_UID) {
17971            versionsCallerCanSee = new SparseIntArray();
17972            String libName = versionedLib.valueAt(0).info.getName();
17973            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17974            if (uidPackages != null) {
17975                for (String uidPackage : uidPackages) {
17976                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17977                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17978                    if (libIdx >= 0) {
17979                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17980                        versionsCallerCanSee.append(libVersion, libVersion);
17981                    }
17982                }
17983            }
17984        }
17985
17986        // Caller can see nothing - done
17987        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17988            return packageName;
17989        }
17990
17991        // Find the version the caller can see and the app version code
17992        SharedLibraryEntry highestVersion = null;
17993        final int versionCount = versionedLib.size();
17994        for (int i = 0; i < versionCount; i++) {
17995            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17996            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17997                    libEntry.info.getVersion()) < 0) {
17998                continue;
17999            }
18000            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18001            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18002                if (libVersionCode == versionCode) {
18003                    return libEntry.apk;
18004                }
18005            } else if (highestVersion == null) {
18006                highestVersion = libEntry;
18007            } else if (libVersionCode  > highestVersion.info
18008                    .getDeclaringPackage().getVersionCode()) {
18009                highestVersion = libEntry;
18010            }
18011        }
18012
18013        if (highestVersion != null) {
18014            return highestVersion.apk;
18015        }
18016
18017        return packageName;
18018    }
18019
18020    boolean isCallerVerifier(int callingUid) {
18021        final int callingUserId = UserHandle.getUserId(callingUid);
18022        return mRequiredVerifierPackage != null &&
18023                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18024    }
18025
18026    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18027        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18028              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18029            return true;
18030        }
18031        final int callingUserId = UserHandle.getUserId(callingUid);
18032        // If the caller installed the pkgName, then allow it to silently uninstall.
18033        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18034            return true;
18035        }
18036
18037        // Allow package verifier to silently uninstall.
18038        if (mRequiredVerifierPackage != null &&
18039                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18040            return true;
18041        }
18042
18043        // Allow package uninstaller to silently uninstall.
18044        if (mRequiredUninstallerPackage != null &&
18045                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18046            return true;
18047        }
18048
18049        // Allow storage manager to silently uninstall.
18050        if (mStorageManagerPackage != null &&
18051                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18052            return true;
18053        }
18054
18055        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18056        // uninstall for device owner provisioning.
18057        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18058                == PERMISSION_GRANTED) {
18059            return true;
18060        }
18061
18062        return false;
18063    }
18064
18065    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18066        int[] result = EMPTY_INT_ARRAY;
18067        for (int userId : userIds) {
18068            if (getBlockUninstallForUser(packageName, userId)) {
18069                result = ArrayUtils.appendInt(result, userId);
18070            }
18071        }
18072        return result;
18073    }
18074
18075    @Override
18076    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18077        final int callingUid = Binder.getCallingUid();
18078        if (getInstantAppPackageName(callingUid) != null
18079                && !isCallerSameApp(packageName, callingUid)) {
18080            return false;
18081        }
18082        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18083    }
18084
18085    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18086        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18087                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18088        try {
18089            if (dpm != null) {
18090                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18091                        /* callingUserOnly =*/ false);
18092                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18093                        : deviceOwnerComponentName.getPackageName();
18094                // Does the package contains the device owner?
18095                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18096                // this check is probably not needed, since DO should be registered as a device
18097                // admin on some user too. (Original bug for this: b/17657954)
18098                if (packageName.equals(deviceOwnerPackageName)) {
18099                    return true;
18100                }
18101                // Does it contain a device admin for any user?
18102                int[] users;
18103                if (userId == UserHandle.USER_ALL) {
18104                    users = sUserManager.getUserIds();
18105                } else {
18106                    users = new int[]{userId};
18107                }
18108                for (int i = 0; i < users.length; ++i) {
18109                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18110                        return true;
18111                    }
18112                }
18113            }
18114        } catch (RemoteException e) {
18115        }
18116        return false;
18117    }
18118
18119    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18120        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18121    }
18122
18123    /**
18124     *  This method is an internal method that could be get invoked either
18125     *  to delete an installed package or to clean up a failed installation.
18126     *  After deleting an installed package, a broadcast is sent to notify any
18127     *  listeners that the package has been removed. For cleaning up a failed
18128     *  installation, the broadcast is not necessary since the package's
18129     *  installation wouldn't have sent the initial broadcast either
18130     *  The key steps in deleting a package are
18131     *  deleting the package information in internal structures like mPackages,
18132     *  deleting the packages base directories through installd
18133     *  updating mSettings to reflect current status
18134     *  persisting settings for later use
18135     *  sending a broadcast if necessary
18136     */
18137    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18138        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18139        final boolean res;
18140
18141        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18142                ? UserHandle.USER_ALL : userId;
18143
18144        if (isPackageDeviceAdmin(packageName, removeUser)) {
18145            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18146            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18147        }
18148
18149        PackageSetting uninstalledPs = null;
18150        PackageParser.Package pkg = null;
18151
18152        // for the uninstall-updates case and restricted profiles, remember the per-
18153        // user handle installed state
18154        int[] allUsers;
18155        synchronized (mPackages) {
18156            uninstalledPs = mSettings.mPackages.get(packageName);
18157            if (uninstalledPs == null) {
18158                Slog.w(TAG, "Not removing non-existent package " + packageName);
18159                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18160            }
18161
18162            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18163                    && uninstalledPs.versionCode != versionCode) {
18164                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18165                        + uninstalledPs.versionCode + " != " + versionCode);
18166                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18167            }
18168
18169            // Static shared libs can be declared by any package, so let us not
18170            // allow removing a package if it provides a lib others depend on.
18171            pkg = mPackages.get(packageName);
18172
18173            allUsers = sUserManager.getUserIds();
18174
18175            if (pkg != null && pkg.staticSharedLibName != null) {
18176                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18177                        pkg.staticSharedLibVersion);
18178                if (libEntry != null) {
18179                    for (int currUserId : allUsers) {
18180                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18181                            continue;
18182                        }
18183                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18184                                libEntry.info, 0, currUserId);
18185                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18186                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18187                                    + " hosting lib " + libEntry.info.getName() + " version "
18188                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18189                                    + " for user " + currUserId);
18190                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18191                        }
18192                    }
18193                }
18194            }
18195
18196            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18197        }
18198
18199        final int freezeUser;
18200        if (isUpdatedSystemApp(uninstalledPs)
18201                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18202            // We're downgrading a system app, which will apply to all users, so
18203            // freeze them all during the downgrade
18204            freezeUser = UserHandle.USER_ALL;
18205        } else {
18206            freezeUser = removeUser;
18207        }
18208
18209        synchronized (mInstallLock) {
18210            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18211            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18212                    deleteFlags, "deletePackageX")) {
18213                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18214                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18215            }
18216            synchronized (mPackages) {
18217                if (res) {
18218                    if (pkg != null) {
18219                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18220                    }
18221                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18222                    updateInstantAppInstallerLocked(packageName);
18223                }
18224            }
18225        }
18226
18227        if (res) {
18228            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18229            info.sendPackageRemovedBroadcasts(killApp);
18230            info.sendSystemPackageUpdatedBroadcasts();
18231            info.sendSystemPackageAppearedBroadcasts();
18232        }
18233        // Force a gc here.
18234        Runtime.getRuntime().gc();
18235        // Delete the resources here after sending the broadcast to let
18236        // other processes clean up before deleting resources.
18237        if (info.args != null) {
18238            synchronized (mInstallLock) {
18239                info.args.doPostDeleteLI(true);
18240            }
18241        }
18242
18243        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18244    }
18245
18246    static class PackageRemovedInfo {
18247        final PackageSender packageSender;
18248        String removedPackage;
18249        String installerPackageName;
18250        int uid = -1;
18251        int removedAppId = -1;
18252        int[] origUsers;
18253        int[] removedUsers = null;
18254        int[] broadcastUsers = null;
18255        SparseArray<Integer> installReasons;
18256        boolean isRemovedPackageSystemUpdate = false;
18257        boolean isUpdate;
18258        boolean dataRemoved;
18259        boolean removedForAllUsers;
18260        boolean isStaticSharedLib;
18261        // Clean up resources deleted packages.
18262        InstallArgs args = null;
18263        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18264        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18265
18266        PackageRemovedInfo(PackageSender packageSender) {
18267            this.packageSender = packageSender;
18268        }
18269
18270        void sendPackageRemovedBroadcasts(boolean killApp) {
18271            sendPackageRemovedBroadcastInternal(killApp);
18272            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18273            for (int i = 0; i < childCount; i++) {
18274                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18275                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18276            }
18277        }
18278
18279        void sendSystemPackageUpdatedBroadcasts() {
18280            if (isRemovedPackageSystemUpdate) {
18281                sendSystemPackageUpdatedBroadcastsInternal();
18282                final int childCount = (removedChildPackages != null)
18283                        ? removedChildPackages.size() : 0;
18284                for (int i = 0; i < childCount; i++) {
18285                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18286                    if (childInfo.isRemovedPackageSystemUpdate) {
18287                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18288                    }
18289                }
18290            }
18291        }
18292
18293        void sendSystemPackageAppearedBroadcasts() {
18294            final int packageCount = (appearedChildPackages != null)
18295                    ? appearedChildPackages.size() : 0;
18296            for (int i = 0; i < packageCount; i++) {
18297                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18298                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18299                    true /*sendBootCompleted*/, false /*startReceiver*/,
18300                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18301            }
18302        }
18303
18304        private void sendSystemPackageUpdatedBroadcastsInternal() {
18305            Bundle extras = new Bundle(2);
18306            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18307            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18308            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18309                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18310            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18311                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18312            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18313                null, null, 0, removedPackage, null, null);
18314            if (installerPackageName != null) {
18315                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18316                        removedPackage, extras, 0 /*flags*/,
18317                        installerPackageName, null, null);
18318                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18319                        removedPackage, extras, 0 /*flags*/,
18320                        installerPackageName, null, null);
18321            }
18322        }
18323
18324        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18325            // Don't send static shared library removal broadcasts as these
18326            // libs are visible only the the apps that depend on them an one
18327            // cannot remove the library if it has a dependency.
18328            if (isStaticSharedLib) {
18329                return;
18330            }
18331            Bundle extras = new Bundle(2);
18332            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18333            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18334            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18335            if (isUpdate || isRemovedPackageSystemUpdate) {
18336                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18337            }
18338            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18339            if (removedPackage != null) {
18340                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18341                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18342                if (installerPackageName != null) {
18343                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18344                            removedPackage, extras, 0 /*flags*/,
18345                            installerPackageName, null, broadcastUsers);
18346                }
18347                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18348                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18349                        removedPackage, extras,
18350                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18351                        null, null, broadcastUsers);
18352                }
18353            }
18354            if (removedAppId >= 0) {
18355                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18356                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18357                    null, null, broadcastUsers);
18358            }
18359        }
18360
18361        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18362            removedUsers = userIds;
18363            if (removedUsers == null) {
18364                broadcastUsers = null;
18365                return;
18366            }
18367
18368            broadcastUsers = EMPTY_INT_ARRAY;
18369            for (int i = userIds.length - 1; i >= 0; --i) {
18370                final int userId = userIds[i];
18371                if (deletedPackageSetting.getInstantApp(userId)) {
18372                    continue;
18373                }
18374                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18375            }
18376        }
18377    }
18378
18379    /*
18380     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18381     * flag is not set, the data directory is removed as well.
18382     * make sure this flag is set for partially installed apps. If not its meaningless to
18383     * delete a partially installed application.
18384     */
18385    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18386            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18387        String packageName = ps.name;
18388        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18389        // Retrieve object to delete permissions for shared user later on
18390        final PackageParser.Package deletedPkg;
18391        final PackageSetting deletedPs;
18392        // reader
18393        synchronized (mPackages) {
18394            deletedPkg = mPackages.get(packageName);
18395            deletedPs = mSettings.mPackages.get(packageName);
18396            if (outInfo != null) {
18397                outInfo.removedPackage = packageName;
18398                outInfo.installerPackageName = ps.installerPackageName;
18399                outInfo.isStaticSharedLib = deletedPkg != null
18400                        && deletedPkg.staticSharedLibName != null;
18401                outInfo.populateUsers(deletedPs == null ? null
18402                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18403            }
18404        }
18405
18406        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18407
18408        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18409            final PackageParser.Package resolvedPkg;
18410            if (deletedPkg != null) {
18411                resolvedPkg = deletedPkg;
18412            } else {
18413                // We don't have a parsed package when it lives on an ejected
18414                // adopted storage device, so fake something together
18415                resolvedPkg = new PackageParser.Package(ps.name);
18416                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18417            }
18418            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18419                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18420            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18421            if (outInfo != null) {
18422                outInfo.dataRemoved = true;
18423            }
18424            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18425        }
18426
18427        int removedAppId = -1;
18428
18429        // writer
18430        synchronized (mPackages) {
18431            boolean installedStateChanged = false;
18432            if (deletedPs != null) {
18433                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18434                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18435                    clearDefaultBrowserIfNeeded(packageName);
18436                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18437                    removedAppId = mSettings.removePackageLPw(packageName);
18438                    if (outInfo != null) {
18439                        outInfo.removedAppId = removedAppId;
18440                    }
18441                    updatePermissionsLPw(deletedPs.name, null, 0);
18442                    if (deletedPs.sharedUser != null) {
18443                        // Remove permissions associated with package. Since runtime
18444                        // permissions are per user we have to kill the removed package
18445                        // or packages running under the shared user of the removed
18446                        // package if revoking the permissions requested only by the removed
18447                        // package is successful and this causes a change in gids.
18448                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18449                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18450                                    userId);
18451                            if (userIdToKill == UserHandle.USER_ALL
18452                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18453                                // If gids changed for this user, kill all affected packages.
18454                                mHandler.post(new Runnable() {
18455                                    @Override
18456                                    public void run() {
18457                                        // This has to happen with no lock held.
18458                                        killApplication(deletedPs.name, deletedPs.appId,
18459                                                KILL_APP_REASON_GIDS_CHANGED);
18460                                    }
18461                                });
18462                                break;
18463                            }
18464                        }
18465                    }
18466                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18467                }
18468                // make sure to preserve per-user disabled state if this removal was just
18469                // a downgrade of a system app to the factory package
18470                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18471                    if (DEBUG_REMOVE) {
18472                        Slog.d(TAG, "Propagating install state across downgrade");
18473                    }
18474                    for (int userId : allUserHandles) {
18475                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18476                        if (DEBUG_REMOVE) {
18477                            Slog.d(TAG, "    user " + userId + " => " + installed);
18478                        }
18479                        if (installed != ps.getInstalled(userId)) {
18480                            installedStateChanged = true;
18481                        }
18482                        ps.setInstalled(installed, userId);
18483                    }
18484                }
18485            }
18486            // can downgrade to reader
18487            if (writeSettings) {
18488                // Save settings now
18489                mSettings.writeLPr();
18490            }
18491            if (installedStateChanged) {
18492                mSettings.writeKernelMappingLPr(ps);
18493            }
18494        }
18495        if (removedAppId != -1) {
18496            // A user ID was deleted here. Go through all users and remove it
18497            // from KeyStore.
18498            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18499        }
18500    }
18501
18502    static boolean locationIsPrivileged(File path) {
18503        try {
18504            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18505                    .getCanonicalPath();
18506            return path.getCanonicalPath().startsWith(privilegedAppDir);
18507        } catch (IOException e) {
18508            Slog.e(TAG, "Unable to access code path " + path);
18509        }
18510        return false;
18511    }
18512
18513    static boolean locationIsOem(File path) {
18514        try {
18515            return path.getCanonicalPath().startsWith(
18516                    Environment.getOemDirectory().getCanonicalPath());
18517        } catch (IOException e) {
18518            Slog.e(TAG, "Unable to access code path " + path);
18519        }
18520        return false;
18521    }
18522
18523    /*
18524     * Tries to delete system package.
18525     */
18526    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18527            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18528            boolean writeSettings) {
18529        if (deletedPs.parentPackageName != null) {
18530            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18531            return false;
18532        }
18533
18534        final boolean applyUserRestrictions
18535                = (allUserHandles != null) && (outInfo.origUsers != null);
18536        final PackageSetting disabledPs;
18537        // Confirm if the system package has been updated
18538        // An updated system app can be deleted. This will also have to restore
18539        // the system pkg from system partition
18540        // reader
18541        synchronized (mPackages) {
18542            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18543        }
18544
18545        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18546                + " disabledPs=" + disabledPs);
18547
18548        if (disabledPs == null) {
18549            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18550            return false;
18551        } else if (DEBUG_REMOVE) {
18552            Slog.d(TAG, "Deleting system pkg from data partition");
18553        }
18554
18555        if (DEBUG_REMOVE) {
18556            if (applyUserRestrictions) {
18557                Slog.d(TAG, "Remembering install states:");
18558                for (int userId : allUserHandles) {
18559                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18560                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18561                }
18562            }
18563        }
18564
18565        // Delete the updated package
18566        outInfo.isRemovedPackageSystemUpdate = true;
18567        if (outInfo.removedChildPackages != null) {
18568            final int childCount = (deletedPs.childPackageNames != null)
18569                    ? deletedPs.childPackageNames.size() : 0;
18570            for (int i = 0; i < childCount; i++) {
18571                String childPackageName = deletedPs.childPackageNames.get(i);
18572                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18573                        .contains(childPackageName)) {
18574                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18575                            childPackageName);
18576                    if (childInfo != null) {
18577                        childInfo.isRemovedPackageSystemUpdate = true;
18578                    }
18579                }
18580            }
18581        }
18582
18583        if (disabledPs.versionCode < deletedPs.versionCode) {
18584            // Delete data for downgrades
18585            flags &= ~PackageManager.DELETE_KEEP_DATA;
18586        } else {
18587            // Preserve data by setting flag
18588            flags |= PackageManager.DELETE_KEEP_DATA;
18589        }
18590
18591        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18592                outInfo, writeSettings, disabledPs.pkg);
18593        if (!ret) {
18594            return false;
18595        }
18596
18597        // writer
18598        synchronized (mPackages) {
18599            // NOTE: The system package always needs to be enabled; even if it's for
18600            // a compressed stub. If we don't, installing the system package fails
18601            // during scan [scanning checks the disabled packages]. We will reverse
18602            // this later, after we've "installed" the stub.
18603            // Reinstate the old system package
18604            enableSystemPackageLPw(disabledPs.pkg);
18605            // Remove any native libraries from the upgraded package.
18606            removeNativeBinariesLI(deletedPs);
18607        }
18608
18609        // Install the system package
18610        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18611        try {
18612            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18613                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18614        } catch (PackageManagerException e) {
18615            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18616                    + e.getMessage());
18617            return false;
18618        } finally {
18619            if (disabledPs.pkg.isStub) {
18620                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18621            }
18622        }
18623        return true;
18624    }
18625
18626    /**
18627     * Installs a package that's already on the system partition.
18628     */
18629    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18630            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18631            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18632                    throws PackageManagerException {
18633        int parseFlags = mDefParseFlags
18634                | PackageParser.PARSE_MUST_BE_APK
18635                | PackageParser.PARSE_IS_SYSTEM
18636                | PackageParser.PARSE_IS_SYSTEM_DIR;
18637        if (isPrivileged || locationIsPrivileged(codePath)) {
18638            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18639        }
18640        if (locationIsOem(codePath)) {
18641            parseFlags |= PackageParser.PARSE_IS_OEM;
18642        }
18643
18644        final PackageParser.Package newPkg =
18645                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18646
18647        try {
18648            // update shared libraries for the newly re-installed system package
18649            updateSharedLibrariesLPr(newPkg, null);
18650        } catch (PackageManagerException e) {
18651            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18652        }
18653
18654        prepareAppDataAfterInstallLIF(newPkg);
18655
18656        // writer
18657        synchronized (mPackages) {
18658            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18659
18660            // Propagate the permissions state as we do not want to drop on the floor
18661            // runtime permissions. The update permissions method below will take
18662            // care of removing obsolete permissions and grant install permissions.
18663            if (origPermissionState != null) {
18664                ps.getPermissionsState().copyFrom(origPermissionState);
18665            }
18666            updatePermissionsLPw(newPkg.packageName, newPkg,
18667                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18668
18669            final boolean applyUserRestrictions
18670                    = (allUserHandles != null) && (origUserHandles != null);
18671            if (applyUserRestrictions) {
18672                boolean installedStateChanged = false;
18673                if (DEBUG_REMOVE) {
18674                    Slog.d(TAG, "Propagating install state across reinstall");
18675                }
18676                for (int userId : allUserHandles) {
18677                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18678                    if (DEBUG_REMOVE) {
18679                        Slog.d(TAG, "    user " + userId + " => " + installed);
18680                    }
18681                    if (installed != ps.getInstalled(userId)) {
18682                        installedStateChanged = true;
18683                    }
18684                    ps.setInstalled(installed, userId);
18685
18686                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18687                }
18688                // Regardless of writeSettings we need to ensure that this restriction
18689                // state propagation is persisted
18690                mSettings.writeAllUsersPackageRestrictionsLPr();
18691                if (installedStateChanged) {
18692                    mSettings.writeKernelMappingLPr(ps);
18693                }
18694            }
18695            // can downgrade to reader here
18696            if (writeSettings) {
18697                mSettings.writeLPr();
18698            }
18699        }
18700        return newPkg;
18701    }
18702
18703    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18704            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18705            PackageRemovedInfo outInfo, boolean writeSettings,
18706            PackageParser.Package replacingPackage) {
18707        synchronized (mPackages) {
18708            if (outInfo != null) {
18709                outInfo.uid = ps.appId;
18710            }
18711
18712            if (outInfo != null && outInfo.removedChildPackages != null) {
18713                final int childCount = (ps.childPackageNames != null)
18714                        ? ps.childPackageNames.size() : 0;
18715                for (int i = 0; i < childCount; i++) {
18716                    String childPackageName = ps.childPackageNames.get(i);
18717                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18718                    if (childPs == null) {
18719                        return false;
18720                    }
18721                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18722                            childPackageName);
18723                    if (childInfo != null) {
18724                        childInfo.uid = childPs.appId;
18725                    }
18726                }
18727            }
18728        }
18729
18730        // Delete package data from internal structures and also remove data if flag is set
18731        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18732
18733        // Delete the child packages data
18734        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18735        for (int i = 0; i < childCount; i++) {
18736            PackageSetting childPs;
18737            synchronized (mPackages) {
18738                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18739            }
18740            if (childPs != null) {
18741                PackageRemovedInfo childOutInfo = (outInfo != null
18742                        && outInfo.removedChildPackages != null)
18743                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18744                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18745                        && (replacingPackage != null
18746                        && !replacingPackage.hasChildPackage(childPs.name))
18747                        ? flags & ~DELETE_KEEP_DATA : flags;
18748                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18749                        deleteFlags, writeSettings);
18750            }
18751        }
18752
18753        // Delete application code and resources only for parent packages
18754        if (ps.parentPackageName == null) {
18755            if (deleteCodeAndResources && (outInfo != null)) {
18756                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18757                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18758                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18759            }
18760        }
18761
18762        return true;
18763    }
18764
18765    @Override
18766    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18767            int userId) {
18768        mContext.enforceCallingOrSelfPermission(
18769                android.Manifest.permission.DELETE_PACKAGES, null);
18770        synchronized (mPackages) {
18771            // Cannot block uninstall of static shared libs as they are
18772            // considered a part of the using app (emulating static linking).
18773            // Also static libs are installed always on internal storage.
18774            PackageParser.Package pkg = mPackages.get(packageName);
18775            if (pkg != null && pkg.staticSharedLibName != null) {
18776                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18777                        + " providing static shared library: " + pkg.staticSharedLibName);
18778                return false;
18779            }
18780            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18781            mSettings.writePackageRestrictionsLPr(userId);
18782        }
18783        return true;
18784    }
18785
18786    @Override
18787    public boolean getBlockUninstallForUser(String packageName, int userId) {
18788        synchronized (mPackages) {
18789            final PackageSetting ps = mSettings.mPackages.get(packageName);
18790            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18791                return false;
18792            }
18793            return mSettings.getBlockUninstallLPr(userId, packageName);
18794        }
18795    }
18796
18797    @Override
18798    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18799        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18800        synchronized (mPackages) {
18801            PackageSetting ps = mSettings.mPackages.get(packageName);
18802            if (ps == null) {
18803                Log.w(TAG, "Package doesn't exist: " + packageName);
18804                return false;
18805            }
18806            if (systemUserApp) {
18807                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18808            } else {
18809                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18810            }
18811            mSettings.writeLPr();
18812        }
18813        return true;
18814    }
18815
18816    /*
18817     * This method handles package deletion in general
18818     */
18819    private boolean deletePackageLIF(String packageName, UserHandle user,
18820            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18821            PackageRemovedInfo outInfo, boolean writeSettings,
18822            PackageParser.Package replacingPackage) {
18823        if (packageName == null) {
18824            Slog.w(TAG, "Attempt to delete null packageName.");
18825            return false;
18826        }
18827
18828        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18829
18830        PackageSetting ps;
18831        synchronized (mPackages) {
18832            ps = mSettings.mPackages.get(packageName);
18833            if (ps == null) {
18834                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18835                return false;
18836            }
18837
18838            if (ps.parentPackageName != null && (!isSystemApp(ps)
18839                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18840                if (DEBUG_REMOVE) {
18841                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18842                            + ((user == null) ? UserHandle.USER_ALL : user));
18843                }
18844                final int removedUserId = (user != null) ? user.getIdentifier()
18845                        : UserHandle.USER_ALL;
18846                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18847                    return false;
18848                }
18849                markPackageUninstalledForUserLPw(ps, user);
18850                scheduleWritePackageRestrictionsLocked(user);
18851                return true;
18852            }
18853        }
18854
18855        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18856                && user.getIdentifier() != UserHandle.USER_ALL)) {
18857            // The caller is asking that the package only be deleted for a single
18858            // user.  To do this, we just mark its uninstalled state and delete
18859            // its data. If this is a system app, we only allow this to happen if
18860            // they have set the special DELETE_SYSTEM_APP which requests different
18861            // semantics than normal for uninstalling system apps.
18862            markPackageUninstalledForUserLPw(ps, user);
18863
18864            if (!isSystemApp(ps)) {
18865                // Do not uninstall the APK if an app should be cached
18866                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18867                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18868                    // Other user still have this package installed, so all
18869                    // we need to do is clear this user's data and save that
18870                    // it is uninstalled.
18871                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18872                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18873                        return false;
18874                    }
18875                    scheduleWritePackageRestrictionsLocked(user);
18876                    return true;
18877                } else {
18878                    // We need to set it back to 'installed' so the uninstall
18879                    // broadcasts will be sent correctly.
18880                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18881                    ps.setInstalled(true, user.getIdentifier());
18882                    mSettings.writeKernelMappingLPr(ps);
18883                }
18884            } else {
18885                // This is a system app, so we assume that the
18886                // other users still have this package installed, so all
18887                // we need to do is clear this user's data and save that
18888                // it is uninstalled.
18889                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18890                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18891                    return false;
18892                }
18893                scheduleWritePackageRestrictionsLocked(user);
18894                return true;
18895            }
18896        }
18897
18898        // If we are deleting a composite package for all users, keep track
18899        // of result for each child.
18900        if (ps.childPackageNames != null && outInfo != null) {
18901            synchronized (mPackages) {
18902                final int childCount = ps.childPackageNames.size();
18903                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18904                for (int i = 0; i < childCount; i++) {
18905                    String childPackageName = ps.childPackageNames.get(i);
18906                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18907                    childInfo.removedPackage = childPackageName;
18908                    childInfo.installerPackageName = ps.installerPackageName;
18909                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18910                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18911                    if (childPs != null) {
18912                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18913                    }
18914                }
18915            }
18916        }
18917
18918        boolean ret = false;
18919        if (isSystemApp(ps)) {
18920            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18921            // When an updated system application is deleted we delete the existing resources
18922            // as well and fall back to existing code in system partition
18923            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18924        } else {
18925            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18926            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18927                    outInfo, writeSettings, replacingPackage);
18928        }
18929
18930        // Take a note whether we deleted the package for all users
18931        if (outInfo != null) {
18932            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18933            if (outInfo.removedChildPackages != null) {
18934                synchronized (mPackages) {
18935                    final int childCount = outInfo.removedChildPackages.size();
18936                    for (int i = 0; i < childCount; i++) {
18937                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18938                        if (childInfo != null) {
18939                            childInfo.removedForAllUsers = mPackages.get(
18940                                    childInfo.removedPackage) == null;
18941                        }
18942                    }
18943                }
18944            }
18945            // If we uninstalled an update to a system app there may be some
18946            // child packages that appeared as they are declared in the system
18947            // app but were not declared in the update.
18948            if (isSystemApp(ps)) {
18949                synchronized (mPackages) {
18950                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18951                    final int childCount = (updatedPs.childPackageNames != null)
18952                            ? updatedPs.childPackageNames.size() : 0;
18953                    for (int i = 0; i < childCount; i++) {
18954                        String childPackageName = updatedPs.childPackageNames.get(i);
18955                        if (outInfo.removedChildPackages == null
18956                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18957                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18958                            if (childPs == null) {
18959                                continue;
18960                            }
18961                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18962                            installRes.name = childPackageName;
18963                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18964                            installRes.pkg = mPackages.get(childPackageName);
18965                            installRes.uid = childPs.pkg.applicationInfo.uid;
18966                            if (outInfo.appearedChildPackages == null) {
18967                                outInfo.appearedChildPackages = new ArrayMap<>();
18968                            }
18969                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18970                        }
18971                    }
18972                }
18973            }
18974        }
18975
18976        return ret;
18977    }
18978
18979    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18980        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18981                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18982        for (int nextUserId : userIds) {
18983            if (DEBUG_REMOVE) {
18984                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18985            }
18986            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18987                    false /*installed*/,
18988                    true /*stopped*/,
18989                    true /*notLaunched*/,
18990                    false /*hidden*/,
18991                    false /*suspended*/,
18992                    false /*instantApp*/,
18993                    false /*virtualPreload*/,
18994                    null /*lastDisableAppCaller*/,
18995                    null /*enabledComponents*/,
18996                    null /*disabledComponents*/,
18997                    ps.readUserState(nextUserId).domainVerificationStatus,
18998                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18999        }
19000        mSettings.writeKernelMappingLPr(ps);
19001    }
19002
19003    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19004            PackageRemovedInfo outInfo) {
19005        final PackageParser.Package pkg;
19006        synchronized (mPackages) {
19007            pkg = mPackages.get(ps.name);
19008        }
19009
19010        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19011                : new int[] {userId};
19012        for (int nextUserId : userIds) {
19013            if (DEBUG_REMOVE) {
19014                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19015                        + nextUserId);
19016            }
19017
19018            destroyAppDataLIF(pkg, userId,
19019                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19020            destroyAppProfilesLIF(pkg, userId);
19021            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19022            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19023            schedulePackageCleaning(ps.name, nextUserId, false);
19024            synchronized (mPackages) {
19025                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19026                    scheduleWritePackageRestrictionsLocked(nextUserId);
19027                }
19028                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19029            }
19030        }
19031
19032        if (outInfo != null) {
19033            outInfo.removedPackage = ps.name;
19034            outInfo.installerPackageName = ps.installerPackageName;
19035            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19036            outInfo.removedAppId = ps.appId;
19037            outInfo.removedUsers = userIds;
19038            outInfo.broadcastUsers = userIds;
19039        }
19040
19041        return true;
19042    }
19043
19044    private final class ClearStorageConnection implements ServiceConnection {
19045        IMediaContainerService mContainerService;
19046
19047        @Override
19048        public void onServiceConnected(ComponentName name, IBinder service) {
19049            synchronized (this) {
19050                mContainerService = IMediaContainerService.Stub
19051                        .asInterface(Binder.allowBlocking(service));
19052                notifyAll();
19053            }
19054        }
19055
19056        @Override
19057        public void onServiceDisconnected(ComponentName name) {
19058        }
19059    }
19060
19061    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19062        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19063
19064        final boolean mounted;
19065        if (Environment.isExternalStorageEmulated()) {
19066            mounted = true;
19067        } else {
19068            final String status = Environment.getExternalStorageState();
19069
19070            mounted = status.equals(Environment.MEDIA_MOUNTED)
19071                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19072        }
19073
19074        if (!mounted) {
19075            return;
19076        }
19077
19078        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19079        int[] users;
19080        if (userId == UserHandle.USER_ALL) {
19081            users = sUserManager.getUserIds();
19082        } else {
19083            users = new int[] { userId };
19084        }
19085        final ClearStorageConnection conn = new ClearStorageConnection();
19086        if (mContext.bindServiceAsUser(
19087                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19088            try {
19089                for (int curUser : users) {
19090                    long timeout = SystemClock.uptimeMillis() + 5000;
19091                    synchronized (conn) {
19092                        long now;
19093                        while (conn.mContainerService == null &&
19094                                (now = SystemClock.uptimeMillis()) < timeout) {
19095                            try {
19096                                conn.wait(timeout - now);
19097                            } catch (InterruptedException e) {
19098                            }
19099                        }
19100                    }
19101                    if (conn.mContainerService == null) {
19102                        return;
19103                    }
19104
19105                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19106                    clearDirectory(conn.mContainerService,
19107                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19108                    if (allData) {
19109                        clearDirectory(conn.mContainerService,
19110                                userEnv.buildExternalStorageAppDataDirs(packageName));
19111                        clearDirectory(conn.mContainerService,
19112                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19113                    }
19114                }
19115            } finally {
19116                mContext.unbindService(conn);
19117            }
19118        }
19119    }
19120
19121    @Override
19122    public void clearApplicationProfileData(String packageName) {
19123        enforceSystemOrRoot("Only the system can clear all profile data");
19124
19125        final PackageParser.Package pkg;
19126        synchronized (mPackages) {
19127            pkg = mPackages.get(packageName);
19128        }
19129
19130        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19131            synchronized (mInstallLock) {
19132                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19133            }
19134        }
19135    }
19136
19137    @Override
19138    public void clearApplicationUserData(final String packageName,
19139            final IPackageDataObserver observer, final int userId) {
19140        mContext.enforceCallingOrSelfPermission(
19141                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19142
19143        final int callingUid = Binder.getCallingUid();
19144        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19145                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19146
19147        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19148        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19149        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19150            throw new SecurityException("Cannot clear data for a protected package: "
19151                    + packageName);
19152        }
19153        // Queue up an async operation since the package deletion may take a little while.
19154        mHandler.post(new Runnable() {
19155            public void run() {
19156                mHandler.removeCallbacks(this);
19157                final boolean succeeded;
19158                if (!filterApp) {
19159                    try (PackageFreezer freezer = freezePackage(packageName,
19160                            "clearApplicationUserData")) {
19161                        synchronized (mInstallLock) {
19162                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19163                        }
19164                        clearExternalStorageDataSync(packageName, userId, true);
19165                        synchronized (mPackages) {
19166                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19167                                    packageName, userId);
19168                        }
19169                    }
19170                    if (succeeded) {
19171                        // invoke DeviceStorageMonitor's update method to clear any notifications
19172                        DeviceStorageMonitorInternal dsm = LocalServices
19173                                .getService(DeviceStorageMonitorInternal.class);
19174                        if (dsm != null) {
19175                            dsm.checkMemory();
19176                        }
19177                    }
19178                } else {
19179                    succeeded = false;
19180                }
19181                if (observer != null) {
19182                    try {
19183                        observer.onRemoveCompleted(packageName, succeeded);
19184                    } catch (RemoteException e) {
19185                        Log.i(TAG, "Observer no longer exists.");
19186                    }
19187                } //end if observer
19188            } //end run
19189        });
19190    }
19191
19192    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19193        if (packageName == null) {
19194            Slog.w(TAG, "Attempt to delete null packageName.");
19195            return false;
19196        }
19197
19198        // Try finding details about the requested package
19199        PackageParser.Package pkg;
19200        synchronized (mPackages) {
19201            pkg = mPackages.get(packageName);
19202            if (pkg == null) {
19203                final PackageSetting ps = mSettings.mPackages.get(packageName);
19204                if (ps != null) {
19205                    pkg = ps.pkg;
19206                }
19207            }
19208
19209            if (pkg == null) {
19210                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19211                return false;
19212            }
19213
19214            PackageSetting ps = (PackageSetting) pkg.mExtras;
19215            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19216        }
19217
19218        clearAppDataLIF(pkg, userId,
19219                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19220
19221        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19222        removeKeystoreDataIfNeeded(userId, appId);
19223
19224        UserManagerInternal umInternal = getUserManagerInternal();
19225        final int flags;
19226        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19227            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19228        } else if (umInternal.isUserRunning(userId)) {
19229            flags = StorageManager.FLAG_STORAGE_DE;
19230        } else {
19231            flags = 0;
19232        }
19233        prepareAppDataContentsLIF(pkg, userId, flags);
19234
19235        return true;
19236    }
19237
19238    /**
19239     * Reverts user permission state changes (permissions and flags) in
19240     * all packages for a given user.
19241     *
19242     * @param userId The device user for which to do a reset.
19243     */
19244    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19245        final int packageCount = mPackages.size();
19246        for (int i = 0; i < packageCount; i++) {
19247            PackageParser.Package pkg = mPackages.valueAt(i);
19248            PackageSetting ps = (PackageSetting) pkg.mExtras;
19249            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19250        }
19251    }
19252
19253    private void resetNetworkPolicies(int userId) {
19254        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19255    }
19256
19257    /**
19258     * Reverts user permission state changes (permissions and flags).
19259     *
19260     * @param ps The package for which to reset.
19261     * @param userId The device user for which to do a reset.
19262     */
19263    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19264            final PackageSetting ps, final int userId) {
19265        if (ps.pkg == null) {
19266            return;
19267        }
19268
19269        // These are flags that can change base on user actions.
19270        final int userSettableMask = FLAG_PERMISSION_USER_SET
19271                | FLAG_PERMISSION_USER_FIXED
19272                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19273                | FLAG_PERMISSION_REVIEW_REQUIRED;
19274
19275        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19276                | FLAG_PERMISSION_POLICY_FIXED;
19277
19278        boolean writeInstallPermissions = false;
19279        boolean writeRuntimePermissions = false;
19280
19281        final int permissionCount = ps.pkg.requestedPermissions.size();
19282        for (int i = 0; i < permissionCount; i++) {
19283            final String permName = ps.pkg.requestedPermissions.get(i);
19284            final BasePermission bp =
19285                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19286            if (bp == null) {
19287                continue;
19288            }
19289
19290            // If shared user we just reset the state to which only this app contributed.
19291            if (ps.sharedUser != null) {
19292                boolean used = false;
19293                final int packageCount = ps.sharedUser.packages.size();
19294                for (int j = 0; j < packageCount; j++) {
19295                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19296                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19297                            && pkg.pkg.requestedPermissions.contains(permName)) {
19298                        used = true;
19299                        break;
19300                    }
19301                }
19302                if (used) {
19303                    continue;
19304                }
19305            }
19306
19307            final PermissionsState permissionsState = ps.getPermissionsState();
19308
19309            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19310
19311            // Always clear the user settable flags.
19312            final boolean hasInstallState =
19313                    permissionsState.getInstallPermissionState(permName) != null;
19314            // If permission review is enabled and this is a legacy app, mark the
19315            // permission as requiring a review as this is the initial state.
19316            int flags = 0;
19317            if (mPermissionReviewRequired
19318                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19319                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19320            }
19321            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19322                if (hasInstallState) {
19323                    writeInstallPermissions = true;
19324                } else {
19325                    writeRuntimePermissions = true;
19326                }
19327            }
19328
19329            // Below is only runtime permission handling.
19330            if (!bp.isRuntime()) {
19331                continue;
19332            }
19333
19334            // Never clobber system or policy.
19335            if ((oldFlags & policyOrSystemFlags) != 0) {
19336                continue;
19337            }
19338
19339            // If this permission was granted by default, make sure it is.
19340            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19341                if (permissionsState.grantRuntimePermission(bp, userId)
19342                        != PERMISSION_OPERATION_FAILURE) {
19343                    writeRuntimePermissions = true;
19344                }
19345            // If permission review is enabled the permissions for a legacy apps
19346            // are represented as constantly granted runtime ones, so don't revoke.
19347            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19348                // Otherwise, reset the permission.
19349                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19350                switch (revokeResult) {
19351                    case PERMISSION_OPERATION_SUCCESS:
19352                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19353                        writeRuntimePermissions = true;
19354                        final int appId = ps.appId;
19355                        mHandler.post(new Runnable() {
19356                            @Override
19357                            public void run() {
19358                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19359                            }
19360                        });
19361                    } break;
19362                }
19363            }
19364        }
19365
19366        // Synchronously write as we are taking permissions away.
19367        if (writeRuntimePermissions) {
19368            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19369        }
19370
19371        // Synchronously write as we are taking permissions away.
19372        if (writeInstallPermissions) {
19373            mSettings.writeLPr();
19374        }
19375    }
19376
19377    /**
19378     * Remove entries from the keystore daemon. Will only remove it if the
19379     * {@code appId} is valid.
19380     */
19381    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19382        if (appId < 0) {
19383            return;
19384        }
19385
19386        final KeyStore keyStore = KeyStore.getInstance();
19387        if (keyStore != null) {
19388            if (userId == UserHandle.USER_ALL) {
19389                for (final int individual : sUserManager.getUserIds()) {
19390                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19391                }
19392            } else {
19393                keyStore.clearUid(UserHandle.getUid(userId, appId));
19394            }
19395        } else {
19396            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19397        }
19398    }
19399
19400    @Override
19401    public void deleteApplicationCacheFiles(final String packageName,
19402            final IPackageDataObserver observer) {
19403        final int userId = UserHandle.getCallingUserId();
19404        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19405    }
19406
19407    @Override
19408    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19409            final IPackageDataObserver observer) {
19410        final int callingUid = Binder.getCallingUid();
19411        mContext.enforceCallingOrSelfPermission(
19412                android.Manifest.permission.DELETE_CACHE_FILES, null);
19413        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19414                /* requireFullPermission= */ true, /* checkShell= */ false,
19415                "delete application cache files");
19416        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19417                android.Manifest.permission.ACCESS_INSTANT_APPS);
19418
19419        final PackageParser.Package pkg;
19420        synchronized (mPackages) {
19421            pkg = mPackages.get(packageName);
19422        }
19423
19424        // Queue up an async operation since the package deletion may take a little while.
19425        mHandler.post(new Runnable() {
19426            public void run() {
19427                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19428                boolean doClearData = true;
19429                if (ps != null) {
19430                    final boolean targetIsInstantApp =
19431                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19432                    doClearData = !targetIsInstantApp
19433                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19434                }
19435                if (doClearData) {
19436                    synchronized (mInstallLock) {
19437                        final int flags = StorageManager.FLAG_STORAGE_DE
19438                                | StorageManager.FLAG_STORAGE_CE;
19439                        // We're only clearing cache files, so we don't care if the
19440                        // app is unfrozen and still able to run
19441                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19442                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19443                    }
19444                    clearExternalStorageDataSync(packageName, userId, false);
19445                }
19446                if (observer != null) {
19447                    try {
19448                        observer.onRemoveCompleted(packageName, true);
19449                    } catch (RemoteException e) {
19450                        Log.i(TAG, "Observer no longer exists.");
19451                    }
19452                }
19453            }
19454        });
19455    }
19456
19457    @Override
19458    public void getPackageSizeInfo(final String packageName, int userHandle,
19459            final IPackageStatsObserver observer) {
19460        throw new UnsupportedOperationException(
19461                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19462    }
19463
19464    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19465        final PackageSetting ps;
19466        synchronized (mPackages) {
19467            ps = mSettings.mPackages.get(packageName);
19468            if (ps == null) {
19469                Slog.w(TAG, "Failed to find settings for " + packageName);
19470                return false;
19471            }
19472        }
19473
19474        final String[] packageNames = { packageName };
19475        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19476        final String[] codePaths = { ps.codePathString };
19477
19478        try {
19479            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19480                    ps.appId, ceDataInodes, codePaths, stats);
19481
19482            // For now, ignore code size of packages on system partition
19483            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19484                stats.codeSize = 0;
19485            }
19486
19487            // External clients expect these to be tracked separately
19488            stats.dataSize -= stats.cacheSize;
19489
19490        } catch (InstallerException e) {
19491            Slog.w(TAG, String.valueOf(e));
19492            return false;
19493        }
19494
19495        return true;
19496    }
19497
19498    private int getUidTargetSdkVersionLockedLPr(int uid) {
19499        Object obj = mSettings.getUserIdLPr(uid);
19500        if (obj instanceof SharedUserSetting) {
19501            final SharedUserSetting sus = (SharedUserSetting) obj;
19502            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19503            final Iterator<PackageSetting> it = sus.packages.iterator();
19504            while (it.hasNext()) {
19505                final PackageSetting ps = it.next();
19506                if (ps.pkg != null) {
19507                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19508                    if (v < vers) vers = v;
19509                }
19510            }
19511            return vers;
19512        } else if (obj instanceof PackageSetting) {
19513            final PackageSetting ps = (PackageSetting) obj;
19514            if (ps.pkg != null) {
19515                return ps.pkg.applicationInfo.targetSdkVersion;
19516            }
19517        }
19518        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19519    }
19520
19521    @Override
19522    public void addPreferredActivity(IntentFilter filter, int match,
19523            ComponentName[] set, ComponentName activity, int userId) {
19524        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19525                "Adding preferred");
19526    }
19527
19528    private void addPreferredActivityInternal(IntentFilter filter, int match,
19529            ComponentName[] set, ComponentName activity, boolean always, int userId,
19530            String opname) {
19531        // writer
19532        int callingUid = Binder.getCallingUid();
19533        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19534                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19535        if (filter.countActions() == 0) {
19536            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19537            return;
19538        }
19539        synchronized (mPackages) {
19540            if (mContext.checkCallingOrSelfPermission(
19541                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19542                    != PackageManager.PERMISSION_GRANTED) {
19543                if (getUidTargetSdkVersionLockedLPr(callingUid)
19544                        < Build.VERSION_CODES.FROYO) {
19545                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19546                            + callingUid);
19547                    return;
19548                }
19549                mContext.enforceCallingOrSelfPermission(
19550                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19551            }
19552
19553            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19554            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19555                    + userId + ":");
19556            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19557            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19558            scheduleWritePackageRestrictionsLocked(userId);
19559            postPreferredActivityChangedBroadcast(userId);
19560        }
19561    }
19562
19563    private void postPreferredActivityChangedBroadcast(int userId) {
19564        mHandler.post(() -> {
19565            final IActivityManager am = ActivityManager.getService();
19566            if (am == null) {
19567                return;
19568            }
19569
19570            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19571            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19572            try {
19573                am.broadcastIntent(null, intent, null, null,
19574                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19575                        null, false, false, userId);
19576            } catch (RemoteException e) {
19577            }
19578        });
19579    }
19580
19581    @Override
19582    public void replacePreferredActivity(IntentFilter filter, int match,
19583            ComponentName[] set, ComponentName activity, int userId) {
19584        if (filter.countActions() != 1) {
19585            throw new IllegalArgumentException(
19586                    "replacePreferredActivity expects filter to have only 1 action.");
19587        }
19588        if (filter.countDataAuthorities() != 0
19589                || filter.countDataPaths() != 0
19590                || filter.countDataSchemes() > 1
19591                || filter.countDataTypes() != 0) {
19592            throw new IllegalArgumentException(
19593                    "replacePreferredActivity expects filter to have no data authorities, " +
19594                    "paths, or types; and at most one scheme.");
19595        }
19596
19597        final int callingUid = Binder.getCallingUid();
19598        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19599                true /* requireFullPermission */, false /* checkShell */,
19600                "replace preferred activity");
19601        synchronized (mPackages) {
19602            if (mContext.checkCallingOrSelfPermission(
19603                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19604                    != PackageManager.PERMISSION_GRANTED) {
19605                if (getUidTargetSdkVersionLockedLPr(callingUid)
19606                        < Build.VERSION_CODES.FROYO) {
19607                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19608                            + Binder.getCallingUid());
19609                    return;
19610                }
19611                mContext.enforceCallingOrSelfPermission(
19612                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19613            }
19614
19615            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19616            if (pir != null) {
19617                // Get all of the existing entries that exactly match this filter.
19618                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19619                if (existing != null && existing.size() == 1) {
19620                    PreferredActivity cur = existing.get(0);
19621                    if (DEBUG_PREFERRED) {
19622                        Slog.i(TAG, "Checking replace of preferred:");
19623                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19624                        if (!cur.mPref.mAlways) {
19625                            Slog.i(TAG, "  -- CUR; not mAlways!");
19626                        } else {
19627                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19628                            Slog.i(TAG, "  -- CUR: mSet="
19629                                    + Arrays.toString(cur.mPref.mSetComponents));
19630                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19631                            Slog.i(TAG, "  -- NEW: mMatch="
19632                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19633                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19634                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19635                        }
19636                    }
19637                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19638                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19639                            && cur.mPref.sameSet(set)) {
19640                        // Setting the preferred activity to what it happens to be already
19641                        if (DEBUG_PREFERRED) {
19642                            Slog.i(TAG, "Replacing with same preferred activity "
19643                                    + cur.mPref.mShortComponent + " for user "
19644                                    + userId + ":");
19645                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19646                        }
19647                        return;
19648                    }
19649                }
19650
19651                if (existing != null) {
19652                    if (DEBUG_PREFERRED) {
19653                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19654                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19655                    }
19656                    for (int i = 0; i < existing.size(); i++) {
19657                        PreferredActivity pa = existing.get(i);
19658                        if (DEBUG_PREFERRED) {
19659                            Slog.i(TAG, "Removing existing preferred activity "
19660                                    + pa.mPref.mComponent + ":");
19661                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19662                        }
19663                        pir.removeFilter(pa);
19664                    }
19665                }
19666            }
19667            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19668                    "Replacing preferred");
19669        }
19670    }
19671
19672    @Override
19673    public void clearPackagePreferredActivities(String packageName) {
19674        final int callingUid = Binder.getCallingUid();
19675        if (getInstantAppPackageName(callingUid) != null) {
19676            return;
19677        }
19678        // writer
19679        synchronized (mPackages) {
19680            PackageParser.Package pkg = mPackages.get(packageName);
19681            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19682                if (mContext.checkCallingOrSelfPermission(
19683                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19684                        != PackageManager.PERMISSION_GRANTED) {
19685                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19686                            < Build.VERSION_CODES.FROYO) {
19687                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19688                                + callingUid);
19689                        return;
19690                    }
19691                    mContext.enforceCallingOrSelfPermission(
19692                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19693                }
19694            }
19695            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19696            if (ps != null
19697                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19698                return;
19699            }
19700            int user = UserHandle.getCallingUserId();
19701            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19702                scheduleWritePackageRestrictionsLocked(user);
19703            }
19704        }
19705    }
19706
19707    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19708    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19709        ArrayList<PreferredActivity> removed = null;
19710        boolean changed = false;
19711        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19712            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19713            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19714            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19715                continue;
19716            }
19717            Iterator<PreferredActivity> it = pir.filterIterator();
19718            while (it.hasNext()) {
19719                PreferredActivity pa = it.next();
19720                // Mark entry for removal only if it matches the package name
19721                // and the entry is of type "always".
19722                if (packageName == null ||
19723                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19724                                && pa.mPref.mAlways)) {
19725                    if (removed == null) {
19726                        removed = new ArrayList<PreferredActivity>();
19727                    }
19728                    removed.add(pa);
19729                }
19730            }
19731            if (removed != null) {
19732                for (int j=0; j<removed.size(); j++) {
19733                    PreferredActivity pa = removed.get(j);
19734                    pir.removeFilter(pa);
19735                }
19736                changed = true;
19737            }
19738        }
19739        if (changed) {
19740            postPreferredActivityChangedBroadcast(userId);
19741        }
19742        return changed;
19743    }
19744
19745    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19746    private void clearIntentFilterVerificationsLPw(int userId) {
19747        final int packageCount = mPackages.size();
19748        for (int i = 0; i < packageCount; i++) {
19749            PackageParser.Package pkg = mPackages.valueAt(i);
19750            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19751        }
19752    }
19753
19754    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19755    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19756        if (userId == UserHandle.USER_ALL) {
19757            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19758                    sUserManager.getUserIds())) {
19759                for (int oneUserId : sUserManager.getUserIds()) {
19760                    scheduleWritePackageRestrictionsLocked(oneUserId);
19761                }
19762            }
19763        } else {
19764            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19765                scheduleWritePackageRestrictionsLocked(userId);
19766            }
19767        }
19768    }
19769
19770    /** Clears state for all users, and touches intent filter verification policy */
19771    void clearDefaultBrowserIfNeeded(String packageName) {
19772        for (int oneUserId : sUserManager.getUserIds()) {
19773            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19774        }
19775    }
19776
19777    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19778        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19779        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19780            if (packageName.equals(defaultBrowserPackageName)) {
19781                setDefaultBrowserPackageName(null, userId);
19782            }
19783        }
19784    }
19785
19786    @Override
19787    public void resetApplicationPreferences(int userId) {
19788        mContext.enforceCallingOrSelfPermission(
19789                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19790        final long identity = Binder.clearCallingIdentity();
19791        // writer
19792        try {
19793            synchronized (mPackages) {
19794                clearPackagePreferredActivitiesLPw(null, userId);
19795                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19796                // TODO: We have to reset the default SMS and Phone. This requires
19797                // significant refactoring to keep all default apps in the package
19798                // manager (cleaner but more work) or have the services provide
19799                // callbacks to the package manager to request a default app reset.
19800                applyFactoryDefaultBrowserLPw(userId);
19801                clearIntentFilterVerificationsLPw(userId);
19802                primeDomainVerificationsLPw(userId);
19803                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19804                scheduleWritePackageRestrictionsLocked(userId);
19805            }
19806            resetNetworkPolicies(userId);
19807        } finally {
19808            Binder.restoreCallingIdentity(identity);
19809        }
19810    }
19811
19812    @Override
19813    public int getPreferredActivities(List<IntentFilter> outFilters,
19814            List<ComponentName> outActivities, String packageName) {
19815        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19816            return 0;
19817        }
19818        int num = 0;
19819        final int userId = UserHandle.getCallingUserId();
19820        // reader
19821        synchronized (mPackages) {
19822            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19823            if (pir != null) {
19824                final Iterator<PreferredActivity> it = pir.filterIterator();
19825                while (it.hasNext()) {
19826                    final PreferredActivity pa = it.next();
19827                    if (packageName == null
19828                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19829                                    && pa.mPref.mAlways)) {
19830                        if (outFilters != null) {
19831                            outFilters.add(new IntentFilter(pa));
19832                        }
19833                        if (outActivities != null) {
19834                            outActivities.add(pa.mPref.mComponent);
19835                        }
19836                    }
19837                }
19838            }
19839        }
19840
19841        return num;
19842    }
19843
19844    @Override
19845    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19846            int userId) {
19847        int callingUid = Binder.getCallingUid();
19848        if (callingUid != Process.SYSTEM_UID) {
19849            throw new SecurityException(
19850                    "addPersistentPreferredActivity can only be run by the system");
19851        }
19852        if (filter.countActions() == 0) {
19853            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19854            return;
19855        }
19856        synchronized (mPackages) {
19857            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19858                    ":");
19859            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19860            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19861                    new PersistentPreferredActivity(filter, activity));
19862            scheduleWritePackageRestrictionsLocked(userId);
19863            postPreferredActivityChangedBroadcast(userId);
19864        }
19865    }
19866
19867    @Override
19868    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19869        int callingUid = Binder.getCallingUid();
19870        if (callingUid != Process.SYSTEM_UID) {
19871            throw new SecurityException(
19872                    "clearPackagePersistentPreferredActivities can only be run by the system");
19873        }
19874        ArrayList<PersistentPreferredActivity> removed = null;
19875        boolean changed = false;
19876        synchronized (mPackages) {
19877            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19878                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19879                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19880                        .valueAt(i);
19881                if (userId != thisUserId) {
19882                    continue;
19883                }
19884                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19885                while (it.hasNext()) {
19886                    PersistentPreferredActivity ppa = it.next();
19887                    // Mark entry for removal only if it matches the package name.
19888                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19889                        if (removed == null) {
19890                            removed = new ArrayList<PersistentPreferredActivity>();
19891                        }
19892                        removed.add(ppa);
19893                    }
19894                }
19895                if (removed != null) {
19896                    for (int j=0; j<removed.size(); j++) {
19897                        PersistentPreferredActivity ppa = removed.get(j);
19898                        ppir.removeFilter(ppa);
19899                    }
19900                    changed = true;
19901                }
19902            }
19903
19904            if (changed) {
19905                scheduleWritePackageRestrictionsLocked(userId);
19906                postPreferredActivityChangedBroadcast(userId);
19907            }
19908        }
19909    }
19910
19911    /**
19912     * Common machinery for picking apart a restored XML blob and passing
19913     * it to a caller-supplied functor to be applied to the running system.
19914     */
19915    private void restoreFromXml(XmlPullParser parser, int userId,
19916            String expectedStartTag, BlobXmlRestorer functor)
19917            throws IOException, XmlPullParserException {
19918        int type;
19919        while ((type = parser.next()) != XmlPullParser.START_TAG
19920                && type != XmlPullParser.END_DOCUMENT) {
19921        }
19922        if (type != XmlPullParser.START_TAG) {
19923            // oops didn't find a start tag?!
19924            if (DEBUG_BACKUP) {
19925                Slog.e(TAG, "Didn't find start tag during restore");
19926            }
19927            return;
19928        }
19929Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19930        // this is supposed to be TAG_PREFERRED_BACKUP
19931        if (!expectedStartTag.equals(parser.getName())) {
19932            if (DEBUG_BACKUP) {
19933                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19934            }
19935            return;
19936        }
19937
19938        // skip interfering stuff, then we're aligned with the backing implementation
19939        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19940Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19941        functor.apply(parser, userId);
19942    }
19943
19944    private interface BlobXmlRestorer {
19945        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19946    }
19947
19948    /**
19949     * Non-Binder method, support for the backup/restore mechanism: write the
19950     * full set of preferred activities in its canonical XML format.  Returns the
19951     * XML output as a byte array, or null if there is none.
19952     */
19953    @Override
19954    public byte[] getPreferredActivityBackup(int userId) {
19955        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19956            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19957        }
19958
19959        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19960        try {
19961            final XmlSerializer serializer = new FastXmlSerializer();
19962            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19963            serializer.startDocument(null, true);
19964            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19965
19966            synchronized (mPackages) {
19967                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19968            }
19969
19970            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19971            serializer.endDocument();
19972            serializer.flush();
19973        } catch (Exception e) {
19974            if (DEBUG_BACKUP) {
19975                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19976            }
19977            return null;
19978        }
19979
19980        return dataStream.toByteArray();
19981    }
19982
19983    @Override
19984    public void restorePreferredActivities(byte[] backup, int userId) {
19985        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19986            throw new SecurityException("Only the system may call restorePreferredActivities()");
19987        }
19988
19989        try {
19990            final XmlPullParser parser = Xml.newPullParser();
19991            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19992            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19993                    new BlobXmlRestorer() {
19994                        @Override
19995                        public void apply(XmlPullParser parser, int userId)
19996                                throws XmlPullParserException, IOException {
19997                            synchronized (mPackages) {
19998                                mSettings.readPreferredActivitiesLPw(parser, userId);
19999                            }
20000                        }
20001                    } );
20002        } catch (Exception e) {
20003            if (DEBUG_BACKUP) {
20004                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20005            }
20006        }
20007    }
20008
20009    /**
20010     * Non-Binder method, support for the backup/restore mechanism: write the
20011     * default browser (etc) settings in its canonical XML format.  Returns the default
20012     * browser XML representation as a byte array, or null if there is none.
20013     */
20014    @Override
20015    public byte[] getDefaultAppsBackup(int userId) {
20016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20017            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20018        }
20019
20020        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20021        try {
20022            final XmlSerializer serializer = new FastXmlSerializer();
20023            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20024            serializer.startDocument(null, true);
20025            serializer.startTag(null, TAG_DEFAULT_APPS);
20026
20027            synchronized (mPackages) {
20028                mSettings.writeDefaultAppsLPr(serializer, userId);
20029            }
20030
20031            serializer.endTag(null, TAG_DEFAULT_APPS);
20032            serializer.endDocument();
20033            serializer.flush();
20034        } catch (Exception e) {
20035            if (DEBUG_BACKUP) {
20036                Slog.e(TAG, "Unable to write default apps for backup", e);
20037            }
20038            return null;
20039        }
20040
20041        return dataStream.toByteArray();
20042    }
20043
20044    @Override
20045    public void restoreDefaultApps(byte[] backup, int userId) {
20046        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20047            throw new SecurityException("Only the system may call restoreDefaultApps()");
20048        }
20049
20050        try {
20051            final XmlPullParser parser = Xml.newPullParser();
20052            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20053            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20054                    new BlobXmlRestorer() {
20055                        @Override
20056                        public void apply(XmlPullParser parser, int userId)
20057                                throws XmlPullParserException, IOException {
20058                            synchronized (mPackages) {
20059                                mSettings.readDefaultAppsLPw(parser, userId);
20060                            }
20061                        }
20062                    } );
20063        } catch (Exception e) {
20064            if (DEBUG_BACKUP) {
20065                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20066            }
20067        }
20068    }
20069
20070    @Override
20071    public byte[] getIntentFilterVerificationBackup(int userId) {
20072        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20073            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20074        }
20075
20076        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20077        try {
20078            final XmlSerializer serializer = new FastXmlSerializer();
20079            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20080            serializer.startDocument(null, true);
20081            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20082
20083            synchronized (mPackages) {
20084                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20085            }
20086
20087            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20088            serializer.endDocument();
20089            serializer.flush();
20090        } catch (Exception e) {
20091            if (DEBUG_BACKUP) {
20092                Slog.e(TAG, "Unable to write default apps for backup", e);
20093            }
20094            return null;
20095        }
20096
20097        return dataStream.toByteArray();
20098    }
20099
20100    @Override
20101    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20102        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20103            throw new SecurityException("Only the system may call restorePreferredActivities()");
20104        }
20105
20106        try {
20107            final XmlPullParser parser = Xml.newPullParser();
20108            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20109            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20110                    new BlobXmlRestorer() {
20111                        @Override
20112                        public void apply(XmlPullParser parser, int userId)
20113                                throws XmlPullParserException, IOException {
20114                            synchronized (mPackages) {
20115                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20116                                mSettings.writeLPr();
20117                            }
20118                        }
20119                    } );
20120        } catch (Exception e) {
20121            if (DEBUG_BACKUP) {
20122                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20123            }
20124        }
20125    }
20126
20127    @Override
20128    public byte[] getPermissionGrantBackup(int userId) {
20129        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20130            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20131        }
20132
20133        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20134        try {
20135            final XmlSerializer serializer = new FastXmlSerializer();
20136            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20137            serializer.startDocument(null, true);
20138            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20139
20140            synchronized (mPackages) {
20141                serializeRuntimePermissionGrantsLPr(serializer, userId);
20142            }
20143
20144            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20145            serializer.endDocument();
20146            serializer.flush();
20147        } catch (Exception e) {
20148            if (DEBUG_BACKUP) {
20149                Slog.e(TAG, "Unable to write default apps for backup", e);
20150            }
20151            return null;
20152        }
20153
20154        return dataStream.toByteArray();
20155    }
20156
20157    @Override
20158    public void restorePermissionGrants(byte[] backup, int userId) {
20159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20160            throw new SecurityException("Only the system may call restorePermissionGrants()");
20161        }
20162
20163        try {
20164            final XmlPullParser parser = Xml.newPullParser();
20165            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20166            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20167                    new BlobXmlRestorer() {
20168                        @Override
20169                        public void apply(XmlPullParser parser, int userId)
20170                                throws XmlPullParserException, IOException {
20171                            synchronized (mPackages) {
20172                                processRestoredPermissionGrantsLPr(parser, userId);
20173                            }
20174                        }
20175                    } );
20176        } catch (Exception e) {
20177            if (DEBUG_BACKUP) {
20178                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20179            }
20180        }
20181    }
20182
20183    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20184            throws IOException {
20185        serializer.startTag(null, TAG_ALL_GRANTS);
20186
20187        final int N = mSettings.mPackages.size();
20188        for (int i = 0; i < N; i++) {
20189            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20190            boolean pkgGrantsKnown = false;
20191
20192            PermissionsState packagePerms = ps.getPermissionsState();
20193
20194            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20195                final int grantFlags = state.getFlags();
20196                // only look at grants that are not system/policy fixed
20197                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20198                    final boolean isGranted = state.isGranted();
20199                    // And only back up the user-twiddled state bits
20200                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20201                        final String packageName = mSettings.mPackages.keyAt(i);
20202                        if (!pkgGrantsKnown) {
20203                            serializer.startTag(null, TAG_GRANT);
20204                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20205                            pkgGrantsKnown = true;
20206                        }
20207
20208                        final boolean userSet =
20209                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20210                        final boolean userFixed =
20211                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20212                        final boolean revoke =
20213                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20214
20215                        serializer.startTag(null, TAG_PERMISSION);
20216                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20217                        if (isGranted) {
20218                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20219                        }
20220                        if (userSet) {
20221                            serializer.attribute(null, ATTR_USER_SET, "true");
20222                        }
20223                        if (userFixed) {
20224                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20225                        }
20226                        if (revoke) {
20227                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20228                        }
20229                        serializer.endTag(null, TAG_PERMISSION);
20230                    }
20231                }
20232            }
20233
20234            if (pkgGrantsKnown) {
20235                serializer.endTag(null, TAG_GRANT);
20236            }
20237        }
20238
20239        serializer.endTag(null, TAG_ALL_GRANTS);
20240    }
20241
20242    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20243            throws XmlPullParserException, IOException {
20244        String pkgName = null;
20245        int outerDepth = parser.getDepth();
20246        int type;
20247        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20248                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20249            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20250                continue;
20251            }
20252
20253            final String tagName = parser.getName();
20254            if (tagName.equals(TAG_GRANT)) {
20255                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20256                if (DEBUG_BACKUP) {
20257                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20258                }
20259            } else if (tagName.equals(TAG_PERMISSION)) {
20260
20261                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20262                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20263
20264                int newFlagSet = 0;
20265                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20266                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20267                }
20268                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20269                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20270                }
20271                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20272                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20273                }
20274                if (DEBUG_BACKUP) {
20275                    Slog.v(TAG, "  + Restoring grant:"
20276                            + " pkg=" + pkgName
20277                            + " perm=" + permName
20278                            + " granted=" + isGranted
20279                            + " bits=0x" + Integer.toHexString(newFlagSet));
20280                }
20281                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20282                if (ps != null) {
20283                    // Already installed so we apply the grant immediately
20284                    if (DEBUG_BACKUP) {
20285                        Slog.v(TAG, "        + already installed; applying");
20286                    }
20287                    PermissionsState perms = ps.getPermissionsState();
20288                    BasePermission bp =
20289                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20290                    if (bp != null) {
20291                        if (isGranted) {
20292                            perms.grantRuntimePermission(bp, userId);
20293                        }
20294                        if (newFlagSet != 0) {
20295                            perms.updatePermissionFlags(
20296                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20297                        }
20298                    }
20299                } else {
20300                    // Need to wait for post-restore install to apply the grant
20301                    if (DEBUG_BACKUP) {
20302                        Slog.v(TAG, "        - not yet installed; saving for later");
20303                    }
20304                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20305                            isGranted, newFlagSet, userId);
20306                }
20307            } else {
20308                PackageManagerService.reportSettingsProblem(Log.WARN,
20309                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20310                XmlUtils.skipCurrentTag(parser);
20311            }
20312        }
20313
20314        scheduleWriteSettingsLocked();
20315        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20316    }
20317
20318    @Override
20319    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20320            int sourceUserId, int targetUserId, int flags) {
20321        mContext.enforceCallingOrSelfPermission(
20322                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20323        int callingUid = Binder.getCallingUid();
20324        enforceOwnerRights(ownerPackage, callingUid);
20325        PackageManagerServiceUtils.enforceShellRestriction(
20326                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20327        if (intentFilter.countActions() == 0) {
20328            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20329            return;
20330        }
20331        synchronized (mPackages) {
20332            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20333                    ownerPackage, targetUserId, flags);
20334            CrossProfileIntentResolver resolver =
20335                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20336            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20337            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20338            if (existing != null) {
20339                int size = existing.size();
20340                for (int i = 0; i < size; i++) {
20341                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20342                        return;
20343                    }
20344                }
20345            }
20346            resolver.addFilter(newFilter);
20347            scheduleWritePackageRestrictionsLocked(sourceUserId);
20348        }
20349    }
20350
20351    @Override
20352    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20353        mContext.enforceCallingOrSelfPermission(
20354                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20355        final int callingUid = Binder.getCallingUid();
20356        enforceOwnerRights(ownerPackage, callingUid);
20357        PackageManagerServiceUtils.enforceShellRestriction(
20358                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20359        synchronized (mPackages) {
20360            CrossProfileIntentResolver resolver =
20361                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20362            ArraySet<CrossProfileIntentFilter> set =
20363                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20364            for (CrossProfileIntentFilter filter : set) {
20365                if (filter.getOwnerPackage().equals(ownerPackage)) {
20366                    resolver.removeFilter(filter);
20367                }
20368            }
20369            scheduleWritePackageRestrictionsLocked(sourceUserId);
20370        }
20371    }
20372
20373    // Enforcing that callingUid is owning pkg on userId
20374    private void enforceOwnerRights(String pkg, int callingUid) {
20375        // The system owns everything.
20376        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20377            return;
20378        }
20379        final int callingUserId = UserHandle.getUserId(callingUid);
20380        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20381        if (pi == null) {
20382            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20383                    + callingUserId);
20384        }
20385        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20386            throw new SecurityException("Calling uid " + callingUid
20387                    + " does not own package " + pkg);
20388        }
20389    }
20390
20391    @Override
20392    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20393        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20394            return null;
20395        }
20396        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20397    }
20398
20399    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20400        UserManagerService ums = UserManagerService.getInstance();
20401        if (ums != null) {
20402            final UserInfo parent = ums.getProfileParent(userId);
20403            final int launcherUid = (parent != null) ? parent.id : userId;
20404            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20405            if (launcherComponent != null) {
20406                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20407                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20408                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20409                        .setPackage(launcherComponent.getPackageName());
20410                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20411            }
20412        }
20413    }
20414
20415    /**
20416     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20417     * then reports the most likely home activity or null if there are more than one.
20418     */
20419    private ComponentName getDefaultHomeActivity(int userId) {
20420        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20421        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20422        if (cn != null) {
20423            return cn;
20424        }
20425
20426        // Find the launcher with the highest priority and return that component if there are no
20427        // other home activity with the same priority.
20428        int lastPriority = Integer.MIN_VALUE;
20429        ComponentName lastComponent = null;
20430        final int size = allHomeCandidates.size();
20431        for (int i = 0; i < size; i++) {
20432            final ResolveInfo ri = allHomeCandidates.get(i);
20433            if (ri.priority > lastPriority) {
20434                lastComponent = ri.activityInfo.getComponentName();
20435                lastPriority = ri.priority;
20436            } else if (ri.priority == lastPriority) {
20437                // Two components found with same priority.
20438                lastComponent = null;
20439            }
20440        }
20441        return lastComponent;
20442    }
20443
20444    private Intent getHomeIntent() {
20445        Intent intent = new Intent(Intent.ACTION_MAIN);
20446        intent.addCategory(Intent.CATEGORY_HOME);
20447        intent.addCategory(Intent.CATEGORY_DEFAULT);
20448        return intent;
20449    }
20450
20451    private IntentFilter getHomeFilter() {
20452        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20453        filter.addCategory(Intent.CATEGORY_HOME);
20454        filter.addCategory(Intent.CATEGORY_DEFAULT);
20455        return filter;
20456    }
20457
20458    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20459            int userId) {
20460        Intent intent  = getHomeIntent();
20461        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20462                PackageManager.GET_META_DATA, userId);
20463        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20464                true, false, false, userId);
20465
20466        allHomeCandidates.clear();
20467        if (list != null) {
20468            for (ResolveInfo ri : list) {
20469                allHomeCandidates.add(ri);
20470            }
20471        }
20472        return (preferred == null || preferred.activityInfo == null)
20473                ? null
20474                : new ComponentName(preferred.activityInfo.packageName,
20475                        preferred.activityInfo.name);
20476    }
20477
20478    @Override
20479    public void setHomeActivity(ComponentName comp, int userId) {
20480        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20481            return;
20482        }
20483        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20484        getHomeActivitiesAsUser(homeActivities, userId);
20485
20486        boolean found = false;
20487
20488        final int size = homeActivities.size();
20489        final ComponentName[] set = new ComponentName[size];
20490        for (int i = 0; i < size; i++) {
20491            final ResolveInfo candidate = homeActivities.get(i);
20492            final ActivityInfo info = candidate.activityInfo;
20493            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20494            set[i] = activityName;
20495            if (!found && activityName.equals(comp)) {
20496                found = true;
20497            }
20498        }
20499        if (!found) {
20500            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20501                    + userId);
20502        }
20503        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20504                set, comp, userId);
20505    }
20506
20507    private @Nullable String getSetupWizardPackageName() {
20508        final Intent intent = new Intent(Intent.ACTION_MAIN);
20509        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20510
20511        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20512                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20513                        | MATCH_DISABLED_COMPONENTS,
20514                UserHandle.myUserId());
20515        if (matches.size() == 1) {
20516            return matches.get(0).getComponentInfo().packageName;
20517        } else {
20518            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20519                    + ": matches=" + matches);
20520            return null;
20521        }
20522    }
20523
20524    private @Nullable String getStorageManagerPackageName() {
20525        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20526
20527        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20528                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20529                        | MATCH_DISABLED_COMPONENTS,
20530                UserHandle.myUserId());
20531        if (matches.size() == 1) {
20532            return matches.get(0).getComponentInfo().packageName;
20533        } else {
20534            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20535                    + matches.size() + ": matches=" + matches);
20536            return null;
20537        }
20538    }
20539
20540    @Override
20541    public void setApplicationEnabledSetting(String appPackageName,
20542            int newState, int flags, int userId, String callingPackage) {
20543        if (!sUserManager.exists(userId)) return;
20544        if (callingPackage == null) {
20545            callingPackage = Integer.toString(Binder.getCallingUid());
20546        }
20547        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20548    }
20549
20550    @Override
20551    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20552        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20553        synchronized (mPackages) {
20554            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20555            if (pkgSetting != null) {
20556                pkgSetting.setUpdateAvailable(updateAvailable);
20557            }
20558        }
20559    }
20560
20561    @Override
20562    public void setComponentEnabledSetting(ComponentName componentName,
20563            int newState, int flags, int userId) {
20564        if (!sUserManager.exists(userId)) return;
20565        setEnabledSetting(componentName.getPackageName(),
20566                componentName.getClassName(), newState, flags, userId, null);
20567    }
20568
20569    private void setEnabledSetting(final String packageName, String className, int newState,
20570            final int flags, int userId, String callingPackage) {
20571        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20572              || newState == COMPONENT_ENABLED_STATE_ENABLED
20573              || newState == COMPONENT_ENABLED_STATE_DISABLED
20574              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20575              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20576            throw new IllegalArgumentException("Invalid new component state: "
20577                    + newState);
20578        }
20579        PackageSetting pkgSetting;
20580        final int callingUid = Binder.getCallingUid();
20581        final int permission;
20582        if (callingUid == Process.SYSTEM_UID) {
20583            permission = PackageManager.PERMISSION_GRANTED;
20584        } else {
20585            permission = mContext.checkCallingOrSelfPermission(
20586                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20587        }
20588        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20589                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20590        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20591        boolean sendNow = false;
20592        boolean isApp = (className == null);
20593        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20594        String componentName = isApp ? packageName : className;
20595        int packageUid = -1;
20596        ArrayList<String> components;
20597
20598        // reader
20599        synchronized (mPackages) {
20600            pkgSetting = mSettings.mPackages.get(packageName);
20601            if (pkgSetting == null) {
20602                if (!isCallerInstantApp) {
20603                    if (className == null) {
20604                        throw new IllegalArgumentException("Unknown package: " + packageName);
20605                    }
20606                    throw new IllegalArgumentException(
20607                            "Unknown component: " + packageName + "/" + className);
20608                } else {
20609                    // throw SecurityException to prevent leaking package information
20610                    throw new SecurityException(
20611                            "Attempt to change component state; "
20612                            + "pid=" + Binder.getCallingPid()
20613                            + ", uid=" + callingUid
20614                            + (className == null
20615                                    ? ", package=" + packageName
20616                                    : ", component=" + packageName + "/" + className));
20617                }
20618            }
20619        }
20620
20621        // Limit who can change which apps
20622        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20623            // Don't allow apps that don't have permission to modify other apps
20624            if (!allowedByPermission
20625                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20626                throw new SecurityException(
20627                        "Attempt to change component state; "
20628                        + "pid=" + Binder.getCallingPid()
20629                        + ", uid=" + callingUid
20630                        + (className == null
20631                                ? ", package=" + packageName
20632                                : ", component=" + packageName + "/" + className));
20633            }
20634            // Don't allow changing protected packages.
20635            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20636                throw new SecurityException("Cannot disable a protected package: " + packageName);
20637            }
20638        }
20639
20640        synchronized (mPackages) {
20641            if (callingUid == Process.SHELL_UID
20642                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20643                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20644                // unless it is a test package.
20645                int oldState = pkgSetting.getEnabled(userId);
20646                if (className == null
20647                        &&
20648                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20649                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20650                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20651                        &&
20652                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20653                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20654                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20655                    // ok
20656                } else {
20657                    throw new SecurityException(
20658                            "Shell cannot change component state for " + packageName + "/"
20659                                    + className + " to " + newState);
20660                }
20661            }
20662        }
20663        if (className == null) {
20664            // We're dealing with an application/package level state change
20665            synchronized (mPackages) {
20666                if (pkgSetting.getEnabled(userId) == newState) {
20667                    // Nothing to do
20668                    return;
20669                }
20670            }
20671            // If we're enabling a system stub, there's a little more work to do.
20672            // Prior to enabling the package, we need to decompress the APK(s) to the
20673            // data partition and then replace the version on the system partition.
20674            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20675            final boolean isSystemStub = deletedPkg.isStub
20676                    && deletedPkg.isSystemApp();
20677            if (isSystemStub
20678                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20679                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20680                final File codePath = decompressPackage(deletedPkg);
20681                if (codePath == null) {
20682                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20683                    return;
20684                }
20685                // TODO remove direct parsing of the package object during internal cleanup
20686                // of scan package
20687                // We need to call parse directly here for no other reason than we need
20688                // the new package in order to disable the old one [we use the information
20689                // for some internal optimization to optionally create a new package setting
20690                // object on replace]. However, we can't get the package from the scan
20691                // because the scan modifies live structures and we need to remove the
20692                // old [system] package from the system before a scan can be attempted.
20693                // Once scan is indempotent we can remove this parse and use the package
20694                // object we scanned, prior to adding it to package settings.
20695                final PackageParser pp = new PackageParser();
20696                pp.setSeparateProcesses(mSeparateProcesses);
20697                pp.setDisplayMetrics(mMetrics);
20698                pp.setCallback(mPackageParserCallback);
20699                final PackageParser.Package tmpPkg;
20700                try {
20701                    final int parseFlags = mDefParseFlags
20702                            | PackageParser.PARSE_MUST_BE_APK
20703                            | PackageParser.PARSE_IS_SYSTEM
20704                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20705                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20706                } catch (PackageParserException e) {
20707                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20708                    return;
20709                }
20710                synchronized (mInstallLock) {
20711                    // Disable the stub and remove any package entries
20712                    removePackageLI(deletedPkg, true);
20713                    synchronized (mPackages) {
20714                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20715                    }
20716                    final PackageParser.Package newPkg;
20717                    try (PackageFreezer freezer =
20718                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20719                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20720                                | PackageParser.PARSE_ENFORCE_CODE;
20721                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20722                                0 /*currentTime*/, null /*user*/);
20723                        prepareAppDataAfterInstallLIF(newPkg);
20724                        synchronized (mPackages) {
20725                            try {
20726                                updateSharedLibrariesLPr(newPkg, null);
20727                            } catch (PackageManagerException e) {
20728                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20729                            }
20730                            updatePermissionsLPw(newPkg.packageName, newPkg,
20731                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20732                            mSettings.writeLPr();
20733                        }
20734                    } catch (PackageManagerException e) {
20735                        // Whoops! Something went wrong; try to roll back to the stub
20736                        Slog.w(TAG, "Failed to install compressed system package:"
20737                                + pkgSetting.name, e);
20738                        // Remove the failed install
20739                        removeCodePathLI(codePath);
20740
20741                        // Install the system package
20742                        try (PackageFreezer freezer =
20743                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20744                            synchronized (mPackages) {
20745                                // NOTE: The system package always needs to be enabled; even
20746                                // if it's for a compressed stub. If we don't, installing the
20747                                // system package fails during scan [scanning checks the disabled
20748                                // packages]. We will reverse this later, after we've "installed"
20749                                // the stub.
20750                                // This leaves us in a fragile state; the stub should never be
20751                                // enabled, so, cross your fingers and hope nothing goes wrong
20752                                // until we can disable the package later.
20753                                enableSystemPackageLPw(deletedPkg);
20754                            }
20755                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20756                                    false /*isPrivileged*/, null /*allUserHandles*/,
20757                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20758                                    true /*writeSettings*/);
20759                        } catch (PackageManagerException pme) {
20760                            Slog.w(TAG, "Failed to restore system package:"
20761                                    + deletedPkg.packageName, pme);
20762                        } finally {
20763                            synchronized (mPackages) {
20764                                mSettings.disableSystemPackageLPw(
20765                                        deletedPkg.packageName, true /*replaced*/);
20766                                mSettings.writeLPr();
20767                            }
20768                        }
20769                        return;
20770                    }
20771                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20772                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20773                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20774                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20775                            newPkg.baseCodePath, newPkg.splitCodePaths);
20776                }
20777            }
20778            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20779                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20780                // Don't care about who enables an app.
20781                callingPackage = null;
20782            }
20783            synchronized (mPackages) {
20784                pkgSetting.setEnabled(newState, userId, callingPackage);
20785            }
20786        } else {
20787            synchronized (mPackages) {
20788                // We're dealing with a component level state change
20789                // First, verify that this is a valid class name.
20790                PackageParser.Package pkg = pkgSetting.pkg;
20791                if (pkg == null || !pkg.hasComponentClassName(className)) {
20792                    if (pkg != null &&
20793                            pkg.applicationInfo.targetSdkVersion >=
20794                                    Build.VERSION_CODES.JELLY_BEAN) {
20795                        throw new IllegalArgumentException("Component class " + className
20796                                + " does not exist in " + packageName);
20797                    } else {
20798                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20799                                + className + " does not exist in " + packageName);
20800                    }
20801                }
20802                switch (newState) {
20803                    case COMPONENT_ENABLED_STATE_ENABLED:
20804                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20805                            return;
20806                        }
20807                        break;
20808                    case COMPONENT_ENABLED_STATE_DISABLED:
20809                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20810                            return;
20811                        }
20812                        break;
20813                    case COMPONENT_ENABLED_STATE_DEFAULT:
20814                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20815                            return;
20816                        }
20817                        break;
20818                    default:
20819                        Slog.e(TAG, "Invalid new component state: " + newState);
20820                        return;
20821                }
20822            }
20823        }
20824        synchronized (mPackages) {
20825            scheduleWritePackageRestrictionsLocked(userId);
20826            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20827            final long callingId = Binder.clearCallingIdentity();
20828            try {
20829                updateInstantAppInstallerLocked(packageName);
20830            } finally {
20831                Binder.restoreCallingIdentity(callingId);
20832            }
20833            components = mPendingBroadcasts.get(userId, packageName);
20834            final boolean newPackage = components == null;
20835            if (newPackage) {
20836                components = new ArrayList<String>();
20837            }
20838            if (!components.contains(componentName)) {
20839                components.add(componentName);
20840            }
20841            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20842                sendNow = true;
20843                // Purge entry from pending broadcast list if another one exists already
20844                // since we are sending one right away.
20845                mPendingBroadcasts.remove(userId, packageName);
20846            } else {
20847                if (newPackage) {
20848                    mPendingBroadcasts.put(userId, packageName, components);
20849                }
20850                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20851                    // Schedule a message
20852                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20853                }
20854            }
20855        }
20856
20857        long callingId = Binder.clearCallingIdentity();
20858        try {
20859            if (sendNow) {
20860                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20861                sendPackageChangedBroadcast(packageName,
20862                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20863            }
20864        } finally {
20865            Binder.restoreCallingIdentity(callingId);
20866        }
20867    }
20868
20869    @Override
20870    public void flushPackageRestrictionsAsUser(int userId) {
20871        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20872            return;
20873        }
20874        if (!sUserManager.exists(userId)) {
20875            return;
20876        }
20877        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20878                false /* checkShell */, "flushPackageRestrictions");
20879        synchronized (mPackages) {
20880            mSettings.writePackageRestrictionsLPr(userId);
20881            mDirtyUsers.remove(userId);
20882            if (mDirtyUsers.isEmpty()) {
20883                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20884            }
20885        }
20886    }
20887
20888    private void sendPackageChangedBroadcast(String packageName,
20889            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20890        if (DEBUG_INSTALL)
20891            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20892                    + componentNames);
20893        Bundle extras = new Bundle(4);
20894        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20895        String nameList[] = new String[componentNames.size()];
20896        componentNames.toArray(nameList);
20897        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20898        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20899        extras.putInt(Intent.EXTRA_UID, packageUid);
20900        // If this is not reporting a change of the overall package, then only send it
20901        // to registered receivers.  We don't want to launch a swath of apps for every
20902        // little component state change.
20903        final int flags = !componentNames.contains(packageName)
20904                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20905        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20906                new int[] {UserHandle.getUserId(packageUid)});
20907    }
20908
20909    @Override
20910    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20911        if (!sUserManager.exists(userId)) return;
20912        final int callingUid = Binder.getCallingUid();
20913        if (getInstantAppPackageName(callingUid) != null) {
20914            return;
20915        }
20916        final int permission = mContext.checkCallingOrSelfPermission(
20917                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20918        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20919        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20920                true /* requireFullPermission */, true /* checkShell */, "stop package");
20921        // writer
20922        synchronized (mPackages) {
20923            final PackageSetting ps = mSettings.mPackages.get(packageName);
20924            if (!filterAppAccessLPr(ps, callingUid, userId)
20925                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20926                            allowedByPermission, callingUid, userId)) {
20927                scheduleWritePackageRestrictionsLocked(userId);
20928            }
20929        }
20930    }
20931
20932    @Override
20933    public String getInstallerPackageName(String packageName) {
20934        final int callingUid = Binder.getCallingUid();
20935        if (getInstantAppPackageName(callingUid) != null) {
20936            return null;
20937        }
20938        // reader
20939        synchronized (mPackages) {
20940            final PackageSetting ps = mSettings.mPackages.get(packageName);
20941            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20942                return null;
20943            }
20944            return mSettings.getInstallerPackageNameLPr(packageName);
20945        }
20946    }
20947
20948    public boolean isOrphaned(String packageName) {
20949        // reader
20950        synchronized (mPackages) {
20951            return mSettings.isOrphaned(packageName);
20952        }
20953    }
20954
20955    @Override
20956    public int getApplicationEnabledSetting(String packageName, int userId) {
20957        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20958        int callingUid = Binder.getCallingUid();
20959        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20960                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20961        // reader
20962        synchronized (mPackages) {
20963            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20964                return COMPONENT_ENABLED_STATE_DISABLED;
20965            }
20966            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20967        }
20968    }
20969
20970    @Override
20971    public int getComponentEnabledSetting(ComponentName component, int userId) {
20972        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20973        int callingUid = Binder.getCallingUid();
20974        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20975                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20976        synchronized (mPackages) {
20977            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20978                    component, TYPE_UNKNOWN, userId)) {
20979                return COMPONENT_ENABLED_STATE_DISABLED;
20980            }
20981            return mSettings.getComponentEnabledSettingLPr(component, userId);
20982        }
20983    }
20984
20985    @Override
20986    public void enterSafeMode() {
20987        enforceSystemOrRoot("Only the system can request entering safe mode");
20988
20989        if (!mSystemReady) {
20990            mSafeMode = true;
20991        }
20992    }
20993
20994    @Override
20995    public void systemReady() {
20996        enforceSystemOrRoot("Only the system can claim the system is ready");
20997
20998        mSystemReady = true;
20999        final ContentResolver resolver = mContext.getContentResolver();
21000        ContentObserver co = new ContentObserver(mHandler) {
21001            @Override
21002            public void onChange(boolean selfChange) {
21003                mEphemeralAppsDisabled =
21004                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21005                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21006            }
21007        };
21008        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21009                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21010                false, co, UserHandle.USER_SYSTEM);
21011        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21012                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21013        co.onChange(true);
21014
21015        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21016        // disabled after already being started.
21017        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21018                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21019
21020        // Read the compatibilty setting when the system is ready.
21021        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21022                mContext.getContentResolver(),
21023                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21024        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21025        if (DEBUG_SETTINGS) {
21026            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21027        }
21028
21029        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21030
21031        synchronized (mPackages) {
21032            // Verify that all of the preferred activity components actually
21033            // exist.  It is possible for applications to be updated and at
21034            // that point remove a previously declared activity component that
21035            // had been set as a preferred activity.  We try to clean this up
21036            // the next time we encounter that preferred activity, but it is
21037            // possible for the user flow to never be able to return to that
21038            // situation so here we do a sanity check to make sure we haven't
21039            // left any junk around.
21040            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21041            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21042                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21043                removed.clear();
21044                for (PreferredActivity pa : pir.filterSet()) {
21045                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21046                        removed.add(pa);
21047                    }
21048                }
21049                if (removed.size() > 0) {
21050                    for (int r=0; r<removed.size(); r++) {
21051                        PreferredActivity pa = removed.get(r);
21052                        Slog.w(TAG, "Removing dangling preferred activity: "
21053                                + pa.mPref.mComponent);
21054                        pir.removeFilter(pa);
21055                    }
21056                    mSettings.writePackageRestrictionsLPr(
21057                            mSettings.mPreferredActivities.keyAt(i));
21058                }
21059            }
21060
21061            for (int userId : UserManagerService.getInstance().getUserIds()) {
21062                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21063                    grantPermissionsUserIds = ArrayUtils.appendInt(
21064                            grantPermissionsUserIds, userId);
21065                }
21066            }
21067        }
21068        sUserManager.systemReady();
21069
21070        // If we upgraded grant all default permissions before kicking off.
21071        for (int userId : grantPermissionsUserIds) {
21072            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21073        }
21074
21075        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21076            // If we did not grant default permissions, we preload from this the
21077            // default permission exceptions lazily to ensure we don't hit the
21078            // disk on a new user creation.
21079            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21080        }
21081
21082        // Now that we've scanned all packages, and granted any default
21083        // permissions, ensure permissions are updated. Beware of dragons if you
21084        // try optimizing this.
21085        synchronized (mPackages) {
21086            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21087                    UPDATE_PERMISSIONS_ALL);
21088        }
21089
21090        // Kick off any messages waiting for system ready
21091        if (mPostSystemReadyMessages != null) {
21092            for (Message msg : mPostSystemReadyMessages) {
21093                msg.sendToTarget();
21094            }
21095            mPostSystemReadyMessages = null;
21096        }
21097
21098        // Watch for external volumes that come and go over time
21099        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21100        storage.registerListener(mStorageListener);
21101
21102        mInstallerService.systemReady();
21103        mPackageDexOptimizer.systemReady();
21104
21105        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21106                StorageManagerInternal.class);
21107        StorageManagerInternal.addExternalStoragePolicy(
21108                new StorageManagerInternal.ExternalStorageMountPolicy() {
21109            @Override
21110            public int getMountMode(int uid, String packageName) {
21111                if (Process.isIsolated(uid)) {
21112                    return Zygote.MOUNT_EXTERNAL_NONE;
21113                }
21114                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21115                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21116                }
21117                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21118                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21119                }
21120                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21121                    return Zygote.MOUNT_EXTERNAL_READ;
21122                }
21123                return Zygote.MOUNT_EXTERNAL_WRITE;
21124            }
21125
21126            @Override
21127            public boolean hasExternalStorage(int uid, String packageName) {
21128                return true;
21129            }
21130        });
21131
21132        // Now that we're mostly running, clean up stale users and apps
21133        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21134        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21135
21136        if (mPrivappPermissionsViolations != null) {
21137            throw new IllegalStateException("Signature|privileged permissions not in "
21138                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21139        }
21140    }
21141
21142    public void waitForAppDataPrepared() {
21143        if (mPrepareAppDataFuture == null) {
21144            return;
21145        }
21146        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21147        mPrepareAppDataFuture = null;
21148    }
21149
21150    @Override
21151    public boolean isSafeMode() {
21152        // allow instant applications
21153        return mSafeMode;
21154    }
21155
21156    @Override
21157    public boolean hasSystemUidErrors() {
21158        // allow instant applications
21159        return mHasSystemUidErrors;
21160    }
21161
21162    static String arrayToString(int[] array) {
21163        StringBuffer buf = new StringBuffer(128);
21164        buf.append('[');
21165        if (array != null) {
21166            for (int i=0; i<array.length; i++) {
21167                if (i > 0) buf.append(", ");
21168                buf.append(array[i]);
21169            }
21170        }
21171        buf.append(']');
21172        return buf.toString();
21173    }
21174
21175    @Override
21176    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21177            FileDescriptor err, String[] args, ShellCallback callback,
21178            ResultReceiver resultReceiver) {
21179        (new PackageManagerShellCommand(this)).exec(
21180                this, in, out, err, args, callback, resultReceiver);
21181    }
21182
21183    @Override
21184    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21185        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21186
21187        DumpState dumpState = new DumpState();
21188        boolean fullPreferred = false;
21189        boolean checkin = false;
21190
21191        String packageName = null;
21192        ArraySet<String> permissionNames = null;
21193
21194        int opti = 0;
21195        while (opti < args.length) {
21196            String opt = args[opti];
21197            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21198                break;
21199            }
21200            opti++;
21201
21202            if ("-a".equals(opt)) {
21203                // Right now we only know how to print all.
21204            } else if ("-h".equals(opt)) {
21205                pw.println("Package manager dump options:");
21206                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21207                pw.println("    --checkin: dump for a checkin");
21208                pw.println("    -f: print details of intent filters");
21209                pw.println("    -h: print this help");
21210                pw.println("  cmd may be one of:");
21211                pw.println("    l[ibraries]: list known shared libraries");
21212                pw.println("    f[eatures]: list device features");
21213                pw.println("    k[eysets]: print known keysets");
21214                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21215                pw.println("    perm[issions]: dump permissions");
21216                pw.println("    permission [name ...]: dump declaration and use of given permission");
21217                pw.println("    pref[erred]: print preferred package settings");
21218                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21219                pw.println("    prov[iders]: dump content providers");
21220                pw.println("    p[ackages]: dump installed packages");
21221                pw.println("    s[hared-users]: dump shared user IDs");
21222                pw.println("    m[essages]: print collected runtime messages");
21223                pw.println("    v[erifiers]: print package verifier info");
21224                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21225                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21226                pw.println("    version: print database version info");
21227                pw.println("    write: write current settings now");
21228                pw.println("    installs: details about install sessions");
21229                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21230                pw.println("    dexopt: dump dexopt state");
21231                pw.println("    compiler-stats: dump compiler statistics");
21232                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21233                pw.println("    <package.name>: info about given package");
21234                return;
21235            } else if ("--checkin".equals(opt)) {
21236                checkin = true;
21237            } else if ("-f".equals(opt)) {
21238                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21239            } else if ("--proto".equals(opt)) {
21240                dumpProto(fd);
21241                return;
21242            } else {
21243                pw.println("Unknown argument: " + opt + "; use -h for help");
21244            }
21245        }
21246
21247        // Is the caller requesting to dump a particular piece of data?
21248        if (opti < args.length) {
21249            String cmd = args[opti];
21250            opti++;
21251            // Is this a package name?
21252            if ("android".equals(cmd) || cmd.contains(".")) {
21253                packageName = cmd;
21254                // When dumping a single package, we always dump all of its
21255                // filter information since the amount of data will be reasonable.
21256                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21257            } else if ("check-permission".equals(cmd)) {
21258                if (opti >= args.length) {
21259                    pw.println("Error: check-permission missing permission argument");
21260                    return;
21261                }
21262                String perm = args[opti];
21263                opti++;
21264                if (opti >= args.length) {
21265                    pw.println("Error: check-permission missing package argument");
21266                    return;
21267                }
21268
21269                String pkg = args[opti];
21270                opti++;
21271                int user = UserHandle.getUserId(Binder.getCallingUid());
21272                if (opti < args.length) {
21273                    try {
21274                        user = Integer.parseInt(args[opti]);
21275                    } catch (NumberFormatException e) {
21276                        pw.println("Error: check-permission user argument is not a number: "
21277                                + args[opti]);
21278                        return;
21279                    }
21280                }
21281
21282                // Normalize package name to handle renamed packages and static libs
21283                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21284
21285                pw.println(checkPermission(perm, pkg, user));
21286                return;
21287            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21288                dumpState.setDump(DumpState.DUMP_LIBS);
21289            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21290                dumpState.setDump(DumpState.DUMP_FEATURES);
21291            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21292                if (opti >= args.length) {
21293                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21294                            | DumpState.DUMP_SERVICE_RESOLVERS
21295                            | DumpState.DUMP_RECEIVER_RESOLVERS
21296                            | DumpState.DUMP_CONTENT_RESOLVERS);
21297                } else {
21298                    while (opti < args.length) {
21299                        String name = args[opti];
21300                        if ("a".equals(name) || "activity".equals(name)) {
21301                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21302                        } else if ("s".equals(name) || "service".equals(name)) {
21303                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21304                        } else if ("r".equals(name) || "receiver".equals(name)) {
21305                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21306                        } else if ("c".equals(name) || "content".equals(name)) {
21307                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21308                        } else {
21309                            pw.println("Error: unknown resolver table type: " + name);
21310                            return;
21311                        }
21312                        opti++;
21313                    }
21314                }
21315            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21316                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21317            } else if ("permission".equals(cmd)) {
21318                if (opti >= args.length) {
21319                    pw.println("Error: permission requires permission name");
21320                    return;
21321                }
21322                permissionNames = new ArraySet<>();
21323                while (opti < args.length) {
21324                    permissionNames.add(args[opti]);
21325                    opti++;
21326                }
21327                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21328                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21329            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21330                dumpState.setDump(DumpState.DUMP_PREFERRED);
21331            } else if ("preferred-xml".equals(cmd)) {
21332                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21333                if (opti < args.length && "--full".equals(args[opti])) {
21334                    fullPreferred = true;
21335                    opti++;
21336                }
21337            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21338                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21339            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21340                dumpState.setDump(DumpState.DUMP_PACKAGES);
21341            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21342                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21343            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21344                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21345            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21346                dumpState.setDump(DumpState.DUMP_MESSAGES);
21347            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21348                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21349            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21350                    || "intent-filter-verifiers".equals(cmd)) {
21351                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21352            } else if ("version".equals(cmd)) {
21353                dumpState.setDump(DumpState.DUMP_VERSION);
21354            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21355                dumpState.setDump(DumpState.DUMP_KEYSETS);
21356            } else if ("installs".equals(cmd)) {
21357                dumpState.setDump(DumpState.DUMP_INSTALLS);
21358            } else if ("frozen".equals(cmd)) {
21359                dumpState.setDump(DumpState.DUMP_FROZEN);
21360            } else if ("volumes".equals(cmd)) {
21361                dumpState.setDump(DumpState.DUMP_VOLUMES);
21362            } else if ("dexopt".equals(cmd)) {
21363                dumpState.setDump(DumpState.DUMP_DEXOPT);
21364            } else if ("compiler-stats".equals(cmd)) {
21365                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21366            } else if ("changes".equals(cmd)) {
21367                dumpState.setDump(DumpState.DUMP_CHANGES);
21368            } else if ("write".equals(cmd)) {
21369                synchronized (mPackages) {
21370                    mSettings.writeLPr();
21371                    pw.println("Settings written.");
21372                    return;
21373                }
21374            }
21375        }
21376
21377        if (checkin) {
21378            pw.println("vers,1");
21379        }
21380
21381        // reader
21382        synchronized (mPackages) {
21383            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21384                if (!checkin) {
21385                    if (dumpState.onTitlePrinted())
21386                        pw.println();
21387                    pw.println("Database versions:");
21388                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21389                }
21390            }
21391
21392            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21393                if (!checkin) {
21394                    if (dumpState.onTitlePrinted())
21395                        pw.println();
21396                    pw.println("Verifiers:");
21397                    pw.print("  Required: ");
21398                    pw.print(mRequiredVerifierPackage);
21399                    pw.print(" (uid=");
21400                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21401                            UserHandle.USER_SYSTEM));
21402                    pw.println(")");
21403                } else if (mRequiredVerifierPackage != null) {
21404                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21405                    pw.print(",");
21406                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21407                            UserHandle.USER_SYSTEM));
21408                }
21409            }
21410
21411            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21412                    packageName == null) {
21413                if (mIntentFilterVerifierComponent != null) {
21414                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21415                    if (!checkin) {
21416                        if (dumpState.onTitlePrinted())
21417                            pw.println();
21418                        pw.println("Intent Filter Verifier:");
21419                        pw.print("  Using: ");
21420                        pw.print(verifierPackageName);
21421                        pw.print(" (uid=");
21422                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21423                                UserHandle.USER_SYSTEM));
21424                        pw.println(")");
21425                    } else if (verifierPackageName != null) {
21426                        pw.print("ifv,"); pw.print(verifierPackageName);
21427                        pw.print(",");
21428                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21429                                UserHandle.USER_SYSTEM));
21430                    }
21431                } else {
21432                    pw.println();
21433                    pw.println("No Intent Filter Verifier available!");
21434                }
21435            }
21436
21437            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21438                boolean printedHeader = false;
21439                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21440                while (it.hasNext()) {
21441                    String libName = it.next();
21442                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21443                    if (versionedLib == null) {
21444                        continue;
21445                    }
21446                    final int versionCount = versionedLib.size();
21447                    for (int i = 0; i < versionCount; i++) {
21448                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21449                        if (!checkin) {
21450                            if (!printedHeader) {
21451                                if (dumpState.onTitlePrinted())
21452                                    pw.println();
21453                                pw.println("Libraries:");
21454                                printedHeader = true;
21455                            }
21456                            pw.print("  ");
21457                        } else {
21458                            pw.print("lib,");
21459                        }
21460                        pw.print(libEntry.info.getName());
21461                        if (libEntry.info.isStatic()) {
21462                            pw.print(" version=" + libEntry.info.getVersion());
21463                        }
21464                        if (!checkin) {
21465                            pw.print(" -> ");
21466                        }
21467                        if (libEntry.path != null) {
21468                            pw.print(" (jar) ");
21469                            pw.print(libEntry.path);
21470                        } else {
21471                            pw.print(" (apk) ");
21472                            pw.print(libEntry.apk);
21473                        }
21474                        pw.println();
21475                    }
21476                }
21477            }
21478
21479            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21480                if (dumpState.onTitlePrinted())
21481                    pw.println();
21482                if (!checkin) {
21483                    pw.println("Features:");
21484                }
21485
21486                synchronized (mAvailableFeatures) {
21487                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21488                        if (checkin) {
21489                            pw.print("feat,");
21490                            pw.print(feat.name);
21491                            pw.print(",");
21492                            pw.println(feat.version);
21493                        } else {
21494                            pw.print("  ");
21495                            pw.print(feat.name);
21496                            if (feat.version > 0) {
21497                                pw.print(" version=");
21498                                pw.print(feat.version);
21499                            }
21500                            pw.println();
21501                        }
21502                    }
21503                }
21504            }
21505
21506            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21507                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21508                        : "Activity Resolver Table:", "  ", packageName,
21509                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21510                    dumpState.setTitlePrinted(true);
21511                }
21512            }
21513            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21514                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21515                        : "Receiver Resolver Table:", "  ", packageName,
21516                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21517                    dumpState.setTitlePrinted(true);
21518                }
21519            }
21520            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21521                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21522                        : "Service Resolver Table:", "  ", packageName,
21523                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21524                    dumpState.setTitlePrinted(true);
21525                }
21526            }
21527            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21528                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21529                        : "Provider Resolver Table:", "  ", packageName,
21530                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21531                    dumpState.setTitlePrinted(true);
21532                }
21533            }
21534
21535            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21536                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21537                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21538                    int user = mSettings.mPreferredActivities.keyAt(i);
21539                    if (pir.dump(pw,
21540                            dumpState.getTitlePrinted()
21541                                ? "\nPreferred Activities User " + user + ":"
21542                                : "Preferred Activities User " + user + ":", "  ",
21543                            packageName, true, false)) {
21544                        dumpState.setTitlePrinted(true);
21545                    }
21546                }
21547            }
21548
21549            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21550                pw.flush();
21551                FileOutputStream fout = new FileOutputStream(fd);
21552                BufferedOutputStream str = new BufferedOutputStream(fout);
21553                XmlSerializer serializer = new FastXmlSerializer();
21554                try {
21555                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21556                    serializer.startDocument(null, true);
21557                    serializer.setFeature(
21558                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21559                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21560                    serializer.endDocument();
21561                    serializer.flush();
21562                } catch (IllegalArgumentException e) {
21563                    pw.println("Failed writing: " + e);
21564                } catch (IllegalStateException e) {
21565                    pw.println("Failed writing: " + e);
21566                } catch (IOException e) {
21567                    pw.println("Failed writing: " + e);
21568                }
21569            }
21570
21571            if (!checkin
21572                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21573                    && packageName == null) {
21574                pw.println();
21575                int count = mSettings.mPackages.size();
21576                if (count == 0) {
21577                    pw.println("No applications!");
21578                    pw.println();
21579                } else {
21580                    final String prefix = "  ";
21581                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21582                    if (allPackageSettings.size() == 0) {
21583                        pw.println("No domain preferred apps!");
21584                        pw.println();
21585                    } else {
21586                        pw.println("App verification status:");
21587                        pw.println();
21588                        count = 0;
21589                        for (PackageSetting ps : allPackageSettings) {
21590                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21591                            if (ivi == null || ivi.getPackageName() == null) continue;
21592                            pw.println(prefix + "Package: " + ivi.getPackageName());
21593                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21594                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21595                            pw.println();
21596                            count++;
21597                        }
21598                        if (count == 0) {
21599                            pw.println(prefix + "No app verification established.");
21600                            pw.println();
21601                        }
21602                        for (int userId : sUserManager.getUserIds()) {
21603                            pw.println("App linkages for user " + userId + ":");
21604                            pw.println();
21605                            count = 0;
21606                            for (PackageSetting ps : allPackageSettings) {
21607                                final long status = ps.getDomainVerificationStatusForUser(userId);
21608                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21609                                        && !DEBUG_DOMAIN_VERIFICATION) {
21610                                    continue;
21611                                }
21612                                pw.println(prefix + "Package: " + ps.name);
21613                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21614                                String statusStr = IntentFilterVerificationInfo.
21615                                        getStatusStringFromValue(status);
21616                                pw.println(prefix + "Status:  " + statusStr);
21617                                pw.println();
21618                                count++;
21619                            }
21620                            if (count == 0) {
21621                                pw.println(prefix + "No configured app linkages.");
21622                                pw.println();
21623                            }
21624                        }
21625                    }
21626                }
21627            }
21628
21629            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21630                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21631            }
21632
21633            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21634                boolean printedSomething = false;
21635                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21636                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21637                        continue;
21638                    }
21639                    if (!printedSomething) {
21640                        if (dumpState.onTitlePrinted())
21641                            pw.println();
21642                        pw.println("Registered ContentProviders:");
21643                        printedSomething = true;
21644                    }
21645                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21646                    pw.print("    "); pw.println(p.toString());
21647                }
21648                printedSomething = false;
21649                for (Map.Entry<String, PackageParser.Provider> entry :
21650                        mProvidersByAuthority.entrySet()) {
21651                    PackageParser.Provider p = entry.getValue();
21652                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21653                        continue;
21654                    }
21655                    if (!printedSomething) {
21656                        if (dumpState.onTitlePrinted())
21657                            pw.println();
21658                        pw.println("ContentProvider Authorities:");
21659                        printedSomething = true;
21660                    }
21661                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21662                    pw.print("    "); pw.println(p.toString());
21663                    if (p.info != null && p.info.applicationInfo != null) {
21664                        final String appInfo = p.info.applicationInfo.toString();
21665                        pw.print("      applicationInfo="); pw.println(appInfo);
21666                    }
21667                }
21668            }
21669
21670            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21671                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21672            }
21673
21674            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21675                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21676            }
21677
21678            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21679                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21680            }
21681
21682            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21683                if (dumpState.onTitlePrinted()) pw.println();
21684                pw.println("Package Changes:");
21685                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21686                final int K = mChangedPackages.size();
21687                for (int i = 0; i < K; i++) {
21688                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21689                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21690                    final int N = changes.size();
21691                    if (N == 0) {
21692                        pw.print("    "); pw.println("No packages changed");
21693                    } else {
21694                        for (int j = 0; j < N; j++) {
21695                            final String pkgName = changes.valueAt(j);
21696                            final int sequenceNumber = changes.keyAt(j);
21697                            pw.print("    ");
21698                            pw.print("seq=");
21699                            pw.print(sequenceNumber);
21700                            pw.print(", package=");
21701                            pw.println(pkgName);
21702                        }
21703                    }
21704                }
21705            }
21706
21707            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21708                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21709            }
21710
21711            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21712                // XXX should handle packageName != null by dumping only install data that
21713                // the given package is involved with.
21714                if (dumpState.onTitlePrinted()) pw.println();
21715
21716                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21717                ipw.println();
21718                ipw.println("Frozen packages:");
21719                ipw.increaseIndent();
21720                if (mFrozenPackages.size() == 0) {
21721                    ipw.println("(none)");
21722                } else {
21723                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21724                        ipw.println(mFrozenPackages.valueAt(i));
21725                    }
21726                }
21727                ipw.decreaseIndent();
21728            }
21729
21730            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21731                if (dumpState.onTitlePrinted()) pw.println();
21732
21733                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21734                ipw.println();
21735                ipw.println("Loaded volumes:");
21736                ipw.increaseIndent();
21737                if (mLoadedVolumes.size() == 0) {
21738                    ipw.println("(none)");
21739                } else {
21740                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21741                        ipw.println(mLoadedVolumes.valueAt(i));
21742                    }
21743                }
21744                ipw.decreaseIndent();
21745            }
21746
21747            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21748                if (dumpState.onTitlePrinted()) pw.println();
21749                dumpDexoptStateLPr(pw, packageName);
21750            }
21751
21752            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21753                if (dumpState.onTitlePrinted()) pw.println();
21754                dumpCompilerStatsLPr(pw, packageName);
21755            }
21756
21757            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21758                if (dumpState.onTitlePrinted()) pw.println();
21759                mSettings.dumpReadMessagesLPr(pw, dumpState);
21760
21761                pw.println();
21762                pw.println("Package warning messages:");
21763                BufferedReader in = null;
21764                String line = null;
21765                try {
21766                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21767                    while ((line = in.readLine()) != null) {
21768                        if (line.contains("ignored: updated version")) continue;
21769                        pw.println(line);
21770                    }
21771                } catch (IOException ignored) {
21772                } finally {
21773                    IoUtils.closeQuietly(in);
21774                }
21775            }
21776
21777            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21778                BufferedReader in = null;
21779                String line = null;
21780                try {
21781                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21782                    while ((line = in.readLine()) != null) {
21783                        if (line.contains("ignored: updated version")) continue;
21784                        pw.print("msg,");
21785                        pw.println(line);
21786                    }
21787                } catch (IOException ignored) {
21788                } finally {
21789                    IoUtils.closeQuietly(in);
21790                }
21791            }
21792        }
21793
21794        // PackageInstaller should be called outside of mPackages lock
21795        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21796            // XXX should handle packageName != null by dumping only install data that
21797            // the given package is involved with.
21798            if (dumpState.onTitlePrinted()) pw.println();
21799            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21800        }
21801    }
21802
21803    private void dumpProto(FileDescriptor fd) {
21804        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21805
21806        synchronized (mPackages) {
21807            final long requiredVerifierPackageToken =
21808                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21809            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21810            proto.write(
21811                    PackageServiceDumpProto.PackageShortProto.UID,
21812                    getPackageUid(
21813                            mRequiredVerifierPackage,
21814                            MATCH_DEBUG_TRIAGED_MISSING,
21815                            UserHandle.USER_SYSTEM));
21816            proto.end(requiredVerifierPackageToken);
21817
21818            if (mIntentFilterVerifierComponent != null) {
21819                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21820                final long verifierPackageToken =
21821                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21822                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21823                proto.write(
21824                        PackageServiceDumpProto.PackageShortProto.UID,
21825                        getPackageUid(
21826                                verifierPackageName,
21827                                MATCH_DEBUG_TRIAGED_MISSING,
21828                                UserHandle.USER_SYSTEM));
21829                proto.end(verifierPackageToken);
21830            }
21831
21832            dumpSharedLibrariesProto(proto);
21833            dumpFeaturesProto(proto);
21834            mSettings.dumpPackagesProto(proto);
21835            mSettings.dumpSharedUsersProto(proto);
21836            dumpMessagesProto(proto);
21837        }
21838        proto.flush();
21839    }
21840
21841    private void dumpMessagesProto(ProtoOutputStream proto) {
21842        BufferedReader in = null;
21843        String line = null;
21844        try {
21845            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21846            while ((line = in.readLine()) != null) {
21847                if (line.contains("ignored: updated version")) continue;
21848                proto.write(PackageServiceDumpProto.MESSAGES, line);
21849            }
21850        } catch (IOException ignored) {
21851        } finally {
21852            IoUtils.closeQuietly(in);
21853        }
21854    }
21855
21856    private void dumpFeaturesProto(ProtoOutputStream proto) {
21857        synchronized (mAvailableFeatures) {
21858            final int count = mAvailableFeatures.size();
21859            for (int i = 0; i < count; i++) {
21860                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21861            }
21862        }
21863    }
21864
21865    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21866        final int count = mSharedLibraries.size();
21867        for (int i = 0; i < count; i++) {
21868            final String libName = mSharedLibraries.keyAt(i);
21869            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21870            if (versionedLib == null) {
21871                continue;
21872            }
21873            final int versionCount = versionedLib.size();
21874            for (int j = 0; j < versionCount; j++) {
21875                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21876                final long sharedLibraryToken =
21877                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21878                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21879                final boolean isJar = (libEntry.path != null);
21880                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21881                if (isJar) {
21882                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21883                } else {
21884                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21885                }
21886                proto.end(sharedLibraryToken);
21887            }
21888        }
21889    }
21890
21891    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21892        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21893        ipw.println();
21894        ipw.println("Dexopt state:");
21895        ipw.increaseIndent();
21896        Collection<PackageParser.Package> packages = null;
21897        if (packageName != null) {
21898            PackageParser.Package targetPackage = mPackages.get(packageName);
21899            if (targetPackage != null) {
21900                packages = Collections.singletonList(targetPackage);
21901            } else {
21902                ipw.println("Unable to find package: " + packageName);
21903                return;
21904            }
21905        } else {
21906            packages = mPackages.values();
21907        }
21908
21909        for (PackageParser.Package pkg : packages) {
21910            ipw.println("[" + pkg.packageName + "]");
21911            ipw.increaseIndent();
21912            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21913                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21914            ipw.decreaseIndent();
21915        }
21916    }
21917
21918    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21919        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
21920        ipw.println();
21921        ipw.println("Compiler stats:");
21922        ipw.increaseIndent();
21923        Collection<PackageParser.Package> packages = null;
21924        if (packageName != null) {
21925            PackageParser.Package targetPackage = mPackages.get(packageName);
21926            if (targetPackage != null) {
21927                packages = Collections.singletonList(targetPackage);
21928            } else {
21929                ipw.println("Unable to find package: " + packageName);
21930                return;
21931            }
21932        } else {
21933            packages = mPackages.values();
21934        }
21935
21936        for (PackageParser.Package pkg : packages) {
21937            ipw.println("[" + pkg.packageName + "]");
21938            ipw.increaseIndent();
21939
21940            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21941            if (stats == null) {
21942                ipw.println("(No recorded stats)");
21943            } else {
21944                stats.dump(ipw);
21945            }
21946            ipw.decreaseIndent();
21947        }
21948    }
21949
21950    private String dumpDomainString(String packageName) {
21951        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21952                .getList();
21953        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21954
21955        ArraySet<String> result = new ArraySet<>();
21956        if (iviList.size() > 0) {
21957            for (IntentFilterVerificationInfo ivi : iviList) {
21958                for (String host : ivi.getDomains()) {
21959                    result.add(host);
21960                }
21961            }
21962        }
21963        if (filters != null && filters.size() > 0) {
21964            for (IntentFilter filter : filters) {
21965                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21966                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21967                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21968                    result.addAll(filter.getHostsList());
21969                }
21970            }
21971        }
21972
21973        StringBuilder sb = new StringBuilder(result.size() * 16);
21974        for (String domain : result) {
21975            if (sb.length() > 0) sb.append(" ");
21976            sb.append(domain);
21977        }
21978        return sb.toString();
21979    }
21980
21981    // ------- apps on sdcard specific code -------
21982    static final boolean DEBUG_SD_INSTALL = false;
21983
21984    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21985
21986    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21987
21988    private boolean mMediaMounted = false;
21989
21990    static String getEncryptKey() {
21991        try {
21992            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21993                    SD_ENCRYPTION_KEYSTORE_NAME);
21994            if (sdEncKey == null) {
21995                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21996                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21997                if (sdEncKey == null) {
21998                    Slog.e(TAG, "Failed to create encryption keys");
21999                    return null;
22000                }
22001            }
22002            return sdEncKey;
22003        } catch (NoSuchAlgorithmException nsae) {
22004            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22005            return null;
22006        } catch (IOException ioe) {
22007            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22008            return null;
22009        }
22010    }
22011
22012    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22013            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22014        final int size = infos.size();
22015        final String[] packageNames = new String[size];
22016        final int[] packageUids = new int[size];
22017        for (int i = 0; i < size; i++) {
22018            final ApplicationInfo info = infos.get(i);
22019            packageNames[i] = info.packageName;
22020            packageUids[i] = info.uid;
22021        }
22022        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22023                finishedReceiver);
22024    }
22025
22026    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22027            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22028        sendResourcesChangedBroadcast(mediaStatus, replacing,
22029                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22030    }
22031
22032    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22033            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22034        int size = pkgList.length;
22035        if (size > 0) {
22036            // Send broadcasts here
22037            Bundle extras = new Bundle();
22038            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22039            if (uidArr != null) {
22040                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22041            }
22042            if (replacing) {
22043                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22044            }
22045            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22046                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22047            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22048        }
22049    }
22050
22051    private void loadPrivatePackages(final VolumeInfo vol) {
22052        mHandler.post(new Runnable() {
22053            @Override
22054            public void run() {
22055                loadPrivatePackagesInner(vol);
22056            }
22057        });
22058    }
22059
22060    private void loadPrivatePackagesInner(VolumeInfo vol) {
22061        final String volumeUuid = vol.fsUuid;
22062        if (TextUtils.isEmpty(volumeUuid)) {
22063            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22064            return;
22065        }
22066
22067        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22068        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22069        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22070
22071        final VersionInfo ver;
22072        final List<PackageSetting> packages;
22073        synchronized (mPackages) {
22074            ver = mSettings.findOrCreateVersion(volumeUuid);
22075            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22076        }
22077
22078        for (PackageSetting ps : packages) {
22079            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22080            synchronized (mInstallLock) {
22081                final PackageParser.Package pkg;
22082                try {
22083                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22084                    loaded.add(pkg.applicationInfo);
22085
22086                } catch (PackageManagerException e) {
22087                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22088                }
22089
22090                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22091                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22092                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22093                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22094                }
22095            }
22096        }
22097
22098        // Reconcile app data for all started/unlocked users
22099        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22100        final UserManager um = mContext.getSystemService(UserManager.class);
22101        UserManagerInternal umInternal = getUserManagerInternal();
22102        for (UserInfo user : um.getUsers()) {
22103            final int flags;
22104            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22105                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22106            } else if (umInternal.isUserRunning(user.id)) {
22107                flags = StorageManager.FLAG_STORAGE_DE;
22108            } else {
22109                continue;
22110            }
22111
22112            try {
22113                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22114                synchronized (mInstallLock) {
22115                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22116                }
22117            } catch (IllegalStateException e) {
22118                // Device was probably ejected, and we'll process that event momentarily
22119                Slog.w(TAG, "Failed to prepare storage: " + e);
22120            }
22121        }
22122
22123        synchronized (mPackages) {
22124            int updateFlags = UPDATE_PERMISSIONS_ALL;
22125            if (ver.sdkVersion != mSdkVersion) {
22126                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22127                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22128                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22129            }
22130            updatePermissionsLocked(null, null, volumeUuid, updateFlags);
22131
22132            // Yay, everything is now upgraded
22133            ver.forceCurrent();
22134
22135            mSettings.writeLPr();
22136        }
22137
22138        for (PackageFreezer freezer : freezers) {
22139            freezer.close();
22140        }
22141
22142        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22143        sendResourcesChangedBroadcast(true, false, loaded, null);
22144        mLoadedVolumes.add(vol.getId());
22145    }
22146
22147    private void unloadPrivatePackages(final VolumeInfo vol) {
22148        mHandler.post(new Runnable() {
22149            @Override
22150            public void run() {
22151                unloadPrivatePackagesInner(vol);
22152            }
22153        });
22154    }
22155
22156    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22157        final String volumeUuid = vol.fsUuid;
22158        if (TextUtils.isEmpty(volumeUuid)) {
22159            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22160            return;
22161        }
22162
22163        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22164        synchronized (mInstallLock) {
22165        synchronized (mPackages) {
22166            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22167            for (PackageSetting ps : packages) {
22168                if (ps.pkg == null) continue;
22169
22170                final ApplicationInfo info = ps.pkg.applicationInfo;
22171                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22172                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22173
22174                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22175                        "unloadPrivatePackagesInner")) {
22176                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22177                            false, null)) {
22178                        unloaded.add(info);
22179                    } else {
22180                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22181                    }
22182                }
22183
22184                // Try very hard to release any references to this package
22185                // so we don't risk the system server being killed due to
22186                // open FDs
22187                AttributeCache.instance().removePackage(ps.name);
22188            }
22189
22190            mSettings.writeLPr();
22191        }
22192        }
22193
22194        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22195        sendResourcesChangedBroadcast(false, false, unloaded, null);
22196        mLoadedVolumes.remove(vol.getId());
22197
22198        // Try very hard to release any references to this path so we don't risk
22199        // the system server being killed due to open FDs
22200        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22201
22202        for (int i = 0; i < 3; i++) {
22203            System.gc();
22204            System.runFinalization();
22205        }
22206    }
22207
22208    private void assertPackageKnown(String volumeUuid, String packageName)
22209            throws PackageManagerException {
22210        synchronized (mPackages) {
22211            // Normalize package name to handle renamed packages
22212            packageName = normalizePackageNameLPr(packageName);
22213
22214            final PackageSetting ps = mSettings.mPackages.get(packageName);
22215            if (ps == null) {
22216                throw new PackageManagerException("Package " + packageName + " is unknown");
22217            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22218                throw new PackageManagerException(
22219                        "Package " + packageName + " found on unknown volume " + volumeUuid
22220                                + "; expected volume " + ps.volumeUuid);
22221            }
22222        }
22223    }
22224
22225    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22226            throws PackageManagerException {
22227        synchronized (mPackages) {
22228            // Normalize package name to handle renamed packages
22229            packageName = normalizePackageNameLPr(packageName);
22230
22231            final PackageSetting ps = mSettings.mPackages.get(packageName);
22232            if (ps == null) {
22233                throw new PackageManagerException("Package " + packageName + " is unknown");
22234            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22235                throw new PackageManagerException(
22236                        "Package " + packageName + " found on unknown volume " + volumeUuid
22237                                + "; expected volume " + ps.volumeUuid);
22238            } else if (!ps.getInstalled(userId)) {
22239                throw new PackageManagerException(
22240                        "Package " + packageName + " not installed for user " + userId);
22241            }
22242        }
22243    }
22244
22245    private List<String> collectAbsoluteCodePaths() {
22246        synchronized (mPackages) {
22247            List<String> codePaths = new ArrayList<>();
22248            final int packageCount = mSettings.mPackages.size();
22249            for (int i = 0; i < packageCount; i++) {
22250                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22251                codePaths.add(ps.codePath.getAbsolutePath());
22252            }
22253            return codePaths;
22254        }
22255    }
22256
22257    /**
22258     * Examine all apps present on given mounted volume, and destroy apps that
22259     * aren't expected, either due to uninstallation or reinstallation on
22260     * another volume.
22261     */
22262    private void reconcileApps(String volumeUuid) {
22263        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22264        List<File> filesToDelete = null;
22265
22266        final File[] files = FileUtils.listFilesOrEmpty(
22267                Environment.getDataAppDirectory(volumeUuid));
22268        for (File file : files) {
22269            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22270                    && !PackageInstallerService.isStageName(file.getName());
22271            if (!isPackage) {
22272                // Ignore entries which are not packages
22273                continue;
22274            }
22275
22276            String absolutePath = file.getAbsolutePath();
22277
22278            boolean pathValid = false;
22279            final int absoluteCodePathCount = absoluteCodePaths.size();
22280            for (int i = 0; i < absoluteCodePathCount; i++) {
22281                String absoluteCodePath = absoluteCodePaths.get(i);
22282                if (absolutePath.startsWith(absoluteCodePath)) {
22283                    pathValid = true;
22284                    break;
22285                }
22286            }
22287
22288            if (!pathValid) {
22289                if (filesToDelete == null) {
22290                    filesToDelete = new ArrayList<>();
22291                }
22292                filesToDelete.add(file);
22293            }
22294        }
22295
22296        if (filesToDelete != null) {
22297            final int fileToDeleteCount = filesToDelete.size();
22298            for (int i = 0; i < fileToDeleteCount; i++) {
22299                File fileToDelete = filesToDelete.get(i);
22300                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22301                synchronized (mInstallLock) {
22302                    removeCodePathLI(fileToDelete);
22303                }
22304            }
22305        }
22306    }
22307
22308    /**
22309     * Reconcile all app data for the given user.
22310     * <p>
22311     * Verifies that directories exist and that ownership and labeling is
22312     * correct for all installed apps on all mounted volumes.
22313     */
22314    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22315        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22316        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22317            final String volumeUuid = vol.getFsUuid();
22318            synchronized (mInstallLock) {
22319                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22320            }
22321        }
22322    }
22323
22324    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22325            boolean migrateAppData) {
22326        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22327    }
22328
22329    /**
22330     * Reconcile all app data on given mounted volume.
22331     * <p>
22332     * Destroys app data that isn't expected, either due to uninstallation or
22333     * reinstallation on another volume.
22334     * <p>
22335     * Verifies that directories exist and that ownership and labeling is
22336     * correct for all installed apps.
22337     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22338     */
22339    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22340            boolean migrateAppData, boolean onlyCoreApps) {
22341        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22342                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22343        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22344
22345        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22346        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22347
22348        // First look for stale data that doesn't belong, and check if things
22349        // have changed since we did our last restorecon
22350        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22351            if (StorageManager.isFileEncryptedNativeOrEmulated()
22352                    && !StorageManager.isUserKeyUnlocked(userId)) {
22353                throw new RuntimeException(
22354                        "Yikes, someone asked us to reconcile CE storage while " + userId
22355                                + " was still locked; this would have caused massive data loss!");
22356            }
22357
22358            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22359            for (File file : files) {
22360                final String packageName = file.getName();
22361                try {
22362                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22363                } catch (PackageManagerException e) {
22364                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22365                    try {
22366                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22367                                StorageManager.FLAG_STORAGE_CE, 0);
22368                    } catch (InstallerException e2) {
22369                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22370                    }
22371                }
22372            }
22373        }
22374        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22375            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22376            for (File file : files) {
22377                final String packageName = file.getName();
22378                try {
22379                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22380                } catch (PackageManagerException e) {
22381                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22382                    try {
22383                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22384                                StorageManager.FLAG_STORAGE_DE, 0);
22385                    } catch (InstallerException e2) {
22386                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22387                    }
22388                }
22389            }
22390        }
22391
22392        // Ensure that data directories are ready to roll for all packages
22393        // installed for this volume and user
22394        final List<PackageSetting> packages;
22395        synchronized (mPackages) {
22396            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22397        }
22398        int preparedCount = 0;
22399        for (PackageSetting ps : packages) {
22400            final String packageName = ps.name;
22401            if (ps.pkg == null) {
22402                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22403                // TODO: might be due to legacy ASEC apps; we should circle back
22404                // and reconcile again once they're scanned
22405                continue;
22406            }
22407            // Skip non-core apps if requested
22408            if (onlyCoreApps && !ps.pkg.coreApp) {
22409                result.add(packageName);
22410                continue;
22411            }
22412
22413            if (ps.getInstalled(userId)) {
22414                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22415                preparedCount++;
22416            }
22417        }
22418
22419        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22420        return result;
22421    }
22422
22423    /**
22424     * Prepare app data for the given app just after it was installed or
22425     * upgraded. This method carefully only touches users that it's installed
22426     * for, and it forces a restorecon to handle any seinfo changes.
22427     * <p>
22428     * Verifies that directories exist and that ownership and labeling is
22429     * correct for all installed apps. If there is an ownership mismatch, it
22430     * will try recovering system apps by wiping data; third-party app data is
22431     * left intact.
22432     * <p>
22433     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22434     */
22435    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22436        final PackageSetting ps;
22437        synchronized (mPackages) {
22438            ps = mSettings.mPackages.get(pkg.packageName);
22439            mSettings.writeKernelMappingLPr(ps);
22440        }
22441
22442        final UserManager um = mContext.getSystemService(UserManager.class);
22443        UserManagerInternal umInternal = getUserManagerInternal();
22444        for (UserInfo user : um.getUsers()) {
22445            final int flags;
22446            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22447                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22448            } else if (umInternal.isUserRunning(user.id)) {
22449                flags = StorageManager.FLAG_STORAGE_DE;
22450            } else {
22451                continue;
22452            }
22453
22454            if (ps.getInstalled(user.id)) {
22455                // TODO: when user data is locked, mark that we're still dirty
22456                prepareAppDataLIF(pkg, user.id, flags);
22457            }
22458        }
22459    }
22460
22461    /**
22462     * Prepare app data for the given app.
22463     * <p>
22464     * Verifies that directories exist and that ownership and labeling is
22465     * correct for all installed apps. If there is an ownership mismatch, this
22466     * will try recovering system apps by wiping data; third-party app data is
22467     * left intact.
22468     */
22469    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22470        if (pkg == null) {
22471            Slog.wtf(TAG, "Package was null!", new Throwable());
22472            return;
22473        }
22474        prepareAppDataLeafLIF(pkg, userId, flags);
22475        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22476        for (int i = 0; i < childCount; i++) {
22477            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22478        }
22479    }
22480
22481    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22482            boolean maybeMigrateAppData) {
22483        prepareAppDataLIF(pkg, userId, flags);
22484
22485        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22486            // We may have just shuffled around app data directories, so
22487            // prepare them one more time
22488            prepareAppDataLIF(pkg, userId, flags);
22489        }
22490    }
22491
22492    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22493        if (DEBUG_APP_DATA) {
22494            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22495                    + Integer.toHexString(flags));
22496        }
22497
22498        final String volumeUuid = pkg.volumeUuid;
22499        final String packageName = pkg.packageName;
22500        final ApplicationInfo app = pkg.applicationInfo;
22501        final int appId = UserHandle.getAppId(app.uid);
22502
22503        Preconditions.checkNotNull(app.seInfo);
22504
22505        long ceDataInode = -1;
22506        try {
22507            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22508                    appId, app.seInfo, app.targetSdkVersion);
22509        } catch (InstallerException e) {
22510            if (app.isSystemApp()) {
22511                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22512                        + ", but trying to recover: " + e);
22513                destroyAppDataLeafLIF(pkg, userId, flags);
22514                try {
22515                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22516                            appId, app.seInfo, app.targetSdkVersion);
22517                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22518                } catch (InstallerException e2) {
22519                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22520                }
22521            } else {
22522                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22523            }
22524        }
22525
22526        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22527            // TODO: mark this structure as dirty so we persist it!
22528            synchronized (mPackages) {
22529                final PackageSetting ps = mSettings.mPackages.get(packageName);
22530                if (ps != null) {
22531                    ps.setCeDataInode(ceDataInode, userId);
22532                }
22533            }
22534        }
22535
22536        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22537    }
22538
22539    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22540        if (pkg == null) {
22541            Slog.wtf(TAG, "Package was null!", new Throwable());
22542            return;
22543        }
22544        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22545        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22546        for (int i = 0; i < childCount; i++) {
22547            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22548        }
22549    }
22550
22551    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22552        final String volumeUuid = pkg.volumeUuid;
22553        final String packageName = pkg.packageName;
22554        final ApplicationInfo app = pkg.applicationInfo;
22555
22556        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22557            // Create a native library symlink only if we have native libraries
22558            // and if the native libraries are 32 bit libraries. We do not provide
22559            // this symlink for 64 bit libraries.
22560            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22561                final String nativeLibPath = app.nativeLibraryDir;
22562                try {
22563                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22564                            nativeLibPath, userId);
22565                } catch (InstallerException e) {
22566                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22567                }
22568            }
22569        }
22570    }
22571
22572    /**
22573     * For system apps on non-FBE devices, this method migrates any existing
22574     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22575     * requested by the app.
22576     */
22577    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22578        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22579                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22580            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22581                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22582            try {
22583                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22584                        storageTarget);
22585            } catch (InstallerException e) {
22586                logCriticalInfo(Log.WARN,
22587                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22588            }
22589            return true;
22590        } else {
22591            return false;
22592        }
22593    }
22594
22595    public PackageFreezer freezePackage(String packageName, String killReason) {
22596        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22597    }
22598
22599    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22600        return new PackageFreezer(packageName, userId, killReason);
22601    }
22602
22603    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22604            String killReason) {
22605        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22606    }
22607
22608    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22609            String killReason) {
22610        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22611            return new PackageFreezer();
22612        } else {
22613            return freezePackage(packageName, userId, killReason);
22614        }
22615    }
22616
22617    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22618            String killReason) {
22619        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22620    }
22621
22622    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22623            String killReason) {
22624        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22625            return new PackageFreezer();
22626        } else {
22627            return freezePackage(packageName, userId, killReason);
22628        }
22629    }
22630
22631    /**
22632     * Class that freezes and kills the given package upon creation, and
22633     * unfreezes it upon closing. This is typically used when doing surgery on
22634     * app code/data to prevent the app from running while you're working.
22635     */
22636    private class PackageFreezer implements AutoCloseable {
22637        private final String mPackageName;
22638        private final PackageFreezer[] mChildren;
22639
22640        private final boolean mWeFroze;
22641
22642        private final AtomicBoolean mClosed = new AtomicBoolean();
22643        private final CloseGuard mCloseGuard = CloseGuard.get();
22644
22645        /**
22646         * Create and return a stub freezer that doesn't actually do anything,
22647         * typically used when someone requested
22648         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22649         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22650         */
22651        public PackageFreezer() {
22652            mPackageName = null;
22653            mChildren = null;
22654            mWeFroze = false;
22655            mCloseGuard.open("close");
22656        }
22657
22658        public PackageFreezer(String packageName, int userId, String killReason) {
22659            synchronized (mPackages) {
22660                mPackageName = packageName;
22661                mWeFroze = mFrozenPackages.add(mPackageName);
22662
22663                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22664                if (ps != null) {
22665                    killApplication(ps.name, ps.appId, userId, killReason);
22666                }
22667
22668                final PackageParser.Package p = mPackages.get(packageName);
22669                if (p != null && p.childPackages != null) {
22670                    final int N = p.childPackages.size();
22671                    mChildren = new PackageFreezer[N];
22672                    for (int i = 0; i < N; i++) {
22673                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22674                                userId, killReason);
22675                    }
22676                } else {
22677                    mChildren = null;
22678                }
22679            }
22680            mCloseGuard.open("close");
22681        }
22682
22683        @Override
22684        protected void finalize() throws Throwable {
22685            try {
22686                if (mCloseGuard != null) {
22687                    mCloseGuard.warnIfOpen();
22688                }
22689
22690                close();
22691            } finally {
22692                super.finalize();
22693            }
22694        }
22695
22696        @Override
22697        public void close() {
22698            mCloseGuard.close();
22699            if (mClosed.compareAndSet(false, true)) {
22700                synchronized (mPackages) {
22701                    if (mWeFroze) {
22702                        mFrozenPackages.remove(mPackageName);
22703                    }
22704
22705                    if (mChildren != null) {
22706                        for (PackageFreezer freezer : mChildren) {
22707                            freezer.close();
22708                        }
22709                    }
22710                }
22711            }
22712        }
22713    }
22714
22715    /**
22716     * Verify that given package is currently frozen.
22717     */
22718    private void checkPackageFrozen(String packageName) {
22719        synchronized (mPackages) {
22720            if (!mFrozenPackages.contains(packageName)) {
22721                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22722            }
22723        }
22724    }
22725
22726    @Override
22727    public int movePackage(final String packageName, final String volumeUuid) {
22728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22729
22730        final int callingUid = Binder.getCallingUid();
22731        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22732        final int moveId = mNextMoveId.getAndIncrement();
22733        mHandler.post(new Runnable() {
22734            @Override
22735            public void run() {
22736                try {
22737                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22738                } catch (PackageManagerException e) {
22739                    Slog.w(TAG, "Failed to move " + packageName, e);
22740                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22741                }
22742            }
22743        });
22744        return moveId;
22745    }
22746
22747    private void movePackageInternal(final String packageName, final String volumeUuid,
22748            final int moveId, final int callingUid, UserHandle user)
22749                    throws PackageManagerException {
22750        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22751        final PackageManager pm = mContext.getPackageManager();
22752
22753        final boolean currentAsec;
22754        final String currentVolumeUuid;
22755        final File codeFile;
22756        final String installerPackageName;
22757        final String packageAbiOverride;
22758        final int appId;
22759        final String seinfo;
22760        final String label;
22761        final int targetSdkVersion;
22762        final PackageFreezer freezer;
22763        final int[] installedUserIds;
22764
22765        // reader
22766        synchronized (mPackages) {
22767            final PackageParser.Package pkg = mPackages.get(packageName);
22768            final PackageSetting ps = mSettings.mPackages.get(packageName);
22769            if (pkg == null
22770                    || ps == null
22771                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22772                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22773            }
22774            if (pkg.applicationInfo.isSystemApp()) {
22775                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22776                        "Cannot move system application");
22777            }
22778
22779            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22780            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22781                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22782            if (isInternalStorage && !allow3rdPartyOnInternal) {
22783                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22784                        "3rd party apps are not allowed on internal storage");
22785            }
22786
22787            if (pkg.applicationInfo.isExternalAsec()) {
22788                currentAsec = true;
22789                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22790            } else if (pkg.applicationInfo.isForwardLocked()) {
22791                currentAsec = true;
22792                currentVolumeUuid = "forward_locked";
22793            } else {
22794                currentAsec = false;
22795                currentVolumeUuid = ps.volumeUuid;
22796
22797                final File probe = new File(pkg.codePath);
22798                final File probeOat = new File(probe, "oat");
22799                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22800                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22801                            "Move only supported for modern cluster style installs");
22802                }
22803            }
22804
22805            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22806                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22807                        "Package already moved to " + volumeUuid);
22808            }
22809            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22810                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22811                        "Device admin cannot be moved");
22812            }
22813
22814            if (mFrozenPackages.contains(packageName)) {
22815                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22816                        "Failed to move already frozen package");
22817            }
22818
22819            codeFile = new File(pkg.codePath);
22820            installerPackageName = ps.installerPackageName;
22821            packageAbiOverride = ps.cpuAbiOverrideString;
22822            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22823            seinfo = pkg.applicationInfo.seInfo;
22824            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22825            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22826            freezer = freezePackage(packageName, "movePackageInternal");
22827            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22828        }
22829
22830        final Bundle extras = new Bundle();
22831        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22832        extras.putString(Intent.EXTRA_TITLE, label);
22833        mMoveCallbacks.notifyCreated(moveId, extras);
22834
22835        int installFlags;
22836        final boolean moveCompleteApp;
22837        final File measurePath;
22838
22839        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22840            installFlags = INSTALL_INTERNAL;
22841            moveCompleteApp = !currentAsec;
22842            measurePath = Environment.getDataAppDirectory(volumeUuid);
22843        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22844            installFlags = INSTALL_EXTERNAL;
22845            moveCompleteApp = false;
22846            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22847        } else {
22848            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22849            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22850                    || !volume.isMountedWritable()) {
22851                freezer.close();
22852                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22853                        "Move location not mounted private volume");
22854            }
22855
22856            Preconditions.checkState(!currentAsec);
22857
22858            installFlags = INSTALL_INTERNAL;
22859            moveCompleteApp = true;
22860            measurePath = Environment.getDataAppDirectory(volumeUuid);
22861        }
22862
22863        // If we're moving app data around, we need all the users unlocked
22864        if (moveCompleteApp) {
22865            for (int userId : installedUserIds) {
22866                if (StorageManager.isFileEncryptedNativeOrEmulated()
22867                        && !StorageManager.isUserKeyUnlocked(userId)) {
22868                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22869                            "User " + userId + " must be unlocked");
22870                }
22871            }
22872        }
22873
22874        final PackageStats stats = new PackageStats(null, -1);
22875        synchronized (mInstaller) {
22876            for (int userId : installedUserIds) {
22877                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22878                    freezer.close();
22879                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22880                            "Failed to measure package size");
22881                }
22882            }
22883        }
22884
22885        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22886                + stats.dataSize);
22887
22888        final long startFreeBytes = measurePath.getUsableSpace();
22889        final long sizeBytes;
22890        if (moveCompleteApp) {
22891            sizeBytes = stats.codeSize + stats.dataSize;
22892        } else {
22893            sizeBytes = stats.codeSize;
22894        }
22895
22896        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22897            freezer.close();
22898            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22899                    "Not enough free space to move");
22900        }
22901
22902        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22903
22904        final CountDownLatch installedLatch = new CountDownLatch(1);
22905        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22906            @Override
22907            public void onUserActionRequired(Intent intent) throws RemoteException {
22908                throw new IllegalStateException();
22909            }
22910
22911            @Override
22912            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22913                    Bundle extras) throws RemoteException {
22914                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22915                        + PackageManager.installStatusToString(returnCode, msg));
22916
22917                installedLatch.countDown();
22918                freezer.close();
22919
22920                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22921                switch (status) {
22922                    case PackageInstaller.STATUS_SUCCESS:
22923                        mMoveCallbacks.notifyStatusChanged(moveId,
22924                                PackageManager.MOVE_SUCCEEDED);
22925                        break;
22926                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22927                        mMoveCallbacks.notifyStatusChanged(moveId,
22928                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22929                        break;
22930                    default:
22931                        mMoveCallbacks.notifyStatusChanged(moveId,
22932                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22933                        break;
22934                }
22935            }
22936        };
22937
22938        final MoveInfo move;
22939        if (moveCompleteApp) {
22940            // Kick off a thread to report progress estimates
22941            new Thread() {
22942                @Override
22943                public void run() {
22944                    while (true) {
22945                        try {
22946                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22947                                break;
22948                            }
22949                        } catch (InterruptedException ignored) {
22950                        }
22951
22952                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22953                        final int progress = 10 + (int) MathUtils.constrain(
22954                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22955                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22956                    }
22957                }
22958            }.start();
22959
22960            final String dataAppName = codeFile.getName();
22961            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22962                    dataAppName, appId, seinfo, targetSdkVersion);
22963        } else {
22964            move = null;
22965        }
22966
22967        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22968
22969        final Message msg = mHandler.obtainMessage(INIT_COPY);
22970        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22971        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22972                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22973                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22974                PackageManager.INSTALL_REASON_UNKNOWN);
22975        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22976        msg.obj = params;
22977
22978        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22979                System.identityHashCode(msg.obj));
22980        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22981                System.identityHashCode(msg.obj));
22982
22983        mHandler.sendMessage(msg);
22984    }
22985
22986    @Override
22987    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22988        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22989
22990        final int realMoveId = mNextMoveId.getAndIncrement();
22991        final Bundle extras = new Bundle();
22992        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22993        mMoveCallbacks.notifyCreated(realMoveId, extras);
22994
22995        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22996            @Override
22997            public void onCreated(int moveId, Bundle extras) {
22998                // Ignored
22999            }
23000
23001            @Override
23002            public void onStatusChanged(int moveId, int status, long estMillis) {
23003                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23004            }
23005        };
23006
23007        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23008        storage.setPrimaryStorageUuid(volumeUuid, callback);
23009        return realMoveId;
23010    }
23011
23012    @Override
23013    public int getMoveStatus(int moveId) {
23014        mContext.enforceCallingOrSelfPermission(
23015                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23016        return mMoveCallbacks.mLastStatus.get(moveId);
23017    }
23018
23019    @Override
23020    public void registerMoveCallback(IPackageMoveObserver callback) {
23021        mContext.enforceCallingOrSelfPermission(
23022                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23023        mMoveCallbacks.register(callback);
23024    }
23025
23026    @Override
23027    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23028        mContext.enforceCallingOrSelfPermission(
23029                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23030        mMoveCallbacks.unregister(callback);
23031    }
23032
23033    @Override
23034    public boolean setInstallLocation(int loc) {
23035        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23036                null);
23037        if (getInstallLocation() == loc) {
23038            return true;
23039        }
23040        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23041                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23042            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23043                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23044            return true;
23045        }
23046        return false;
23047   }
23048
23049    @Override
23050    public int getInstallLocation() {
23051        // allow instant app access
23052        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23053                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23054                PackageHelper.APP_INSTALL_AUTO);
23055    }
23056
23057    /** Called by UserManagerService */
23058    void cleanUpUser(UserManagerService userManager, int userHandle) {
23059        synchronized (mPackages) {
23060            mDirtyUsers.remove(userHandle);
23061            mUserNeedsBadging.delete(userHandle);
23062            mSettings.removeUserLPw(userHandle);
23063            mPendingBroadcasts.remove(userHandle);
23064            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23065            removeUnusedPackagesLPw(userManager, userHandle);
23066        }
23067    }
23068
23069    /**
23070     * We're removing userHandle and would like to remove any downloaded packages
23071     * that are no longer in use by any other user.
23072     * @param userHandle the user being removed
23073     */
23074    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23075        final boolean DEBUG_CLEAN_APKS = false;
23076        int [] users = userManager.getUserIds();
23077        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23078        while (psit.hasNext()) {
23079            PackageSetting ps = psit.next();
23080            if (ps.pkg == null) {
23081                continue;
23082            }
23083            final String packageName = ps.pkg.packageName;
23084            // Skip over if system app
23085            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23086                continue;
23087            }
23088            if (DEBUG_CLEAN_APKS) {
23089                Slog.i(TAG, "Checking package " + packageName);
23090            }
23091            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23092            if (keep) {
23093                if (DEBUG_CLEAN_APKS) {
23094                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23095                }
23096            } else {
23097                for (int i = 0; i < users.length; i++) {
23098                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23099                        keep = true;
23100                        if (DEBUG_CLEAN_APKS) {
23101                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23102                                    + users[i]);
23103                        }
23104                        break;
23105                    }
23106                }
23107            }
23108            if (!keep) {
23109                if (DEBUG_CLEAN_APKS) {
23110                    Slog.i(TAG, "  Removing package " + packageName);
23111                }
23112                mHandler.post(new Runnable() {
23113                    public void run() {
23114                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23115                                userHandle, 0);
23116                    } //end run
23117                });
23118            }
23119        }
23120    }
23121
23122    /** Called by UserManagerService */
23123    void createNewUser(int userId, String[] disallowedPackages) {
23124        synchronized (mInstallLock) {
23125            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23126        }
23127        synchronized (mPackages) {
23128            scheduleWritePackageRestrictionsLocked(userId);
23129            scheduleWritePackageListLocked(userId);
23130            applyFactoryDefaultBrowserLPw(userId);
23131            primeDomainVerificationsLPw(userId);
23132        }
23133    }
23134
23135    void onNewUserCreated(final int userId) {
23136        synchronized(mPackages) {
23137            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23138            // If permission review for legacy apps is required, we represent
23139            // dagerous permissions for such apps as always granted runtime
23140            // permissions to keep per user flag state whether review is needed.
23141            // Hence, if a new user is added we have to propagate dangerous
23142            // permission grants for these legacy apps.
23143            if (mPermissionReviewRequired) {
23144                updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23145                        | UPDATE_PERMISSIONS_REPLACE_ALL);
23146            }
23147        }
23148    }
23149
23150    @Override
23151    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23152        mContext.enforceCallingOrSelfPermission(
23153                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23154                "Only package verification agents can read the verifier device identity");
23155
23156        synchronized (mPackages) {
23157            return mSettings.getVerifierDeviceIdentityLPw();
23158        }
23159    }
23160
23161    @Override
23162    public void setPermissionEnforced(String permission, boolean enforced) {
23163        // TODO: Now that we no longer change GID for storage, this should to away.
23164        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23165                "setPermissionEnforced");
23166        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23167            synchronized (mPackages) {
23168                if (mSettings.mReadExternalStorageEnforced == null
23169                        || mSettings.mReadExternalStorageEnforced != enforced) {
23170                    mSettings.mReadExternalStorageEnforced =
23171                            enforced ? Boolean.TRUE : Boolean.FALSE;
23172                    mSettings.writeLPr();
23173                }
23174            }
23175            // kill any non-foreground processes so we restart them and
23176            // grant/revoke the GID.
23177            final IActivityManager am = ActivityManager.getService();
23178            if (am != null) {
23179                final long token = Binder.clearCallingIdentity();
23180                try {
23181                    am.killProcessesBelowForeground("setPermissionEnforcement");
23182                } catch (RemoteException e) {
23183                } finally {
23184                    Binder.restoreCallingIdentity(token);
23185                }
23186            }
23187        } else {
23188            throw new IllegalArgumentException("No selective enforcement for " + permission);
23189        }
23190    }
23191
23192    @Override
23193    @Deprecated
23194    public boolean isPermissionEnforced(String permission) {
23195        // allow instant applications
23196        return true;
23197    }
23198
23199    @Override
23200    public boolean isStorageLow() {
23201        // allow instant applications
23202        final long token = Binder.clearCallingIdentity();
23203        try {
23204            final DeviceStorageMonitorInternal
23205                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23206            if (dsm != null) {
23207                return dsm.isMemoryLow();
23208            } else {
23209                return false;
23210            }
23211        } finally {
23212            Binder.restoreCallingIdentity(token);
23213        }
23214    }
23215
23216    @Override
23217    public IPackageInstaller getPackageInstaller() {
23218        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23219            return null;
23220        }
23221        return mInstallerService;
23222    }
23223
23224    private boolean userNeedsBadging(int userId) {
23225        int index = mUserNeedsBadging.indexOfKey(userId);
23226        if (index < 0) {
23227            final UserInfo userInfo;
23228            final long token = Binder.clearCallingIdentity();
23229            try {
23230                userInfo = sUserManager.getUserInfo(userId);
23231            } finally {
23232                Binder.restoreCallingIdentity(token);
23233            }
23234            final boolean b;
23235            if (userInfo != null && userInfo.isManagedProfile()) {
23236                b = true;
23237            } else {
23238                b = false;
23239            }
23240            mUserNeedsBadging.put(userId, b);
23241            return b;
23242        }
23243        return mUserNeedsBadging.valueAt(index);
23244    }
23245
23246    @Override
23247    public KeySet getKeySetByAlias(String packageName, String alias) {
23248        if (packageName == null || alias == null) {
23249            return null;
23250        }
23251        synchronized(mPackages) {
23252            final PackageParser.Package pkg = mPackages.get(packageName);
23253            if (pkg == null) {
23254                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23255                throw new IllegalArgumentException("Unknown package: " + packageName);
23256            }
23257            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23258            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23259                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23260                throw new IllegalArgumentException("Unknown package: " + packageName);
23261            }
23262            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23263            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23264        }
23265    }
23266
23267    @Override
23268    public KeySet getSigningKeySet(String packageName) {
23269        if (packageName == null) {
23270            return null;
23271        }
23272        synchronized(mPackages) {
23273            final int callingUid = Binder.getCallingUid();
23274            final int callingUserId = UserHandle.getUserId(callingUid);
23275            final PackageParser.Package pkg = mPackages.get(packageName);
23276            if (pkg == null) {
23277                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23278                throw new IllegalArgumentException("Unknown package: " + packageName);
23279            }
23280            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23281            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23282                // filter and pretend the package doesn't exist
23283                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23284                        + ", uid:" + callingUid);
23285                throw new IllegalArgumentException("Unknown package: " + packageName);
23286            }
23287            if (pkg.applicationInfo.uid != callingUid
23288                    && Process.SYSTEM_UID != callingUid) {
23289                throw new SecurityException("May not access signing KeySet of other apps.");
23290            }
23291            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23292            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23293        }
23294    }
23295
23296    @Override
23297    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23298        final int callingUid = Binder.getCallingUid();
23299        if (getInstantAppPackageName(callingUid) != null) {
23300            return false;
23301        }
23302        if (packageName == null || ks == null) {
23303            return false;
23304        }
23305        synchronized(mPackages) {
23306            final PackageParser.Package pkg = mPackages.get(packageName);
23307            if (pkg == null
23308                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23309                            UserHandle.getUserId(callingUid))) {
23310                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23311                throw new IllegalArgumentException("Unknown package: " + packageName);
23312            }
23313            IBinder ksh = ks.getToken();
23314            if (ksh instanceof KeySetHandle) {
23315                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23316                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23317            }
23318            return false;
23319        }
23320    }
23321
23322    @Override
23323    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23324        final int callingUid = Binder.getCallingUid();
23325        if (getInstantAppPackageName(callingUid) != null) {
23326            return false;
23327        }
23328        if (packageName == null || ks == null) {
23329            return false;
23330        }
23331        synchronized(mPackages) {
23332            final PackageParser.Package pkg = mPackages.get(packageName);
23333            if (pkg == null
23334                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23335                            UserHandle.getUserId(callingUid))) {
23336                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23337                throw new IllegalArgumentException("Unknown package: " + packageName);
23338            }
23339            IBinder ksh = ks.getToken();
23340            if (ksh instanceof KeySetHandle) {
23341                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23342                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23343            }
23344            return false;
23345        }
23346    }
23347
23348    private void deletePackageIfUnusedLPr(final String packageName) {
23349        PackageSetting ps = mSettings.mPackages.get(packageName);
23350        if (ps == null) {
23351            return;
23352        }
23353        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23354            // TODO Implement atomic delete if package is unused
23355            // It is currently possible that the package will be deleted even if it is installed
23356            // after this method returns.
23357            mHandler.post(new Runnable() {
23358                public void run() {
23359                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23360                            0, PackageManager.DELETE_ALL_USERS);
23361                }
23362            });
23363        }
23364    }
23365
23366    /**
23367     * Check and throw if the given before/after packages would be considered a
23368     * downgrade.
23369     */
23370    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23371            throws PackageManagerException {
23372        if (after.versionCode < before.mVersionCode) {
23373            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23374                    "Update version code " + after.versionCode + " is older than current "
23375                    + before.mVersionCode);
23376        } else if (after.versionCode == before.mVersionCode) {
23377            if (after.baseRevisionCode < before.baseRevisionCode) {
23378                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23379                        "Update base revision code " + after.baseRevisionCode
23380                        + " is older than current " + before.baseRevisionCode);
23381            }
23382
23383            if (!ArrayUtils.isEmpty(after.splitNames)) {
23384                for (int i = 0; i < after.splitNames.length; i++) {
23385                    final String splitName = after.splitNames[i];
23386                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23387                    if (j != -1) {
23388                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23389                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23390                                    "Update split " + splitName + " revision code "
23391                                    + after.splitRevisionCodes[i] + " is older than current "
23392                                    + before.splitRevisionCodes[j]);
23393                        }
23394                    }
23395                }
23396            }
23397        }
23398    }
23399
23400    private static class MoveCallbacks extends Handler {
23401        private static final int MSG_CREATED = 1;
23402        private static final int MSG_STATUS_CHANGED = 2;
23403
23404        private final RemoteCallbackList<IPackageMoveObserver>
23405                mCallbacks = new RemoteCallbackList<>();
23406
23407        private final SparseIntArray mLastStatus = new SparseIntArray();
23408
23409        public MoveCallbacks(Looper looper) {
23410            super(looper);
23411        }
23412
23413        public void register(IPackageMoveObserver callback) {
23414            mCallbacks.register(callback);
23415        }
23416
23417        public void unregister(IPackageMoveObserver callback) {
23418            mCallbacks.unregister(callback);
23419        }
23420
23421        @Override
23422        public void handleMessage(Message msg) {
23423            final SomeArgs args = (SomeArgs) msg.obj;
23424            final int n = mCallbacks.beginBroadcast();
23425            for (int i = 0; i < n; i++) {
23426                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23427                try {
23428                    invokeCallback(callback, msg.what, args);
23429                } catch (RemoteException ignored) {
23430                }
23431            }
23432            mCallbacks.finishBroadcast();
23433            args.recycle();
23434        }
23435
23436        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23437                throws RemoteException {
23438            switch (what) {
23439                case MSG_CREATED: {
23440                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23441                    break;
23442                }
23443                case MSG_STATUS_CHANGED: {
23444                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23445                    break;
23446                }
23447            }
23448        }
23449
23450        private void notifyCreated(int moveId, Bundle extras) {
23451            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23452
23453            final SomeArgs args = SomeArgs.obtain();
23454            args.argi1 = moveId;
23455            args.arg2 = extras;
23456            obtainMessage(MSG_CREATED, args).sendToTarget();
23457        }
23458
23459        private void notifyStatusChanged(int moveId, int status) {
23460            notifyStatusChanged(moveId, status, -1);
23461        }
23462
23463        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23464            Slog.v(TAG, "Move " + moveId + " status " + status);
23465
23466            final SomeArgs args = SomeArgs.obtain();
23467            args.argi1 = moveId;
23468            args.argi2 = status;
23469            args.arg3 = estMillis;
23470            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23471
23472            synchronized (mLastStatus) {
23473                mLastStatus.put(moveId, status);
23474            }
23475        }
23476    }
23477
23478    private final static class OnPermissionChangeListeners extends Handler {
23479        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23480
23481        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23482                new RemoteCallbackList<>();
23483
23484        public OnPermissionChangeListeners(Looper looper) {
23485            super(looper);
23486        }
23487
23488        @Override
23489        public void handleMessage(Message msg) {
23490            switch (msg.what) {
23491                case MSG_ON_PERMISSIONS_CHANGED: {
23492                    final int uid = msg.arg1;
23493                    handleOnPermissionsChanged(uid);
23494                } break;
23495            }
23496        }
23497
23498        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23499            mPermissionListeners.register(listener);
23500
23501        }
23502
23503        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23504            mPermissionListeners.unregister(listener);
23505        }
23506
23507        public void onPermissionsChanged(int uid) {
23508            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23509                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23510            }
23511        }
23512
23513        private void handleOnPermissionsChanged(int uid) {
23514            final int count = mPermissionListeners.beginBroadcast();
23515            try {
23516                for (int i = 0; i < count; i++) {
23517                    IOnPermissionsChangeListener callback = mPermissionListeners
23518                            .getBroadcastItem(i);
23519                    try {
23520                        callback.onPermissionsChanged(uid);
23521                    } catch (RemoteException e) {
23522                        Log.e(TAG, "Permission listener is dead", e);
23523                    }
23524                }
23525            } finally {
23526                mPermissionListeners.finishBroadcast();
23527            }
23528        }
23529    }
23530
23531    private class PackageManagerNative extends IPackageManagerNative.Stub {
23532        @Override
23533        public String[] getNamesForUids(int[] uids) throws RemoteException {
23534            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23535            // massage results so they can be parsed by the native binder
23536            for (int i = results.length - 1; i >= 0; --i) {
23537                if (results[i] == null) {
23538                    results[i] = "";
23539                }
23540            }
23541            return results;
23542        }
23543
23544        // NB: this differentiates between preloads and sideloads
23545        @Override
23546        public String getInstallerForPackage(String packageName) throws RemoteException {
23547            final String installerName = getInstallerPackageName(packageName);
23548            if (!TextUtils.isEmpty(installerName)) {
23549                return installerName;
23550            }
23551            // differentiate between preload and sideload
23552            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23553            ApplicationInfo appInfo = getApplicationInfo(packageName,
23554                                    /*flags*/ 0,
23555                                    /*userId*/ callingUser);
23556            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23557                return "preload";
23558            }
23559            return "";
23560        }
23561
23562        @Override
23563        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23564            try {
23565                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23566                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23567                if (pInfo != null) {
23568                    return pInfo.versionCode;
23569                }
23570            } catch (Exception e) {
23571            }
23572            return 0;
23573        }
23574    }
23575
23576    private class PackageManagerInternalImpl extends PackageManagerInternal {
23577        @Override
23578        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23579                int flagValues, int userId) {
23580            PackageManagerService.this.updatePermissionFlags(
23581                    permName, packageName, flagMask, flagValues, userId);
23582        }
23583
23584        @Override
23585        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23586            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23587        }
23588
23589        @Override
23590        public PackageParser.PermissionGroup getPermissionGroupTEMP(String groupName) {
23591            synchronized (mPackages) {
23592                return mPermissionGroups.get(groupName);
23593            }
23594        }
23595
23596        @Override
23597        public boolean isInstantApp(String packageName, int userId) {
23598            return PackageManagerService.this.isInstantApp(packageName, userId);
23599        }
23600
23601        @Override
23602        public String getInstantAppPackageName(int uid) {
23603            return PackageManagerService.this.getInstantAppPackageName(uid);
23604        }
23605
23606        @Override
23607        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23608            synchronized (mPackages) {
23609                return PackageManagerService.this.filterAppAccessLPr(
23610                        (PackageSetting) pkg.mExtras, callingUid, userId);
23611            }
23612        }
23613
23614        @Override
23615        public PackageParser.Package getPackage(String packageName) {
23616            synchronized (mPackages) {
23617                packageName = resolveInternalPackageNameLPr(
23618                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23619                return mPackages.get(packageName);
23620            }
23621        }
23622
23623        @Override
23624        public PackageParser.Package getDisabledPackage(String packageName) {
23625            synchronized (mPackages) {
23626                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23627                return (ps != null) ? ps.pkg : null;
23628            }
23629        }
23630
23631        @Override
23632        public String getKnownPackageName(int knownPackage, int userId) {
23633            switch(knownPackage) {
23634                case PackageManagerInternal.PACKAGE_BROWSER:
23635                    return getDefaultBrowserPackageName(userId);
23636                case PackageManagerInternal.PACKAGE_INSTALLER:
23637                    return mRequiredInstallerPackage;
23638                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23639                    return mSetupWizardPackage;
23640                case PackageManagerInternal.PACKAGE_SYSTEM:
23641                    return "android";
23642                case PackageManagerInternal.PACKAGE_VERIFIER:
23643                    return mRequiredVerifierPackage;
23644            }
23645            return null;
23646        }
23647
23648        @Override
23649        public boolean isResolveActivityComponent(ComponentInfo component) {
23650            return mResolveActivity.packageName.equals(component.packageName)
23651                    && mResolveActivity.name.equals(component.name);
23652        }
23653
23654        @Override
23655        public void setLocationPackagesProvider(PackagesProvider provider) {
23656            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23657        }
23658
23659        @Override
23660        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23661            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23662        }
23663
23664        @Override
23665        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23666            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23667        }
23668
23669        @Override
23670        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23671            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23672        }
23673
23674        @Override
23675        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23676            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23677        }
23678
23679        @Override
23680        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23681            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23682        }
23683
23684        @Override
23685        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23686            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23687        }
23688
23689        @Override
23690        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23691            synchronized (mPackages) {
23692                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23693            }
23694            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23695        }
23696
23697        @Override
23698        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23699            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23700                    packageName, userId);
23701        }
23702
23703        @Override
23704        public void setKeepUninstalledPackages(final List<String> packageList) {
23705            Preconditions.checkNotNull(packageList);
23706            List<String> removedFromList = null;
23707            synchronized (mPackages) {
23708                if (mKeepUninstalledPackages != null) {
23709                    final int packagesCount = mKeepUninstalledPackages.size();
23710                    for (int i = 0; i < packagesCount; i++) {
23711                        String oldPackage = mKeepUninstalledPackages.get(i);
23712                        if (packageList != null && packageList.contains(oldPackage)) {
23713                            continue;
23714                        }
23715                        if (removedFromList == null) {
23716                            removedFromList = new ArrayList<>();
23717                        }
23718                        removedFromList.add(oldPackage);
23719                    }
23720                }
23721                mKeepUninstalledPackages = new ArrayList<>(packageList);
23722                if (removedFromList != null) {
23723                    final int removedCount = removedFromList.size();
23724                    for (int i = 0; i < removedCount; i++) {
23725                        deletePackageIfUnusedLPr(removedFromList.get(i));
23726                    }
23727                }
23728            }
23729        }
23730
23731        @Override
23732        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23733            synchronized (mPackages) {
23734                // If we do not support permission review, done.
23735                if (!mPermissionReviewRequired) {
23736                    return false;
23737                }
23738
23739                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23740                if (packageSetting == null) {
23741                    return false;
23742                }
23743
23744                // Permission review applies only to apps not supporting the new permission model.
23745                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23746                    return false;
23747                }
23748
23749                // Legacy apps have the permission and get user consent on launch.
23750                PermissionsState permissionsState = packageSetting.getPermissionsState();
23751                return permissionsState.isPermissionReviewRequired(userId);
23752            }
23753        }
23754
23755        @Override
23756        public PackageInfo getPackageInfo(
23757                String packageName, int flags, int filterCallingUid, int userId) {
23758            return PackageManagerService.this
23759                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23760                            flags, filterCallingUid, userId);
23761        }
23762
23763        @Override
23764        public ApplicationInfo getApplicationInfo(
23765                String packageName, int flags, int filterCallingUid, int userId) {
23766            return PackageManagerService.this
23767                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23768        }
23769
23770        @Override
23771        public ActivityInfo getActivityInfo(
23772                ComponentName component, int flags, int filterCallingUid, int userId) {
23773            return PackageManagerService.this
23774                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23775        }
23776
23777        @Override
23778        public List<ResolveInfo> queryIntentActivities(
23779                Intent intent, int flags, int filterCallingUid, int userId) {
23780            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23781            return PackageManagerService.this
23782                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23783                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23784        }
23785
23786        @Override
23787        public List<ResolveInfo> queryIntentServices(
23788                Intent intent, int flags, int callingUid, int userId) {
23789            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23790            return PackageManagerService.this
23791                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23792                            false);
23793        }
23794
23795        @Override
23796        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23797                int userId) {
23798            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23799        }
23800
23801        @Override
23802        public void setDeviceAndProfileOwnerPackages(
23803                int deviceOwnerUserId, String deviceOwnerPackage,
23804                SparseArray<String> profileOwnerPackages) {
23805            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23806                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23807        }
23808
23809        @Override
23810        public boolean isPackageDataProtected(int userId, String packageName) {
23811            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23812        }
23813
23814        @Override
23815        public boolean isPackageEphemeral(int userId, String packageName) {
23816            synchronized (mPackages) {
23817                final PackageSetting ps = mSettings.mPackages.get(packageName);
23818                return ps != null ? ps.getInstantApp(userId) : false;
23819            }
23820        }
23821
23822        @Override
23823        public boolean wasPackageEverLaunched(String packageName, int userId) {
23824            synchronized (mPackages) {
23825                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23826            }
23827        }
23828
23829        @Override
23830        public void grantRuntimePermission(String packageName, String permName, int userId,
23831                boolean overridePolicy) {
23832            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23833                    permName, packageName, overridePolicy, getCallingUid(), userId,
23834                    mPermissionCallback);
23835        }
23836
23837        @Override
23838        public void revokeRuntimePermission(String packageName, String permName, int userId,
23839                boolean overridePolicy) {
23840            mPermissionManager.revokeRuntimePermission(
23841                    permName, packageName, overridePolicy, getCallingUid(), userId,
23842                    mPermissionCallback);
23843        }
23844
23845        @Override
23846        public String getNameForUid(int uid) {
23847            return PackageManagerService.this.getNameForUid(uid);
23848        }
23849
23850        @Override
23851        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23852                Intent origIntent, String resolvedType, String callingPackage,
23853                Bundle verificationBundle, int userId) {
23854            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23855                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23856                    userId);
23857        }
23858
23859        @Override
23860        public void grantEphemeralAccess(int userId, Intent intent,
23861                int targetAppId, int ephemeralAppId) {
23862            synchronized (mPackages) {
23863                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23864                        targetAppId, ephemeralAppId);
23865            }
23866        }
23867
23868        @Override
23869        public boolean isInstantAppInstallerComponent(ComponentName component) {
23870            synchronized (mPackages) {
23871                return mInstantAppInstallerActivity != null
23872                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23873            }
23874        }
23875
23876        @Override
23877        public void pruneInstantApps() {
23878            mInstantAppRegistry.pruneInstantApps();
23879        }
23880
23881        @Override
23882        public String getSetupWizardPackageName() {
23883            return mSetupWizardPackage;
23884        }
23885
23886        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23887            if (policy != null) {
23888                mExternalSourcesPolicy = policy;
23889            }
23890        }
23891
23892        @Override
23893        public boolean isPackagePersistent(String packageName) {
23894            synchronized (mPackages) {
23895                PackageParser.Package pkg = mPackages.get(packageName);
23896                return pkg != null
23897                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23898                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23899                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23900                        : false;
23901            }
23902        }
23903
23904        @Override
23905        public List<PackageInfo> getOverlayPackages(int userId) {
23906            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23907            synchronized (mPackages) {
23908                for (PackageParser.Package p : mPackages.values()) {
23909                    if (p.mOverlayTarget != null) {
23910                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23911                        if (pkg != null) {
23912                            overlayPackages.add(pkg);
23913                        }
23914                    }
23915                }
23916            }
23917            return overlayPackages;
23918        }
23919
23920        @Override
23921        public List<String> getTargetPackageNames(int userId) {
23922            List<String> targetPackages = new ArrayList<>();
23923            synchronized (mPackages) {
23924                for (PackageParser.Package p : mPackages.values()) {
23925                    if (p.mOverlayTarget == null) {
23926                        targetPackages.add(p.packageName);
23927                    }
23928                }
23929            }
23930            return targetPackages;
23931        }
23932
23933        @Override
23934        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23935                @Nullable List<String> overlayPackageNames) {
23936            synchronized (mPackages) {
23937                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23938                    Slog.e(TAG, "failed to find package " + targetPackageName);
23939                    return false;
23940                }
23941                ArrayList<String> overlayPaths = null;
23942                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23943                    final int N = overlayPackageNames.size();
23944                    overlayPaths = new ArrayList<>(N);
23945                    for (int i = 0; i < N; i++) {
23946                        final String packageName = overlayPackageNames.get(i);
23947                        final PackageParser.Package pkg = mPackages.get(packageName);
23948                        if (pkg == null) {
23949                            Slog.e(TAG, "failed to find package " + packageName);
23950                            return false;
23951                        }
23952                        overlayPaths.add(pkg.baseCodePath);
23953                    }
23954                }
23955
23956                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23957                ps.setOverlayPaths(overlayPaths, userId);
23958                return true;
23959            }
23960        }
23961
23962        @Override
23963        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23964                int flags, int userId, boolean resolveForStart) {
23965            return resolveIntentInternal(
23966                    intent, resolvedType, flags, userId, resolveForStart);
23967        }
23968
23969        @Override
23970        public ResolveInfo resolveService(Intent intent, String resolvedType,
23971                int flags, int userId, int callingUid) {
23972            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23973        }
23974
23975        @Override
23976        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23977            return PackageManagerService.this.resolveContentProviderInternal(
23978                    name, flags, userId);
23979        }
23980
23981        @Override
23982        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23983            synchronized (mPackages) {
23984                mIsolatedOwners.put(isolatedUid, ownerUid);
23985            }
23986        }
23987
23988        @Override
23989        public void removeIsolatedUid(int isolatedUid) {
23990            synchronized (mPackages) {
23991                mIsolatedOwners.delete(isolatedUid);
23992            }
23993        }
23994
23995        @Override
23996        public int getUidTargetSdkVersion(int uid) {
23997            synchronized (mPackages) {
23998                return getUidTargetSdkVersionLockedLPr(uid);
23999            }
24000        }
24001
24002        @Override
24003        public boolean canAccessInstantApps(int callingUid, int userId) {
24004            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24005        }
24006
24007        @Override
24008        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24009            synchronized (mPackages) {
24010                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24011            }
24012        }
24013
24014        @Override
24015        public void notifyPackageUse(String packageName, int reason) {
24016            synchronized (mPackages) {
24017                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24018            }
24019        }
24020    }
24021
24022    @Override
24023    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24024        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24025        synchronized (mPackages) {
24026            final long identity = Binder.clearCallingIdentity();
24027            try {
24028                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24029                        packageNames, userId);
24030            } finally {
24031                Binder.restoreCallingIdentity(identity);
24032            }
24033        }
24034    }
24035
24036    @Override
24037    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24038        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24039        synchronized (mPackages) {
24040            final long identity = Binder.clearCallingIdentity();
24041            try {
24042                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24043                        packageNames, userId);
24044            } finally {
24045                Binder.restoreCallingIdentity(identity);
24046            }
24047        }
24048    }
24049
24050    private static void enforceSystemOrPhoneCaller(String tag) {
24051        int callingUid = Binder.getCallingUid();
24052        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24053            throw new SecurityException(
24054                    "Cannot call " + tag + " from UID " + callingUid);
24055        }
24056    }
24057
24058    boolean isHistoricalPackageUsageAvailable() {
24059        return mPackageUsage.isHistoricalPackageUsageAvailable();
24060    }
24061
24062    /**
24063     * Return a <b>copy</b> of the collection of packages known to the package manager.
24064     * @return A copy of the values of mPackages.
24065     */
24066    Collection<PackageParser.Package> getPackages() {
24067        synchronized (mPackages) {
24068            return new ArrayList<>(mPackages.values());
24069        }
24070    }
24071
24072    /**
24073     * Logs process start information (including base APK hash) to the security log.
24074     * @hide
24075     */
24076    @Override
24077    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24078            String apkFile, int pid) {
24079        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24080            return;
24081        }
24082        if (!SecurityLog.isLoggingEnabled()) {
24083            return;
24084        }
24085        Bundle data = new Bundle();
24086        data.putLong("startTimestamp", System.currentTimeMillis());
24087        data.putString("processName", processName);
24088        data.putInt("uid", uid);
24089        data.putString("seinfo", seinfo);
24090        data.putString("apkFile", apkFile);
24091        data.putInt("pid", pid);
24092        Message msg = mProcessLoggingHandler.obtainMessage(
24093                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24094        msg.setData(data);
24095        mProcessLoggingHandler.sendMessage(msg);
24096    }
24097
24098    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24099        return mCompilerStats.getPackageStats(pkgName);
24100    }
24101
24102    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24103        return getOrCreateCompilerPackageStats(pkg.packageName);
24104    }
24105
24106    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24107        return mCompilerStats.getOrCreatePackageStats(pkgName);
24108    }
24109
24110    public void deleteCompilerPackageStats(String pkgName) {
24111        mCompilerStats.deletePackageStats(pkgName);
24112    }
24113
24114    @Override
24115    public int getInstallReason(String packageName, int userId) {
24116        final int callingUid = Binder.getCallingUid();
24117        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24118                true /* requireFullPermission */, false /* checkShell */,
24119                "get install reason");
24120        synchronized (mPackages) {
24121            final PackageSetting ps = mSettings.mPackages.get(packageName);
24122            if (filterAppAccessLPr(ps, callingUid, userId)) {
24123                return PackageManager.INSTALL_REASON_UNKNOWN;
24124            }
24125            if (ps != null) {
24126                return ps.getInstallReason(userId);
24127            }
24128        }
24129        return PackageManager.INSTALL_REASON_UNKNOWN;
24130    }
24131
24132    @Override
24133    public boolean canRequestPackageInstalls(String packageName, int userId) {
24134        return canRequestPackageInstallsInternal(packageName, 0, userId,
24135                true /* throwIfPermNotDeclared*/);
24136    }
24137
24138    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24139            boolean throwIfPermNotDeclared) {
24140        int callingUid = Binder.getCallingUid();
24141        int uid = getPackageUid(packageName, 0, userId);
24142        if (callingUid != uid && callingUid != Process.ROOT_UID
24143                && callingUid != Process.SYSTEM_UID) {
24144            throw new SecurityException(
24145                    "Caller uid " + callingUid + " does not own package " + packageName);
24146        }
24147        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24148        if (info == null) {
24149            return false;
24150        }
24151        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24152            return false;
24153        }
24154        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24155        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24156        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24157            if (throwIfPermNotDeclared) {
24158                throw new SecurityException("Need to declare " + appOpPermission
24159                        + " to call this api");
24160            } else {
24161                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24162                return false;
24163            }
24164        }
24165        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24166            return false;
24167        }
24168        if (mExternalSourcesPolicy != null) {
24169            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24170            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24171                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24172            }
24173        }
24174        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24175    }
24176
24177    @Override
24178    public ComponentName getInstantAppResolverSettingsComponent() {
24179        return mInstantAppResolverSettingsComponent;
24180    }
24181
24182    @Override
24183    public ComponentName getInstantAppInstallerComponent() {
24184        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24185            return null;
24186        }
24187        return mInstantAppInstallerActivity == null
24188                ? null : mInstantAppInstallerActivity.getComponentName();
24189    }
24190
24191    @Override
24192    public String getInstantAppAndroidId(String packageName, int userId) {
24193        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24194                "getInstantAppAndroidId");
24195        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24196                true /* requireFullPermission */, false /* checkShell */,
24197                "getInstantAppAndroidId");
24198        // Make sure the target is an Instant App.
24199        if (!isInstantApp(packageName, userId)) {
24200            return null;
24201        }
24202        synchronized (mPackages) {
24203            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24204        }
24205    }
24206
24207    boolean canHaveOatDir(String packageName) {
24208        synchronized (mPackages) {
24209            PackageParser.Package p = mPackages.get(packageName);
24210            if (p == null) {
24211                return false;
24212            }
24213            return p.canHaveOatDir();
24214        }
24215    }
24216
24217    private String getOatDir(PackageParser.Package pkg) {
24218        if (!pkg.canHaveOatDir()) {
24219            return null;
24220        }
24221        File codePath = new File(pkg.codePath);
24222        if (codePath.isDirectory()) {
24223            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24224        }
24225        return null;
24226    }
24227
24228    void deleteOatArtifactsOfPackage(String packageName) {
24229        final String[] instructionSets;
24230        final List<String> codePaths;
24231        final String oatDir;
24232        final PackageParser.Package pkg;
24233        synchronized (mPackages) {
24234            pkg = mPackages.get(packageName);
24235        }
24236        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24237        codePaths = pkg.getAllCodePaths();
24238        oatDir = getOatDir(pkg);
24239
24240        for (String codePath : codePaths) {
24241            for (String isa : instructionSets) {
24242                try {
24243                    mInstaller.deleteOdex(codePath, isa, oatDir);
24244                } catch (InstallerException e) {
24245                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24246                }
24247            }
24248        }
24249    }
24250
24251    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24252        Set<String> unusedPackages = new HashSet<>();
24253        long currentTimeInMillis = System.currentTimeMillis();
24254        synchronized (mPackages) {
24255            for (PackageParser.Package pkg : mPackages.values()) {
24256                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24257                if (ps == null) {
24258                    continue;
24259                }
24260                PackageDexUsage.PackageUseInfo packageUseInfo =
24261                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24262                if (PackageManagerServiceUtils
24263                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24264                                downgradeTimeThresholdMillis, packageUseInfo,
24265                                pkg.getLatestPackageUseTimeInMills(),
24266                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24267                    unusedPackages.add(pkg.packageName);
24268                }
24269            }
24270        }
24271        return unusedPackages;
24272    }
24273}
24274
24275interface PackageSender {
24276    void sendPackageBroadcast(final String action, final String pkg,
24277        final Bundle extras, final int flags, final String targetPkg,
24278        final IIntentReceiver finishedReceiver, final int[] userIds);
24279    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24280        boolean includeStopped, int appId, int... userIds);
24281}
24282