PackageManagerService.java revision 0eb9738d1708d9aa7846782046e6828ffc9fe901
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_OEM;
86import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
87import static android.content.pm.PackageParser.isApkFile;
88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
89import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
90import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
91import static android.system.OsConstants.O_CREAT;
92import static android.system.OsConstants.O_RDWR;
93
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
95import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
96import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
97import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
98import static com.android.internal.util.ArrayUtils.appendInt;
99import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
101import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
102import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
103import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
105import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
108import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManagerInternal;
163import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.Package;
167import android.content.pm.PackageParser.PackageLite;
168import android.content.pm.PackageParser.PackageParserException;
169import android.content.pm.PackageStats;
170import android.content.pm.PackageUserState;
171import android.content.pm.ParceledListSlice;
172import android.content.pm.PermissionGroupInfo;
173import android.content.pm.PermissionInfo;
174import android.content.pm.ProviderInfo;
175import android.content.pm.ResolveInfo;
176import android.content.pm.ServiceInfo;
177import android.content.pm.SharedLibraryInfo;
178import android.content.pm.Signature;
179import android.content.pm.UserInfo;
180import android.content.pm.VerifierDeviceIdentity;
181import android.content.pm.VerifierInfo;
182import android.content.pm.VersionedPackage;
183import android.content.res.Resources;
184import android.database.ContentObserver;
185import android.graphics.Bitmap;
186import android.hardware.display.DisplayManager;
187import android.net.Uri;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Debug;
192import android.os.Environment;
193import android.os.Environment.UserEnvironment;
194import android.os.FileUtils;
195import android.os.Handler;
196import android.os.IBinder;
197import android.os.Looper;
198import android.os.Message;
199import android.os.Parcel;
200import android.os.ParcelFileDescriptor;
201import android.os.PatternMatcher;
202import android.os.Process;
203import android.os.RemoteCallbackList;
204import android.os.RemoteException;
205import android.os.ResultReceiver;
206import android.os.SELinux;
207import android.os.ServiceManager;
208import android.os.ShellCallback;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.Trace;
212import android.os.UserHandle;
213import android.os.UserManager;
214import android.os.UserManagerInternal;
215import android.os.storage.IStorageManager;
216import android.os.storage.StorageEventListener;
217import android.os.storage.StorageManager;
218import android.os.storage.StorageManagerInternal;
219import android.os.storage.VolumeInfo;
220import android.os.storage.VolumeRecord;
221import android.provider.Settings.Global;
222import android.provider.Settings.Secure;
223import android.security.KeyStore;
224import android.security.SystemKeyStore;
225import android.service.pm.PackageServiceDumpProto;
226import android.system.ErrnoException;
227import android.system.Os;
228import android.text.TextUtils;
229import android.text.format.DateUtils;
230import android.util.ArrayMap;
231import android.util.ArraySet;
232import android.util.Base64;
233import android.util.TimingsTraceLog;
234import android.util.DisplayMetrics;
235import android.util.EventLog;
236import android.util.ExceptionUtils;
237import android.util.Log;
238import android.util.LogPrinter;
239import android.util.MathUtils;
240import android.util.PackageUtils;
241import android.util.Pair;
242import android.util.PrintStreamPrinter;
243import android.util.Slog;
244import android.util.SparseArray;
245import android.util.SparseBooleanArray;
246import android.util.SparseIntArray;
247import android.util.Xml;
248import android.util.jar.StrictJarFile;
249import android.util.proto.ProtoOutputStream;
250import android.view.Display;
251
252import com.android.internal.R;
253import com.android.internal.annotations.GuardedBy;
254import com.android.internal.app.IMediaContainerService;
255import com.android.internal.app.ResolverActivity;
256import com.android.internal.content.NativeLibraryHelper;
257import com.android.internal.content.PackageHelper;
258import com.android.internal.logging.MetricsLogger;
259import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
260import com.android.internal.os.IParcelFileDescriptorFactory;
261import com.android.internal.os.RoSystemProperties;
262import com.android.internal.os.SomeArgs;
263import com.android.internal.os.Zygote;
264import com.android.internal.telephony.CarrierAppUtils;
265import com.android.internal.util.ArrayUtils;
266import com.android.internal.util.ConcurrentUtils;
267import com.android.internal.util.DumpUtils;
268import com.android.internal.util.FastPrintWriter;
269import com.android.internal.util.FastXmlSerializer;
270import com.android.internal.util.IndentingPrintWriter;
271import com.android.internal.util.Preconditions;
272import com.android.internal.util.XmlUtils;
273import com.android.server.AttributeCache;
274import com.android.server.DeviceIdleController;
275import com.android.server.EventLogTags;
276import com.android.server.FgThread;
277import com.android.server.IntentResolver;
278import com.android.server.LocalServices;
279import com.android.server.LockGuard;
280import com.android.server.ServiceThread;
281import com.android.server.SystemConfig;
282import com.android.server.SystemServerInitThreadPool;
283import com.android.server.Watchdog;
284import com.android.server.net.NetworkPolicyManagerInternal;
285import com.android.server.pm.Installer.InstallerException;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.pm.permission.BasePermission;
292import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
293import com.android.server.pm.permission.PermissionManagerService;
294import com.android.server.pm.permission.PermissionManagerInternal;
295import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
296import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
297import com.android.server.pm.permission.PermissionsState;
298import com.android.server.pm.permission.PermissionsState.PermissionState;
299import com.android.server.storage.DeviceStorageMonitorInternal;
300
301import dalvik.system.CloseGuard;
302import dalvik.system.DexFile;
303import dalvik.system.VMRuntime;
304
305import libcore.io.IoUtils;
306import libcore.io.Streams;
307import libcore.util.EmptyArray;
308
309import org.xmlpull.v1.XmlPullParser;
310import org.xmlpull.v1.XmlPullParserException;
311import org.xmlpull.v1.XmlSerializer;
312
313import java.io.BufferedOutputStream;
314import java.io.BufferedReader;
315import java.io.ByteArrayInputStream;
316import java.io.ByteArrayOutputStream;
317import java.io.File;
318import java.io.FileDescriptor;
319import java.io.FileInputStream;
320import java.io.FileOutputStream;
321import java.io.FileReader;
322import java.io.FilenameFilter;
323import java.io.IOException;
324import java.io.InputStream;
325import java.io.OutputStream;
326import java.io.PrintWriter;
327import java.lang.annotation.Retention;
328import java.lang.annotation.RetentionPolicy;
329import java.nio.charset.StandardCharsets;
330import java.security.DigestInputStream;
331import java.security.MessageDigest;
332import java.security.NoSuchAlgorithmException;
333import java.security.PublicKey;
334import java.security.SecureRandom;
335import java.security.cert.Certificate;
336import java.security.cert.CertificateEncodingException;
337import java.security.cert.CertificateException;
338import java.text.SimpleDateFormat;
339import java.util.ArrayList;
340import java.util.Arrays;
341import java.util.Collection;
342import java.util.Collections;
343import java.util.Comparator;
344import java.util.Date;
345import java.util.HashMap;
346import java.util.HashSet;
347import java.util.Iterator;
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    private 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    private 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    /** The location for ASEC container files on internal storage. */
663    final String mAsecInternalPath;
664
665    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
666    // LOCK HELD.  Can be called with mInstallLock held.
667    @GuardedBy("mInstallLock")
668    final Installer mInstaller;
669
670    /** Directory where installed third-party apps stored */
671    final File mAppInstallDir;
672
673    /**
674     * Directory to which applications installed internally have their
675     * 32 bit native libraries copied.
676     */
677    private File mAppLib32InstallDir;
678
679    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
680    // apps.
681    final File mDrmAppPrivateInstallDir;
682
683    // ----------------------------------------------------------------
684
685    // Lock for state used when installing and doing other long running
686    // operations.  Methods that must be called with this lock held have
687    // the suffix "LI".
688    final Object mInstallLock = new Object();
689
690    // ----------------------------------------------------------------
691
692    // Keys are String (package name), values are Package.  This also serves
693    // as the lock for the global state.  Methods that must be called with
694    // this lock held have the prefix "LP".
695    @GuardedBy("mPackages")
696    final ArrayMap<String, PackageParser.Package> mPackages =
697            new ArrayMap<String, PackageParser.Package>();
698
699    final ArrayMap<String, Set<String>> mKnownCodebase =
700            new ArrayMap<String, Set<String>>();
701
702    // Keys are isolated uids and values are the uid of the application
703    // that created the isolated proccess.
704    @GuardedBy("mPackages")
705    final SparseIntArray mIsolatedOwners = new SparseIntArray();
706
707    /**
708     * Tracks new system packages [received in an OTA] that we expect to
709     * find updated user-installed versions. Keys are package name, values
710     * are package location.
711     */
712    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
713    /**
714     * Tracks high priority intent filters for protected actions. During boot, certain
715     * filter actions are protected and should never be allowed to have a high priority
716     * intent filter for them. However, there is one, and only one exception -- the
717     * setup wizard. It must be able to define a high priority intent filter for these
718     * actions to ensure there are no escapes from the wizard. We need to delay processing
719     * of these during boot as we need to look at all of the system packages in order
720     * to know which component is the setup wizard.
721     */
722    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
723    /**
724     * Whether or not processing protected filters should be deferred.
725     */
726    private boolean mDeferProtectedFilters = true;
727
728    /**
729     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
730     */
731    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
732    /**
733     * Whether or not system app permissions should be promoted from install to runtime.
734     */
735    boolean mPromoteSystemApps;
736
737    @GuardedBy("mPackages")
738    final Settings mSettings;
739
740    /**
741     * Set of package names that are currently "frozen", which means active
742     * surgery is being done on the code/data for that package. The platform
743     * will refuse to launch frozen packages to avoid race conditions.
744     *
745     * @see PackageFreezer
746     */
747    @GuardedBy("mPackages")
748    final ArraySet<String> mFrozenPackages = new ArraySet<>();
749
750    final ProtectedPackages mProtectedPackages;
751
752    @GuardedBy("mLoadedVolumes")
753    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
754
755    boolean mFirstBoot;
756
757    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
758
759    // System configuration read by SystemConfig.
760    final int[] mGlobalGids;
761    final SparseArray<ArraySet<String>> mSystemPermissions;
762    @GuardedBy("mAvailableFeatures")
763    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
764
765    // If mac_permissions.xml was found for seinfo labeling.
766    boolean mFoundPolicyFile;
767
768    private final InstantAppRegistry mInstantAppRegistry;
769
770    @GuardedBy("mPackages")
771    int mChangedPackagesSequenceNumber;
772    /**
773     * List of changed [installed, removed or updated] packages.
774     * mapping from user id -> sequence number -> package name
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
778    /**
779     * The sequence number of the last change to a package.
780     * mapping from user id -> package name -> sequence number
781     */
782    @GuardedBy("mPackages")
783    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
784
785    class PackageParserCallback implements PackageParser.Callback {
786        @Override public final boolean hasFeature(String feature) {
787            return PackageManagerService.this.hasSystemFeature(feature, 0);
788        }
789
790        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
791                Collection<PackageParser.Package> allPackages, String targetPackageName) {
792            List<PackageParser.Package> overlayPackages = null;
793            for (PackageParser.Package p : allPackages) {
794                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
795                    if (overlayPackages == null) {
796                        overlayPackages = new ArrayList<PackageParser.Package>();
797                    }
798                    overlayPackages.add(p);
799                }
800            }
801            if (overlayPackages != null) {
802                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
803                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
804                        return p1.mOverlayPriority - p2.mOverlayPriority;
805                    }
806                };
807                Collections.sort(overlayPackages, cmp);
808            }
809            return overlayPackages;
810        }
811
812        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
813                String targetPackageName, String targetPath) {
814            if ("android".equals(targetPackageName)) {
815                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
816                // native AssetManager.
817                return null;
818            }
819            List<PackageParser.Package> overlayPackages =
820                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
821            if (overlayPackages == null || overlayPackages.isEmpty()) {
822                return null;
823            }
824            List<String> overlayPathList = null;
825            for (PackageParser.Package overlayPackage : overlayPackages) {
826                if (targetPath == null) {
827                    if (overlayPathList == null) {
828                        overlayPathList = new ArrayList<String>();
829                    }
830                    overlayPathList.add(overlayPackage.baseCodePath);
831                    continue;
832                }
833
834                try {
835                    // Creates idmaps for system to parse correctly the Android manifest of the
836                    // target package.
837                    //
838                    // OverlayManagerService will update each of them with a correct gid from its
839                    // target package app id.
840                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
841                            UserHandle.getSharedAppGid(
842                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
843                    if (overlayPathList == null) {
844                        overlayPathList = new ArrayList<String>();
845                    }
846                    overlayPathList.add(overlayPackage.baseCodePath);
847                } catch (InstallerException e) {
848                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
849                            overlayPackage.baseCodePath);
850                }
851            }
852            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
853        }
854
855        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
856            synchronized (mPackages) {
857                return getStaticOverlayPathsLocked(
858                        mPackages.values(), targetPackageName, targetPath);
859            }
860        }
861
862        @Override public final String[] getOverlayApks(String targetPackageName) {
863            return getStaticOverlayPaths(targetPackageName, null);
864        }
865
866        @Override public final String[] getOverlayPaths(String targetPackageName,
867                String targetPath) {
868            return getStaticOverlayPaths(targetPackageName, targetPath);
869        }
870    }
871
872    class ParallelPackageParserCallback extends PackageParserCallback {
873        List<PackageParser.Package> mOverlayPackages = null;
874
875        void findStaticOverlayPackages() {
876            synchronized (mPackages) {
877                for (PackageParser.Package p : mPackages.values()) {
878                    if (p.mIsStaticOverlay) {
879                        if (mOverlayPackages == null) {
880                            mOverlayPackages = new ArrayList<PackageParser.Package>();
881                        }
882                        mOverlayPackages.add(p);
883                    }
884                }
885            }
886        }
887
888        @Override
889        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
890            // We can trust mOverlayPackages without holding mPackages because package uninstall
891            // can't happen while running parallel parsing.
892            // Moreover holding mPackages on each parsing thread causes dead-lock.
893            return mOverlayPackages == null ? null :
894                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
895        }
896    }
897
898    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
899    final ParallelPackageParserCallback mParallelPackageParserCallback =
900            new ParallelPackageParserCallback();
901
902    public static final class SharedLibraryEntry {
903        public final @Nullable String path;
904        public final @Nullable String apk;
905        public final @NonNull SharedLibraryInfo info;
906
907        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
908                String declaringPackageName, int declaringPackageVersionCode) {
909            path = _path;
910            apk = _apk;
911            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
912                    declaringPackageName, declaringPackageVersionCode), null);
913        }
914    }
915
916    // Currently known shared libraries.
917    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
918    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
919            new ArrayMap<>();
920
921    // All available activities, for your resolving pleasure.
922    final ActivityIntentResolver mActivities =
923            new ActivityIntentResolver();
924
925    // All available receivers, for your resolving pleasure.
926    final ActivityIntentResolver mReceivers =
927            new ActivityIntentResolver();
928
929    // All available services, for your resolving pleasure.
930    final ServiceIntentResolver mServices = new ServiceIntentResolver();
931
932    // All available providers, for your resolving pleasure.
933    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
934
935    // Mapping from provider base names (first directory in content URI codePath)
936    // to the provider information.
937    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
938            new ArrayMap<String, PackageParser.Provider>();
939
940    // Mapping from instrumentation class names to info about them.
941    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
942            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
943
944    // Mapping from permission names to info about them.
945    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
946            new ArrayMap<String, PackageParser.PermissionGroup>();
947
948    // Packages whose data we have transfered into another package, thus
949    // should no longer exist.
950    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
951
952    // Broadcast actions that are only available to the system.
953    @GuardedBy("mProtectedBroadcasts")
954    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
955
956    /** List of packages waiting for verification. */
957    final SparseArray<PackageVerificationState> mPendingVerification
958            = new SparseArray<PackageVerificationState>();
959
960    /** Set of packages associated with each app op permission. */
961    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
962
963    final PackageInstallerService mInstallerService;
964
965    private final PackageDexOptimizer mPackageDexOptimizer;
966    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
967    // is used by other apps).
968    private final DexManager mDexManager;
969
970    private AtomicInteger mNextMoveId = new AtomicInteger();
971    private final MoveCallbacks mMoveCallbacks;
972
973    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
974
975    // Cache of users who need badging.
976    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
977
978    /** Token for keys in mPendingVerification. */
979    private int mPendingVerificationToken = 0;
980
981    volatile boolean mSystemReady;
982    volatile boolean mSafeMode;
983    volatile boolean mHasSystemUidErrors;
984    private volatile boolean mEphemeralAppsDisabled;
985
986    ApplicationInfo mAndroidApplication;
987    final ActivityInfo mResolveActivity = new ActivityInfo();
988    final ResolveInfo mResolveInfo = new ResolveInfo();
989    ComponentName mResolveComponentName;
990    PackageParser.Package mPlatformPackage;
991    ComponentName mCustomResolverComponentName;
992
993    boolean mResolverReplaced = false;
994
995    private final @Nullable ComponentName mIntentFilterVerifierComponent;
996    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
997
998    private int mIntentFilterVerificationToken = 0;
999
1000    /** The service connection to the ephemeral resolver */
1001    final EphemeralResolverConnection mInstantAppResolverConnection;
1002    /** Component used to show resolver settings for Instant Apps */
1003    final ComponentName mInstantAppResolverSettingsComponent;
1004
1005    /** Activity used to install instant applications */
1006    ActivityInfo mInstantAppInstallerActivity;
1007    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1008
1009    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1010            = new SparseArray<IntentFilterVerificationState>();
1011
1012    // TODO remove this and go through mPermissonManager directly
1013    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1014    private final PermissionManagerInternal mPermissionManager;
1015
1016    // List of packages names to keep cached, even if they are uninstalled for all users
1017    private List<String> mKeepUninstalledPackages;
1018
1019    private UserManagerInternal mUserManagerInternal;
1020
1021    private DeviceIdleController.LocalService mDeviceIdleController;
1022
1023    private File mCacheDir;
1024
1025    private ArraySet<String> mPrivappPermissionsViolations;
1026
1027    private Future<?> mPrepareAppDataFuture;
1028
1029    private static class IFVerificationParams {
1030        PackageParser.Package pkg;
1031        boolean replacing;
1032        int userId;
1033        int verifierUid;
1034
1035        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1036                int _userId, int _verifierUid) {
1037            pkg = _pkg;
1038            replacing = _replacing;
1039            userId = _userId;
1040            replacing = _replacing;
1041            verifierUid = _verifierUid;
1042        }
1043    }
1044
1045    private interface IntentFilterVerifier<T extends IntentFilter> {
1046        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1047                                               T filter, String packageName);
1048        void startVerifications(int userId);
1049        void receiveVerificationResponse(int verificationId);
1050    }
1051
1052    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1053        private Context mContext;
1054        private ComponentName mIntentFilterVerifierComponent;
1055        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1056
1057        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1058            mContext = context;
1059            mIntentFilterVerifierComponent = verifierComponent;
1060        }
1061
1062        private String getDefaultScheme() {
1063            return IntentFilter.SCHEME_HTTPS;
1064        }
1065
1066        @Override
1067        public void startVerifications(int userId) {
1068            // Launch verifications requests
1069            int count = mCurrentIntentFilterVerifications.size();
1070            for (int n=0; n<count; n++) {
1071                int verificationId = mCurrentIntentFilterVerifications.get(n);
1072                final IntentFilterVerificationState ivs =
1073                        mIntentFilterVerificationStates.get(verificationId);
1074
1075                String packageName = ivs.getPackageName();
1076
1077                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1078                final int filterCount = filters.size();
1079                ArraySet<String> domainsSet = new ArraySet<>();
1080                for (int m=0; m<filterCount; m++) {
1081                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1082                    domainsSet.addAll(filter.getHostsList());
1083                }
1084                synchronized (mPackages) {
1085                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1086                            packageName, domainsSet) != null) {
1087                        scheduleWriteSettingsLocked();
1088                    }
1089                }
1090                sendVerificationRequest(verificationId, ivs);
1091            }
1092            mCurrentIntentFilterVerifications.clear();
1093        }
1094
1095        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1096            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1099                    verificationId);
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1102                    getDefaultScheme());
1103            verificationIntent.putExtra(
1104                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1105                    ivs.getHostsString());
1106            verificationIntent.putExtra(
1107                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1108                    ivs.getPackageName());
1109            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1110            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1111
1112            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1113            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1114                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1115                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1116
1117            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1118            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1119                    "Sending IntentFilter verification broadcast");
1120        }
1121
1122        public void receiveVerificationResponse(int verificationId) {
1123            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1124
1125            final boolean verified = ivs.isVerified();
1126
1127            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1128            final int count = filters.size();
1129            if (DEBUG_DOMAIN_VERIFICATION) {
1130                Slog.i(TAG, "Received verification response " + verificationId
1131                        + " for " + count + " filters, verified=" + verified);
1132            }
1133            for (int n=0; n<count; n++) {
1134                PackageParser.ActivityIntentInfo filter = filters.get(n);
1135                filter.setVerified(verified);
1136
1137                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1138                        + " verified with result:" + verified + " and hosts:"
1139                        + ivs.getHostsString());
1140            }
1141
1142            mIntentFilterVerificationStates.remove(verificationId);
1143
1144            final String packageName = ivs.getPackageName();
1145            IntentFilterVerificationInfo ivi = null;
1146
1147            synchronized (mPackages) {
1148                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1149            }
1150            if (ivi == null) {
1151                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1152                        + verificationId + " packageName:" + packageName);
1153                return;
1154            }
1155            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1156                    "Updating IntentFilterVerificationInfo for package " + packageName
1157                            +" verificationId:" + verificationId);
1158
1159            synchronized (mPackages) {
1160                if (verified) {
1161                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1162                } else {
1163                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1164                }
1165                scheduleWriteSettingsLocked();
1166
1167                final int userId = ivs.getUserId();
1168                if (userId != UserHandle.USER_ALL) {
1169                    final int userStatus =
1170                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1171
1172                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1173                    boolean needUpdate = false;
1174
1175                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1176                    // already been set by the User thru the Disambiguation dialog
1177                    switch (userStatus) {
1178                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1179                            if (verified) {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1181                            } else {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1183                            }
1184                            needUpdate = true;
1185                            break;
1186
1187                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1188                            if (verified) {
1189                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1190                                needUpdate = true;
1191                            }
1192                            break;
1193
1194                        default:
1195                            // Nothing to do
1196                    }
1197
1198                    if (needUpdate) {
1199                        mSettings.updateIntentFilterVerificationStatusLPw(
1200                                packageName, updatedStatus, userId);
1201                        scheduleWritePackageRestrictionsLocked(userId);
1202                    }
1203                }
1204            }
1205        }
1206
1207        @Override
1208        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1209                    ActivityIntentInfo filter, String packageName) {
1210            if (!hasValidDomains(filter)) {
1211                return false;
1212            }
1213            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1214            if (ivs == null) {
1215                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1216                        packageName);
1217            }
1218            if (DEBUG_DOMAIN_VERIFICATION) {
1219                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1220            }
1221            ivs.addFilter(filter);
1222            return true;
1223        }
1224
1225        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1226                int userId, int verificationId, String packageName) {
1227            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1228                    verifierUid, userId, packageName);
1229            ivs.setPendingState();
1230            synchronized (mPackages) {
1231                mIntentFilterVerificationStates.append(verificationId, ivs);
1232                mCurrentIntentFilterVerifications.add(verificationId);
1233            }
1234            return ivs;
1235        }
1236    }
1237
1238    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1239        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1240                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1241                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1242    }
1243
1244    // Set of pending broadcasts for aggregating enable/disable of components.
1245    static class PendingPackageBroadcasts {
1246        // for each user id, a map of <package name -> components within that package>
1247        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1248
1249        public PendingPackageBroadcasts() {
1250            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1251        }
1252
1253        public ArrayList<String> get(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1255            return packages.get(packageName);
1256        }
1257
1258        public void put(int userId, String packageName, ArrayList<String> components) {
1259            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1260            packages.put(packageName, components);
1261        }
1262
1263        public void remove(int userId, String packageName) {
1264            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1265            if (packages != null) {
1266                packages.remove(packageName);
1267            }
1268        }
1269
1270        public void remove(int userId) {
1271            mUidMap.remove(userId);
1272        }
1273
1274        public int userIdCount() {
1275            return mUidMap.size();
1276        }
1277
1278        public int userIdAt(int n) {
1279            return mUidMap.keyAt(n);
1280        }
1281
1282        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1283            return mUidMap.get(userId);
1284        }
1285
1286        public int size() {
1287            // total number of pending broadcast entries across all userIds
1288            int num = 0;
1289            for (int i = 0; i< mUidMap.size(); i++) {
1290                num += mUidMap.valueAt(i).size();
1291            }
1292            return num;
1293        }
1294
1295        public void clear() {
1296            mUidMap.clear();
1297        }
1298
1299        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1300            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1301            if (map == null) {
1302                map = new ArrayMap<String, ArrayList<String>>();
1303                mUidMap.put(userId, map);
1304            }
1305            return map;
1306        }
1307    }
1308    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1309
1310    // Service Connection to remote media container service to copy
1311    // package uri's from external media onto secure containers
1312    // or internal storage.
1313    private IMediaContainerService mContainerService = null;
1314
1315    static final int SEND_PENDING_BROADCAST = 1;
1316    static final int MCS_BOUND = 3;
1317    static final int END_COPY = 4;
1318    static final int INIT_COPY = 5;
1319    static final int MCS_UNBIND = 6;
1320    static final int START_CLEANING_PACKAGE = 7;
1321    static final int FIND_INSTALL_LOC = 8;
1322    static final int POST_INSTALL = 9;
1323    static final int MCS_RECONNECT = 10;
1324    static final int MCS_GIVE_UP = 11;
1325    static final int UPDATED_MEDIA_STATUS = 12;
1326    static final int WRITE_SETTINGS = 13;
1327    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1328    static final int PACKAGE_VERIFIED = 15;
1329    static final int CHECK_PENDING_VERIFICATION = 16;
1330    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1331    static final int INTENT_FILTER_VERIFIED = 18;
1332    static final int WRITE_PACKAGE_LIST = 19;
1333    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1334
1335    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1336
1337    // Delay time in millisecs
1338    static final int BROADCAST_DELAY = 10 * 1000;
1339
1340    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1341            2 * 60 * 60 * 1000L; /* two hours */
1342
1343    static UserManagerService sUserManager;
1344
1345    // Stores a list of users whose package restrictions file needs to be updated
1346    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1347
1348    final private DefaultContainerConnection mDefContainerConn =
1349            new DefaultContainerConnection();
1350    class DefaultContainerConnection implements ServiceConnection {
1351        public void onServiceConnected(ComponentName name, IBinder service) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1353            final IMediaContainerService imcs = IMediaContainerService.Stub
1354                    .asInterface(Binder.allowBlocking(service));
1355            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1356        }
1357
1358        public void onServiceDisconnected(ComponentName name) {
1359            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1360        }
1361    }
1362
1363    // Recordkeeping of restore-after-install operations that are currently in flight
1364    // between the Package Manager and the Backup Manager
1365    static class PostInstallData {
1366        public InstallArgs args;
1367        public PackageInstalledInfo res;
1368
1369        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1370            args = _a;
1371            res = _r;
1372        }
1373    }
1374
1375    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1376    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1377
1378    // XML tags for backup/restore of various bits of state
1379    private static final String TAG_PREFERRED_BACKUP = "pa";
1380    private static final String TAG_DEFAULT_APPS = "da";
1381    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1382
1383    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1384    private static final String TAG_ALL_GRANTS = "rt-grants";
1385    private static final String TAG_GRANT = "grant";
1386    private static final String ATTR_PACKAGE_NAME = "pkg";
1387
1388    private static final String TAG_PERMISSION = "perm";
1389    private static final String ATTR_PERMISSION_NAME = "name";
1390    private static final String ATTR_IS_GRANTED = "g";
1391    private static final String ATTR_USER_SET = "set";
1392    private static final String ATTR_USER_FIXED = "fixed";
1393    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1394
1395    // System/policy permission grants are not backed up
1396    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1397            FLAG_PERMISSION_POLICY_FIXED
1398            | FLAG_PERMISSION_SYSTEM_FIXED
1399            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1400
1401    // And we back up these user-adjusted states
1402    private static final int USER_RUNTIME_GRANT_MASK =
1403            FLAG_PERMISSION_USER_SET
1404            | FLAG_PERMISSION_USER_FIXED
1405            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1406
1407    final @Nullable String mRequiredVerifierPackage;
1408    final @NonNull String mRequiredInstallerPackage;
1409    final @NonNull String mRequiredUninstallerPackage;
1410    final @Nullable String mSetupWizardPackage;
1411    final @Nullable String mStorageManagerPackage;
1412    final @NonNull String mServicesSystemSharedLibraryPackageName;
1413    final @NonNull String mSharedSystemSharedLibraryPackageName;
1414
1415    final boolean mPermissionReviewRequired;
1416
1417    private final PackageUsage mPackageUsage = new PackageUsage();
1418    private final CompilerStats mCompilerStats = new CompilerStats();
1419
1420    class PackageHandler extends Handler {
1421        private boolean mBound = false;
1422        final ArrayList<HandlerParams> mPendingInstalls =
1423            new ArrayList<HandlerParams>();
1424
1425        private boolean connectToService() {
1426            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1427                    " DefaultContainerService");
1428            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1431                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433                mBound = true;
1434                return true;
1435            }
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1437            return false;
1438        }
1439
1440        private void disconnectService() {
1441            mContainerService = null;
1442            mBound = false;
1443            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1444            mContext.unbindService(mDefContainerConn);
1445            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1446        }
1447
1448        PackageHandler(Looper looper) {
1449            super(looper);
1450        }
1451
1452        public void handleMessage(Message msg) {
1453            try {
1454                doHandleMessage(msg);
1455            } finally {
1456                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1457            }
1458        }
1459
1460        void doHandleMessage(Message msg) {
1461            switch (msg.what) {
1462                case INIT_COPY: {
1463                    HandlerParams params = (HandlerParams) msg.obj;
1464                    int idx = mPendingInstalls.size();
1465                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1466                    // If a bind was already initiated we dont really
1467                    // need to do anything. The pending install
1468                    // will be processed later on.
1469                    if (!mBound) {
1470                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                System.identityHashCode(mHandler));
1472                        // If this is the only one pending we might
1473                        // have to bind to the service again.
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            params.serviceError();
1477                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1478                                    System.identityHashCode(mHandler));
1479                            if (params.traceMethod != null) {
1480                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1481                                        params.traceCookie);
1482                            }
1483                            return;
1484                        } else {
1485                            // Once we bind to the service, the first
1486                            // pending request will be processed.
1487                            mPendingInstalls.add(idx, params);
1488                        }
1489                    } else {
1490                        mPendingInstalls.add(idx, params);
1491                        // Already bound to the service. Just make
1492                        // sure we trigger off processing the first request.
1493                        if (idx == 0) {
1494                            mHandler.sendEmptyMessage(MCS_BOUND);
1495                        }
1496                    }
1497                    break;
1498                }
1499                case MCS_BOUND: {
1500                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1501                    if (msg.obj != null) {
1502                        mContainerService = (IMediaContainerService) msg.obj;
1503                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1504                                System.identityHashCode(mHandler));
1505                    }
1506                    if (mContainerService == null) {
1507                        if (!mBound) {
1508                            // Something seriously wrong since we are not bound and we are not
1509                            // waiting for connection. Bail out.
1510                            Slog.e(TAG, "Cannot bind to media container service");
1511                            for (HandlerParams params : mPendingInstalls) {
1512                                // Indicate service bind error
1513                                params.serviceError();
1514                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1515                                        System.identityHashCode(params));
1516                                if (params.traceMethod != null) {
1517                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1518                                            params.traceMethod, params.traceCookie);
1519                                }
1520                                return;
1521                            }
1522                            mPendingInstalls.clear();
1523                        } else {
1524                            Slog.w(TAG, "Waiting to connect to media container service");
1525                        }
1526                    } else if (mPendingInstalls.size() > 0) {
1527                        HandlerParams params = mPendingInstalls.get(0);
1528                        if (params != null) {
1529                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1530                                    System.identityHashCode(params));
1531                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1532                            if (params.startCopy()) {
1533                                // We are done...  look for more work or to
1534                                // go idle.
1535                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                        "Checking for more work or unbind...");
1537                                // Delete pending install
1538                                if (mPendingInstalls.size() > 0) {
1539                                    mPendingInstalls.remove(0);
1540                                }
1541                                if (mPendingInstalls.size() == 0) {
1542                                    if (mBound) {
1543                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                                "Posting delayed MCS_UNBIND");
1545                                        removeMessages(MCS_UNBIND);
1546                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1547                                        // Unbind after a little delay, to avoid
1548                                        // continual thrashing.
1549                                        sendMessageDelayed(ubmsg, 10000);
1550                                    }
1551                                } else {
1552                                    // There are more pending requests in queue.
1553                                    // Just post MCS_BOUND message to trigger processing
1554                                    // of next pending install.
1555                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1556                                            "Posting MCS_BOUND for next work");
1557                                    mHandler.sendEmptyMessage(MCS_BOUND);
1558                                }
1559                            }
1560                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1561                        }
1562                    } else {
1563                        // Should never happen ideally.
1564                        Slog.w(TAG, "Empty queue");
1565                    }
1566                    break;
1567                }
1568                case MCS_RECONNECT: {
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1570                    if (mPendingInstalls.size() > 0) {
1571                        if (mBound) {
1572                            disconnectService();
1573                        }
1574                        if (!connectToService()) {
1575                            Slog.e(TAG, "Failed to bind to media container service");
1576                            for (HandlerParams params : mPendingInstalls) {
1577                                // Indicate service bind error
1578                                params.serviceError();
1579                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                                        System.identityHashCode(params));
1581                            }
1582                            mPendingInstalls.clear();
1583                        }
1584                    }
1585                    break;
1586                }
1587                case MCS_UNBIND: {
1588                    // If there is no actual work left, then time to unbind.
1589                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1590
1591                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1592                        if (mBound) {
1593                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1594
1595                            disconnectService();
1596                        }
1597                    } else if (mPendingInstalls.size() > 0) {
1598                        // There are more pending requests in queue.
1599                        // Just post MCS_BOUND message to trigger processing
1600                        // of next pending install.
1601                        mHandler.sendEmptyMessage(MCS_BOUND);
1602                    }
1603
1604                    break;
1605                }
1606                case MCS_GIVE_UP: {
1607                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1608                    HandlerParams params = mPendingInstalls.remove(0);
1609                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1610                            System.identityHashCode(params));
1611                    break;
1612                }
1613                case SEND_PENDING_BROADCAST: {
1614                    String packages[];
1615                    ArrayList<String> components[];
1616                    int size = 0;
1617                    int uids[];
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1619                    synchronized (mPackages) {
1620                        if (mPendingBroadcasts == null) {
1621                            return;
1622                        }
1623                        size = mPendingBroadcasts.size();
1624                        if (size <= 0) {
1625                            // Nothing to be done. Just return
1626                            return;
1627                        }
1628                        packages = new String[size];
1629                        components = new ArrayList[size];
1630                        uids = new int[size];
1631                        int i = 0;  // filling out the above arrays
1632
1633                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1634                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1635                            Iterator<Map.Entry<String, ArrayList<String>>> it
1636                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1637                                            .entrySet().iterator();
1638                            while (it.hasNext() && i < size) {
1639                                Map.Entry<String, ArrayList<String>> ent = it.next();
1640                                packages[i] = ent.getKey();
1641                                components[i] = ent.getValue();
1642                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1643                                uids[i] = (ps != null)
1644                                        ? UserHandle.getUid(packageUserId, ps.appId)
1645                                        : -1;
1646                                i++;
1647                            }
1648                        }
1649                        size = i;
1650                        mPendingBroadcasts.clear();
1651                    }
1652                    // Send broadcasts
1653                    for (int i = 0; i < size; i++) {
1654                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1655                    }
1656                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1657                    break;
1658                }
1659                case START_CLEANING_PACKAGE: {
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1661                    final String packageName = (String)msg.obj;
1662                    final int userId = msg.arg1;
1663                    final boolean andCode = msg.arg2 != 0;
1664                    synchronized (mPackages) {
1665                        if (userId == UserHandle.USER_ALL) {
1666                            int[] users = sUserManager.getUserIds();
1667                            for (int user : users) {
1668                                mSettings.addPackageToCleanLPw(
1669                                        new PackageCleanItem(user, packageName, andCode));
1670                            }
1671                        } else {
1672                            mSettings.addPackageToCleanLPw(
1673                                    new PackageCleanItem(userId, packageName, andCode));
1674                        }
1675                    }
1676                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1677                    startCleaningPackages();
1678                } break;
1679                case POST_INSTALL: {
1680                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1681
1682                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1683                    final boolean didRestore = (msg.arg2 != 0);
1684                    mRunningInstalls.delete(msg.arg1);
1685
1686                    if (data != null) {
1687                        InstallArgs args = data.args;
1688                        PackageInstalledInfo parentRes = data.res;
1689
1690                        final boolean grantPermissions = (args.installFlags
1691                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1692                        final boolean killApp = (args.installFlags
1693                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1694                        final boolean virtualPreload = ((args.installFlags
1695                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1696                        final String[] grantedPermissions = args.installGrantPermissions;
1697
1698                        // Handle the parent package
1699                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1700                                virtualPreload, grantedPermissions, didRestore,
1701                                args.installerPackageName, args.observer);
1702
1703                        // Handle the child packages
1704                        final int childCount = (parentRes.addedChildPackages != null)
1705                                ? parentRes.addedChildPackages.size() : 0;
1706                        for (int i = 0; i < childCount; i++) {
1707                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1708                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1709                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1710                                    args.installerPackageName, args.observer);
1711                        }
1712
1713                        // Log tracing if needed
1714                        if (args.traceMethod != null) {
1715                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1716                                    args.traceCookie);
1717                        }
1718                    } else {
1719                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1720                    }
1721
1722                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1723                } break;
1724                case UPDATED_MEDIA_STATUS: {
1725                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1726                    boolean reportStatus = msg.arg1 == 1;
1727                    boolean doGc = msg.arg2 == 1;
1728                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1729                    if (doGc) {
1730                        // Force a gc to clear up stale containers.
1731                        Runtime.getRuntime().gc();
1732                    }
1733                    if (msg.obj != null) {
1734                        @SuppressWarnings("unchecked")
1735                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1736                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1737                        // Unload containers
1738                        unloadAllContainers(args);
1739                    }
1740                    if (reportStatus) {
1741                        try {
1742                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1743                                    "Invoking StorageManagerService call back");
1744                            PackageHelper.getStorageManager().finishMediaUpdate();
1745                        } catch (RemoteException e) {
1746                            Log.e(TAG, "StorageManagerService not running?");
1747                        }
1748                    }
1749                } break;
1750                case WRITE_SETTINGS: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_SETTINGS);
1754                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1755                        mSettings.writeLPr();
1756                        mDirtyUsers.clear();
1757                    }
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1759                } break;
1760                case WRITE_PACKAGE_RESTRICTIONS: {
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1762                    synchronized (mPackages) {
1763                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1764                        for (int userId : mDirtyUsers) {
1765                            mSettings.writePackageRestrictionsLPr(userId);
1766                        }
1767                        mDirtyUsers.clear();
1768                    }
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1770                } break;
1771                case WRITE_PACKAGE_LIST: {
1772                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1773                    synchronized (mPackages) {
1774                        removeMessages(WRITE_PACKAGE_LIST);
1775                        mSettings.writePackageListLPr(msg.arg1);
1776                    }
1777                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1778                } break;
1779                case CHECK_PENDING_VERIFICATION: {
1780                    final int verificationId = msg.arg1;
1781                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1782
1783                    if ((state != null) && !state.timeoutExtended()) {
1784                        final InstallArgs args = state.getInstallArgs();
1785                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1786
1787                        Slog.i(TAG, "Verification timed out for " + originUri);
1788                        mPendingVerification.remove(verificationId);
1789
1790                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1791
1792                        final UserHandle user = args.getUser();
1793                        if (getDefaultVerificationResponse(user)
1794                                == PackageManager.VERIFICATION_ALLOW) {
1795                            Slog.i(TAG, "Continuing with installation of " + originUri);
1796                            state.setVerifierResponse(Binder.getCallingUid(),
1797                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    PackageManager.VERIFICATION_ALLOW, user);
1800                            try {
1801                                ret = args.copyApk(mContainerService, true);
1802                            } catch (RemoteException e) {
1803                                Slog.e(TAG, "Could not contact the ContainerService");
1804                            }
1805                        } else {
1806                            broadcastPackageVerified(verificationId, originUri,
1807                                    PackageManager.VERIFICATION_REJECT, user);
1808                        }
1809
1810                        Trace.asyncTraceEnd(
1811                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1812
1813                        processPendingInstall(args, ret);
1814                        mHandler.sendEmptyMessage(MCS_UNBIND);
1815                    }
1816                    break;
1817                }
1818                case PACKAGE_VERIFIED: {
1819                    final int verificationId = msg.arg1;
1820
1821                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1822                    if (state == null) {
1823                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1824                        break;
1825                    }
1826
1827                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1828
1829                    state.setVerifierResponse(response.callerUid, response.code);
1830
1831                    if (state.isVerificationComplete()) {
1832                        mPendingVerification.remove(verificationId);
1833
1834                        final InstallArgs args = state.getInstallArgs();
1835                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1836
1837                        int ret;
1838                        if (state.isInstallAllowed()) {
1839                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1840                            broadcastPackageVerified(verificationId, originUri,
1841                                    response.code, state.getInstallArgs().getUser());
1842                            try {
1843                                ret = args.copyApk(mContainerService, true);
1844                            } catch (RemoteException e) {
1845                                Slog.e(TAG, "Could not contact the ContainerService");
1846                            }
1847                        } else {
1848                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1849                        }
1850
1851                        Trace.asyncTraceEnd(
1852                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1853
1854                        processPendingInstall(args, ret);
1855                        mHandler.sendEmptyMessage(MCS_UNBIND);
1856                    }
1857
1858                    break;
1859                }
1860                case START_INTENT_FILTER_VERIFICATIONS: {
1861                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1862                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1863                            params.replacing, params.pkg);
1864                    break;
1865                }
1866                case INTENT_FILTER_VERIFIED: {
1867                    final int verificationId = msg.arg1;
1868
1869                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1870                            verificationId);
1871                    if (state == null) {
1872                        Slog.w(TAG, "Invalid IntentFilter verification token "
1873                                + verificationId + " received");
1874                        break;
1875                    }
1876
1877                    final int userId = state.getUserId();
1878
1879                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                            "Processing IntentFilter verification with token:"
1881                            + verificationId + " and userId:" + userId);
1882
1883                    final IntentFilterVerificationResponse response =
1884                            (IntentFilterVerificationResponse) msg.obj;
1885
1886                    state.setVerifierResponse(response.callerUid, response.code);
1887
1888                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1889                            "IntentFilter verification with token:" + verificationId
1890                            + " and userId:" + userId
1891                            + " is settings verifier response with response code:"
1892                            + response.code);
1893
1894                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1895                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1896                                + response.getFailedDomainsString());
1897                    }
1898
1899                    if (state.isVerificationComplete()) {
1900                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1901                    } else {
1902                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1903                                "IntentFilter verification with token:" + verificationId
1904                                + " was not said to be complete");
1905                    }
1906
1907                    break;
1908                }
1909                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1910                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1911                            mInstantAppResolverConnection,
1912                            (InstantAppRequest) msg.obj,
1913                            mInstantAppInstallerActivity,
1914                            mHandler);
1915                }
1916            }
1917        }
1918    }
1919
1920    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1921        @Override
1922        public void onGidsChanged(int appId, int userId) {
1923            mHandler.post(new Runnable() {
1924                @Override
1925                public void run() {
1926                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1927                }
1928            });
1929        }
1930        @Override
1931        public void onPermissionGranted(int uid, int userId) {
1932            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1933
1934            // Not critical; if this is lost, the application has to request again.
1935            synchronized (mPackages) {
1936                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1937            }
1938        }
1939        @Override
1940        public void onInstallPermissionGranted() {
1941            synchronized (mPackages) {
1942                scheduleWriteSettingsLocked();
1943            }
1944        }
1945        @Override
1946        public void onPermissionRevoked(int uid, int userId) {
1947            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1948
1949            synchronized (mPackages) {
1950                // Critical; after this call the application should never have the permission
1951                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1952            }
1953
1954            final int appId = UserHandle.getAppId(uid);
1955            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1956        }
1957        @Override
1958        public void onInstallPermissionRevoked() {
1959            synchronized (mPackages) {
1960                scheduleWriteSettingsLocked();
1961            }
1962        }
1963        @Override
1964        public void onPermissionUpdated(int userId) {
1965            synchronized (mPackages) {
1966                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1967            }
1968        }
1969        @Override
1970        public void onInstallPermissionUpdated() {
1971            synchronized (mPackages) {
1972                scheduleWriteSettingsLocked();
1973            }
1974        }
1975        @Override
1976        public void onPermissionRemoved() {
1977            synchronized (mPackages) {
1978                mSettings.writeLPr();
1979            }
1980        }
1981    };
1982
1983    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1984            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1985            boolean launchedForRestore, String installerPackage,
1986            IPackageInstallObserver2 installObserver) {
1987        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1988            // Send the removed broadcasts
1989            if (res.removedInfo != null) {
1990                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1991            }
1992
1993            // Now that we successfully installed the package, grant runtime
1994            // permissions if requested before broadcasting the install. Also
1995            // for legacy apps in permission review mode we clear the permission
1996            // review flag which is used to emulate runtime permissions for
1997            // legacy apps.
1998            if (grantPermissions) {
1999                final int callingUid = Binder.getCallingUid();
2000                mPermissionManager.grantRequestedRuntimePermissions(
2001                        res.pkg, res.newUsers, grantedPermissions, callingUid,
2002                        mPermissionCallback);
2003            }
2004
2005            final boolean update = res.removedInfo != null
2006                    && res.removedInfo.removedPackage != null;
2007            final String installerPackageName =
2008                    res.installerPackageName != null
2009                            ? res.installerPackageName
2010                            : res.removedInfo != null
2011                                    ? res.removedInfo.installerPackageName
2012                                    : null;
2013
2014            // If this is the first time we have child packages for a disabled privileged
2015            // app that had no children, we grant requested runtime permissions to the new
2016            // children if the parent on the system image had them already granted.
2017            if (res.pkg.parentPackage != null) {
2018                final int callingUid = Binder.getCallingUid();
2019                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
2020                        res.pkg, callingUid, mPermissionCallback);
2021            }
2022
2023            synchronized (mPackages) {
2024                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
2025            }
2026
2027            final String packageName = res.pkg.applicationInfo.packageName;
2028
2029            // Determine the set of users who are adding this package for
2030            // the first time vs. those who are seeing an update.
2031            int[] firstUsers = EMPTY_INT_ARRAY;
2032            int[] updateUsers = EMPTY_INT_ARRAY;
2033            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2034            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2035            for (int newUser : res.newUsers) {
2036                if (ps.getInstantApp(newUser)) {
2037                    continue;
2038                }
2039                if (allNewUsers) {
2040                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2041                    continue;
2042                }
2043                boolean isNew = true;
2044                for (int origUser : res.origUsers) {
2045                    if (origUser == newUser) {
2046                        isNew = false;
2047                        break;
2048                    }
2049                }
2050                if (isNew) {
2051                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2052                } else {
2053                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2054                }
2055            }
2056
2057            // Send installed broadcasts if the package is not a static shared lib.
2058            if (res.pkg.staticSharedLibName == null) {
2059                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2060
2061                // Send added for users that see the package for the first time
2062                // sendPackageAddedForNewUsers also deals with system apps
2063                int appId = UserHandle.getAppId(res.uid);
2064                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2065                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2066                        virtualPreload /*startReceiver*/, appId, firstUsers);
2067
2068                // Send added for users that don't see the package for the first time
2069                Bundle extras = new Bundle(1);
2070                extras.putInt(Intent.EXTRA_UID, res.uid);
2071                if (update) {
2072                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2073                }
2074                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2075                        extras, 0 /*flags*/,
2076                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2077                if (installerPackageName != null) {
2078                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2079                            extras, 0 /*flags*/,
2080                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2081                }
2082
2083                // Send replaced for users that don't see the package for the first time
2084                if (update) {
2085                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2086                            packageName, extras, 0 /*flags*/,
2087                            null /*targetPackage*/, null /*finishedReceiver*/,
2088                            updateUsers);
2089                    if (installerPackageName != null) {
2090                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2091                                extras, 0 /*flags*/,
2092                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2093                    }
2094                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2095                            null /*package*/, null /*extras*/, 0 /*flags*/,
2096                            packageName /*targetPackage*/,
2097                            null /*finishedReceiver*/, updateUsers);
2098                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2099                    // First-install and we did a restore, so we're responsible for the
2100                    // first-launch broadcast.
2101                    if (DEBUG_BACKUP) {
2102                        Slog.i(TAG, "Post-restore of " + packageName
2103                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2104                    }
2105                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2106                }
2107
2108                // Send broadcast package appeared if forward locked/external for all users
2109                // treat asec-hosted packages like removable media on upgrade
2110                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2111                    if (DEBUG_INSTALL) {
2112                        Slog.i(TAG, "upgrading pkg " + res.pkg
2113                                + " is ASEC-hosted -> AVAILABLE");
2114                    }
2115                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2116                    ArrayList<String> pkgList = new ArrayList<>(1);
2117                    pkgList.add(packageName);
2118                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2119                }
2120            }
2121
2122            // Work that needs to happen on first install within each user
2123            if (firstUsers != null && firstUsers.length > 0) {
2124                synchronized (mPackages) {
2125                    for (int userId : firstUsers) {
2126                        // If this app is a browser and it's newly-installed for some
2127                        // users, clear any default-browser state in those users. The
2128                        // app's nature doesn't depend on the user, so we can just check
2129                        // its browser nature in any user and generalize.
2130                        if (packageIsBrowser(packageName, userId)) {
2131                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2132                        }
2133
2134                        // We may also need to apply pending (restored) runtime
2135                        // permission grants within these users.
2136                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2137                    }
2138                }
2139            }
2140
2141            // Log current value of "unknown sources" setting
2142            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2143                    getUnknownSourcesSettings());
2144
2145            // Remove the replaced package's older resources safely now
2146            // We delete after a gc for applications  on sdcard.
2147            if (res.removedInfo != null && res.removedInfo.args != null) {
2148                Runtime.getRuntime().gc();
2149                synchronized (mInstallLock) {
2150                    res.removedInfo.args.doPostDeleteLI(true);
2151                }
2152            } else {
2153                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2154                // and not block here.
2155                VMRuntime.getRuntime().requestConcurrentGC();
2156            }
2157
2158            // Notify DexManager that the package was installed for new users.
2159            // The updated users should already be indexed and the package code paths
2160            // should not change.
2161            // Don't notify the manager for ephemeral apps as they are not expected to
2162            // survive long enough to benefit of background optimizations.
2163            for (int userId : firstUsers) {
2164                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2165                // There's a race currently where some install events may interleave with an uninstall.
2166                // This can lead to package info being null (b/36642664).
2167                if (info != null) {
2168                    mDexManager.notifyPackageInstalled(info, userId);
2169                }
2170            }
2171        }
2172
2173        // If someone is watching installs - notify them
2174        if (installObserver != null) {
2175            try {
2176                Bundle extras = extrasForInstallResult(res);
2177                installObserver.onPackageInstalled(res.name, res.returnCode,
2178                        res.returnMsg, extras);
2179            } catch (RemoteException e) {
2180                Slog.i(TAG, "Observer no longer exists.");
2181            }
2182        }
2183    }
2184
2185    private StorageEventListener mStorageListener = new StorageEventListener() {
2186        @Override
2187        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2188            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2189                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2190                    final String volumeUuid = vol.getFsUuid();
2191
2192                    // Clean up any users or apps that were removed or recreated
2193                    // while this volume was missing
2194                    sUserManager.reconcileUsers(volumeUuid);
2195                    reconcileApps(volumeUuid);
2196
2197                    // Clean up any install sessions that expired or were
2198                    // cancelled while this volume was missing
2199                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2200
2201                    loadPrivatePackages(vol);
2202
2203                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2204                    unloadPrivatePackages(vol);
2205                }
2206            }
2207
2208            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2209                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2210                    updateExternalMediaStatus(true, false);
2211                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2212                    updateExternalMediaStatus(false, false);
2213                }
2214            }
2215        }
2216
2217        @Override
2218        public void onVolumeForgotten(String fsUuid) {
2219            if (TextUtils.isEmpty(fsUuid)) {
2220                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2221                return;
2222            }
2223
2224            // Remove any apps installed on the forgotten volume
2225            synchronized (mPackages) {
2226                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2227                for (PackageSetting ps : packages) {
2228                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2229                    deletePackageVersioned(new VersionedPackage(ps.name,
2230                            PackageManager.VERSION_CODE_HIGHEST),
2231                            new LegacyPackageDeleteObserver(null).getBinder(),
2232                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2233                    // Try very hard to release any references to this package
2234                    // so we don't risk the system server being killed due to
2235                    // open FDs
2236                    AttributeCache.instance().removePackage(ps.name);
2237                }
2238
2239                mSettings.onVolumeForgotten(fsUuid);
2240                mSettings.writeLPr();
2241            }
2242        }
2243    };
2244
2245    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2246        Bundle extras = null;
2247        switch (res.returnCode) {
2248            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2249                extras = new Bundle();
2250                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2251                        res.origPermission);
2252                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2253                        res.origPackage);
2254                break;
2255            }
2256            case PackageManager.INSTALL_SUCCEEDED: {
2257                extras = new Bundle();
2258                extras.putBoolean(Intent.EXTRA_REPLACING,
2259                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2260                break;
2261            }
2262        }
2263        return extras;
2264    }
2265
2266    void scheduleWriteSettingsLocked() {
2267        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2268            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2269        }
2270    }
2271
2272    void scheduleWritePackageListLocked(int userId) {
2273        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2274            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2275            msg.arg1 = userId;
2276            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2277        }
2278    }
2279
2280    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2281        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2282        scheduleWritePackageRestrictionsLocked(userId);
2283    }
2284
2285    void scheduleWritePackageRestrictionsLocked(int userId) {
2286        final int[] userIds = (userId == UserHandle.USER_ALL)
2287                ? sUserManager.getUserIds() : new int[]{userId};
2288        for (int nextUserId : userIds) {
2289            if (!sUserManager.exists(nextUserId)) return;
2290            mDirtyUsers.add(nextUserId);
2291            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2292                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2293            }
2294        }
2295    }
2296
2297    public static PackageManagerService main(Context context, Installer installer,
2298            boolean factoryTest, boolean onlyCore) {
2299        // Self-check for initial settings.
2300        PackageManagerServiceCompilerMapping.checkProperties();
2301
2302        PackageManagerService m = new PackageManagerService(context, installer,
2303                factoryTest, onlyCore);
2304        m.enableSystemUserPackages();
2305        ServiceManager.addService("package", m);
2306        final PackageManagerNative pmn = m.new PackageManagerNative();
2307        ServiceManager.addService("package_native", pmn);
2308        return m;
2309    }
2310
2311    private void enableSystemUserPackages() {
2312        if (!UserManager.isSplitSystemUser()) {
2313            return;
2314        }
2315        // For system user, enable apps based on the following conditions:
2316        // - app is whitelisted or belong to one of these groups:
2317        //   -- system app which has no launcher icons
2318        //   -- system app which has INTERACT_ACROSS_USERS permission
2319        //   -- system IME app
2320        // - app is not in the blacklist
2321        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2322        Set<String> enableApps = new ArraySet<>();
2323        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2324                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2325                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2326        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2327        enableApps.addAll(wlApps);
2328        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2329                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2330        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2331        enableApps.removeAll(blApps);
2332        Log.i(TAG, "Applications installed for system user: " + enableApps);
2333        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2334                UserHandle.SYSTEM);
2335        final int allAppsSize = allAps.size();
2336        synchronized (mPackages) {
2337            for (int i = 0; i < allAppsSize; i++) {
2338                String pName = allAps.get(i);
2339                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2340                // Should not happen, but we shouldn't be failing if it does
2341                if (pkgSetting == null) {
2342                    continue;
2343                }
2344                boolean install = enableApps.contains(pName);
2345                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2346                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2347                            + " for system user");
2348                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2349                }
2350            }
2351            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2352        }
2353    }
2354
2355    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2356        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2357                Context.DISPLAY_SERVICE);
2358        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2359    }
2360
2361    /**
2362     * Requests that files preopted on a secondary system partition be copied to the data partition
2363     * if possible.  Note that the actual copying of the files is accomplished by init for security
2364     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2365     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2366     */
2367    private static void requestCopyPreoptedFiles() {
2368        final int WAIT_TIME_MS = 100;
2369        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2370        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2371            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2372            // We will wait for up to 100 seconds.
2373            final long timeStart = SystemClock.uptimeMillis();
2374            final long timeEnd = timeStart + 100 * 1000;
2375            long timeNow = timeStart;
2376            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2377                try {
2378                    Thread.sleep(WAIT_TIME_MS);
2379                } catch (InterruptedException e) {
2380                    // Do nothing
2381                }
2382                timeNow = SystemClock.uptimeMillis();
2383                if (timeNow > timeEnd) {
2384                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2385                    Slog.wtf(TAG, "cppreopt did not finish!");
2386                    break;
2387                }
2388            }
2389
2390            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2391        }
2392    }
2393
2394    public PackageManagerService(Context context, Installer installer,
2395            boolean factoryTest, boolean onlyCore) {
2396        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2397        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2398        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2399                SystemClock.uptimeMillis());
2400
2401        if (mSdkVersion <= 0) {
2402            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2403        }
2404
2405        mContext = context;
2406
2407        mPermissionReviewRequired = context.getResources().getBoolean(
2408                R.bool.config_permissionReviewRequired);
2409
2410        mFactoryTest = factoryTest;
2411        mOnlyCore = onlyCore;
2412        mMetrics = new DisplayMetrics();
2413        mInstaller = installer;
2414
2415        // Create sub-components that provide services / data. Order here is important.
2416        synchronized (mInstallLock) {
2417        synchronized (mPackages) {
2418            // Expose private service for system components to use.
2419            LocalServices.addService(
2420                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2421            sUserManager = new UserManagerService(context, this,
2422                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2423            mPermissionManager = PermissionManagerService.create(context,
2424                    new DefaultPermissionGrantedCallback() {
2425                        @Override
2426                        public void onDefaultRuntimePermissionsGranted(int userId) {
2427                            synchronized(mPackages) {
2428                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2429                            }
2430                        }
2431                    }, mPackages /*externalLock*/);
2432            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2433            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2434        }
2435        }
2436        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2441                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2442        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2443                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2444        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2445                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2446        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2447                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2448
2449        String separateProcesses = SystemProperties.get("debug.separate_processes");
2450        if (separateProcesses != null && separateProcesses.length() > 0) {
2451            if ("*".equals(separateProcesses)) {
2452                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2453                mSeparateProcesses = null;
2454                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2455            } else {
2456                mDefParseFlags = 0;
2457                mSeparateProcesses = separateProcesses.split(",");
2458                Slog.w(TAG, "Running with debug.separate_processes: "
2459                        + separateProcesses);
2460            }
2461        } else {
2462            mDefParseFlags = 0;
2463            mSeparateProcesses = null;
2464        }
2465
2466        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2467                "*dexopt*");
2468        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2469        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2470
2471        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2472                FgThread.get().getLooper());
2473
2474        getDefaultDisplayMetrics(context, mMetrics);
2475
2476        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2477        SystemConfig systemConfig = SystemConfig.getInstance();
2478        mGlobalGids = systemConfig.getGlobalGids();
2479        mSystemPermissions = systemConfig.getSystemPermissions();
2480        mAvailableFeatures = systemConfig.getAvailableFeatures();
2481        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2482
2483        mProtectedPackages = new ProtectedPackages(mContext);
2484
2485        synchronized (mInstallLock) {
2486        // writer
2487        synchronized (mPackages) {
2488            mHandlerThread = new ServiceThread(TAG,
2489                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2490            mHandlerThread.start();
2491            mHandler = new PackageHandler(mHandlerThread.getLooper());
2492            mProcessLoggingHandler = new ProcessLoggingHandler();
2493            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2494            mInstantAppRegistry = new InstantAppRegistry(this);
2495
2496            File dataDir = Environment.getDataDirectory();
2497            mAppInstallDir = new File(dataDir, "app");
2498            mAppLib32InstallDir = new File(dataDir, "app-lib");
2499            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2500            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2501
2502            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2503            final int builtInLibCount = libConfig.size();
2504            for (int i = 0; i < builtInLibCount; i++) {
2505                String name = libConfig.keyAt(i);
2506                String path = libConfig.valueAt(i);
2507                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2508                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2509            }
2510
2511            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2512
2513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2514            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2516
2517            // Clean up orphaned packages for which the code path doesn't exist
2518            // and they are an update to a system app - caused by bug/32321269
2519            final int packageSettingCount = mSettings.mPackages.size();
2520            for (int i = packageSettingCount - 1; i >= 0; i--) {
2521                PackageSetting ps = mSettings.mPackages.valueAt(i);
2522                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2523                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2524                    mSettings.mPackages.removeAt(i);
2525                    mSettings.enableSystemPackageLPw(ps.name);
2526                }
2527            }
2528
2529            if (mFirstBoot) {
2530                requestCopyPreoptedFiles();
2531            }
2532
2533            String customResolverActivity = Resources.getSystem().getString(
2534                    R.string.config_customResolverActivity);
2535            if (TextUtils.isEmpty(customResolverActivity)) {
2536                customResolverActivity = null;
2537            } else {
2538                mCustomResolverComponentName = ComponentName.unflattenFromString(
2539                        customResolverActivity);
2540            }
2541
2542            long startTime = SystemClock.uptimeMillis();
2543
2544            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2545                    startTime);
2546
2547            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2548            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2549
2550            if (bootClassPath == null) {
2551                Slog.w(TAG, "No BOOTCLASSPATH found!");
2552            }
2553
2554            if (systemServerClassPath == null) {
2555                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2556            }
2557
2558            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2559
2560            final VersionInfo ver = mSettings.getInternalVersion();
2561            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2562            if (mIsUpgrade) {
2563                logCriticalInfo(Log.INFO,
2564                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2565            }
2566
2567            // when upgrading from pre-M, promote system app permissions from install to runtime
2568            mPromoteSystemApps =
2569                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2570
2571            // When upgrading from pre-N, we need to handle package extraction like first boot,
2572            // as there is no profiling data available.
2573            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2574
2575            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2576
2577            // save off the names of pre-existing system packages prior to scanning; we don't
2578            // want to automatically grant runtime permissions for new system apps
2579            if (mPromoteSystemApps) {
2580                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2581                while (pkgSettingIter.hasNext()) {
2582                    PackageSetting ps = pkgSettingIter.next();
2583                    if (isSystemApp(ps)) {
2584                        mExistingSystemPackages.add(ps.name);
2585                    }
2586                }
2587            }
2588
2589            mCacheDir = preparePackageParserCache(mIsUpgrade);
2590
2591            // Set flag to monitor and not change apk file paths when
2592            // scanning install directories.
2593            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2594
2595            if (mIsUpgrade || mFirstBoot) {
2596                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2597            }
2598
2599            // Collect vendor overlay packages. (Do this before scanning any apps.)
2600            // For security and version matching reason, only consider
2601            // overlay packages if they reside in the right directory.
2602            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2606
2607            mParallelPackageParserCallback.findStaticOverlayPackages();
2608
2609            // Find base frameworks (resource packages without code).
2610            scanDirTracedLI(frameworkDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR
2613                    | PackageParser.PARSE_IS_PRIVILEGED,
2614                    scanFlags | SCAN_NO_DEX, 0);
2615
2616            // Collected privileged system packages.
2617            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2618            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR
2621                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2622
2623            // Collect ordinary system packages.
2624            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2625            scanDirTracedLI(systemAppDir, mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2628
2629            // Collect all vendor packages.
2630            File vendorAppDir = new File("/vendor/app");
2631            try {
2632                vendorAppDir = vendorAppDir.getCanonicalFile();
2633            } catch (IOException e) {
2634                // failed to look up canonical path, continue with original one
2635            }
2636            scanDirTracedLI(vendorAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Collect all OEM packages.
2641            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2642            scanDirTracedLI(oemAppDir, mDefParseFlags
2643                    | PackageParser.PARSE_IS_SYSTEM
2644                    | PackageParser.PARSE_IS_SYSTEM_DIR
2645                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2646
2647            // Prune any system packages that no longer exist.
2648            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2649            // Stub packages must either be replaced with full versions in the /data
2650            // partition or be disabled.
2651            final List<String> stubSystemApps = new ArrayList<>();
2652            if (!mOnlyCore) {
2653                // do this first before mucking with mPackages for the "expecting better" case
2654                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2655                while (pkgIterator.hasNext()) {
2656                    final PackageParser.Package pkg = pkgIterator.next();
2657                    if (pkg.isStub) {
2658                        stubSystemApps.add(pkg.packageName);
2659                    }
2660                }
2661
2662                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2663                while (psit.hasNext()) {
2664                    PackageSetting ps = psit.next();
2665
2666                    /*
2667                     * If this is not a system app, it can't be a
2668                     * disable system app.
2669                     */
2670                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2671                        continue;
2672                    }
2673
2674                    /*
2675                     * If the package is scanned, it's not erased.
2676                     */
2677                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2678                    if (scannedPkg != null) {
2679                        /*
2680                         * If the system app is both scanned and in the
2681                         * disabled packages list, then it must have been
2682                         * added via OTA. Remove it from the currently
2683                         * scanned package so the previously user-installed
2684                         * application can be scanned.
2685                         */
2686                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2687                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2688                                    + ps.name + "; removing system app.  Last known codePath="
2689                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2690                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2691                                    + scannedPkg.mVersionCode);
2692                            removePackageLI(scannedPkg, true);
2693                            mExpectingBetter.put(ps.name, ps.codePath);
2694                        }
2695
2696                        continue;
2697                    }
2698
2699                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2700                        psit.remove();
2701                        logCriticalInfo(Log.WARN, "System package " + ps.name
2702                                + " no longer exists; it's data will be wiped");
2703                        // Actual deletion of code and data will be handled by later
2704                        // reconciliation step
2705                    } else {
2706                        // we still have a disabled system package, but, it still might have
2707                        // been removed. check the code path still exists and check there's
2708                        // still a package. the latter can happen if an OTA keeps the same
2709                        // code path, but, changes the package name.
2710                        final PackageSetting disabledPs =
2711                                mSettings.getDisabledSystemPkgLPr(ps.name);
2712                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2713                                || disabledPs.pkg == null) {
2714                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2715                        }
2716                    }
2717                }
2718            }
2719
2720            //look for any incomplete package installations
2721            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2722            for (int i = 0; i < deletePkgsList.size(); i++) {
2723                // Actual deletion of code and data will be handled by later
2724                // reconciliation step
2725                final String packageName = deletePkgsList.get(i).name;
2726                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2727                synchronized (mPackages) {
2728                    mSettings.removePackageLPw(packageName);
2729                }
2730            }
2731
2732            //delete tmp files
2733            deleteTempPackageFiles();
2734
2735            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2736
2737            // Remove any shared userIDs that have no associated packages
2738            mSettings.pruneSharedUsersLPw();
2739            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2740            final int systemPackagesCount = mPackages.size();
2741            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2742                    + " ms, packageCount: " + systemPackagesCount
2743                    + " , timePerPackage: "
2744                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2745                    + " , cached: " + cachedSystemApps);
2746            if (mIsUpgrade && systemPackagesCount > 0) {
2747                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2748                        ((int) systemScanTime) / systemPackagesCount);
2749            }
2750            if (!mOnlyCore) {
2751                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2752                        SystemClock.uptimeMillis());
2753                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2754
2755                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2756                        | PackageParser.PARSE_FORWARD_LOCK,
2757                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2758
2759                // Remove disable package settings for updated system apps that were
2760                // removed via an OTA. If the update is no longer present, remove the
2761                // app completely. Otherwise, revoke their system privileges.
2762                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2763                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2764                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2765
2766                    final String msg;
2767                    if (deletedPkg == null) {
2768                        // should have found an update, but, we didn't; remove everything
2769                        msg = "Updated system package " + deletedAppName
2770                                + " no longer exists; removing its data";
2771                        // Actual deletion of code and data will be handled by later
2772                        // reconciliation step
2773                    } else {
2774                        // found an update; revoke system privileges
2775                        msg = "Updated system package + " + deletedAppName
2776                                + " no longer exists; revoking system privileges";
2777
2778                        // Don't do anything if a stub is removed from the system image. If
2779                        // we were to remove the uncompressed version from the /data partition,
2780                        // this is where it'd be done.
2781
2782                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2783                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2784                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2785                    }
2786                    logCriticalInfo(Log.WARN, msg);
2787                }
2788
2789                /*
2790                 * Make sure all system apps that we expected to appear on
2791                 * the userdata partition actually showed up. If they never
2792                 * appeared, crawl back and revive the system version.
2793                 */
2794                for (int i = 0; i < mExpectingBetter.size(); i++) {
2795                    final String packageName = mExpectingBetter.keyAt(i);
2796                    if (!mPackages.containsKey(packageName)) {
2797                        final File scanFile = mExpectingBetter.valueAt(i);
2798
2799                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2800                                + " but never showed up; reverting to system");
2801
2802                        int reparseFlags = mDefParseFlags;
2803                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2806                                    | PackageParser.PARSE_IS_PRIVILEGED;
2807                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2808                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2809                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2810                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2811                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2812                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2813                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2814                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2815                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2816                                    | PackageParser.PARSE_IS_OEM;
2817                        } else {
2818                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2819                            continue;
2820                        }
2821
2822                        mSettings.enableSystemPackageLPw(packageName);
2823
2824                        try {
2825                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2826                        } catch (PackageManagerException e) {
2827                            Slog.e(TAG, "Failed to parse original system package: "
2828                                    + e.getMessage());
2829                        }
2830                    }
2831                }
2832
2833                // Uncompress and install any stubbed system applications.
2834                // This must be done last to ensure all stubs are replaced or disabled.
2835                decompressSystemApplications(stubSystemApps, scanFlags);
2836
2837                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2838                                - cachedSystemApps;
2839
2840                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2841                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2842                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2843                        + " ms, packageCount: " + dataPackagesCount
2844                        + " , timePerPackage: "
2845                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2846                        + " , cached: " + cachedNonSystemApps);
2847                if (mIsUpgrade && dataPackagesCount > 0) {
2848                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2849                            ((int) dataScanTime) / dataPackagesCount);
2850                }
2851            }
2852            mExpectingBetter.clear();
2853
2854            // Resolve the storage manager.
2855            mStorageManagerPackage = getStorageManagerPackageName();
2856
2857            // Resolve protected action filters. Only the setup wizard is allowed to
2858            // have a high priority filter for these actions.
2859            mSetupWizardPackage = getSetupWizardPackageName();
2860            if (mProtectedFilters.size() > 0) {
2861                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2862                    Slog.i(TAG, "No setup wizard;"
2863                        + " All protected intents capped to priority 0");
2864                }
2865                for (ActivityIntentInfo filter : mProtectedFilters) {
2866                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2867                        if (DEBUG_FILTERS) {
2868                            Slog.i(TAG, "Found setup wizard;"
2869                                + " allow priority " + filter.getPriority() + ";"
2870                                + " package: " + filter.activity.info.packageName
2871                                + " activity: " + filter.activity.className
2872                                + " priority: " + filter.getPriority());
2873                        }
2874                        // skip setup wizard; allow it to keep the high priority filter
2875                        continue;
2876                    }
2877                    if (DEBUG_FILTERS) {
2878                        Slog.i(TAG, "Protected action; cap priority to 0;"
2879                                + " package: " + filter.activity.info.packageName
2880                                + " activity: " + filter.activity.className
2881                                + " origPrio: " + filter.getPriority());
2882                    }
2883                    filter.setPriority(0);
2884                }
2885            }
2886            mDeferProtectedFilters = false;
2887            mProtectedFilters.clear();
2888
2889            // Now that we know all of the shared libraries, update all clients to have
2890            // the correct library paths.
2891            updateAllSharedLibrariesLPw(null);
2892
2893            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2894                // NOTE: We ignore potential failures here during a system scan (like
2895                // the rest of the commands above) because there's precious little we
2896                // can do about it. A settings error is reported, though.
2897                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2898            }
2899
2900            // Now that we know all the packages we are keeping,
2901            // read and update their last usage times.
2902            mPackageUsage.read(mPackages);
2903            mCompilerStats.read();
2904
2905            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2906                    SystemClock.uptimeMillis());
2907            Slog.i(TAG, "Time to scan packages: "
2908                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2909                    + " seconds");
2910
2911            // If the platform SDK has changed since the last time we booted,
2912            // we need to re-grant app permission to catch any new ones that
2913            // appear.  This is really a hack, and means that apps can in some
2914            // cases get permissions that the user didn't initially explicitly
2915            // allow...  it would be nice to have some better way to handle
2916            // this situation.
2917            int updateFlags = UPDATE_PERMISSIONS_ALL;
2918            if (ver.sdkVersion != mSdkVersion) {
2919                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2920                        + mSdkVersion + "; regranting permissions for internal storage");
2921                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2922            }
2923            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2924            ver.sdkVersion = mSdkVersion;
2925
2926            // If this is the first boot or an update from pre-M, and it is a normal
2927            // boot, then we need to initialize the default preferred apps across
2928            // all defined users.
2929            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2930                for (UserInfo user : sUserManager.getUsers(true)) {
2931                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2932                    applyFactoryDefaultBrowserLPw(user.id);
2933                    primeDomainVerificationsLPw(user.id);
2934                }
2935            }
2936
2937            // Prepare storage for system user really early during boot,
2938            // since core system apps like SettingsProvider and SystemUI
2939            // can't wait for user to start
2940            final int storageFlags;
2941            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2942                storageFlags = StorageManager.FLAG_STORAGE_DE;
2943            } else {
2944                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2945            }
2946            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2947                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2948                    true /* onlyCoreApps */);
2949            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2950                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2951                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2952                traceLog.traceBegin("AppDataFixup");
2953                try {
2954                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2955                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2956                } catch (InstallerException e) {
2957                    Slog.w(TAG, "Trouble fixing GIDs", e);
2958                }
2959                traceLog.traceEnd();
2960
2961                traceLog.traceBegin("AppDataPrepare");
2962                if (deferPackages == null || deferPackages.isEmpty()) {
2963                    return;
2964                }
2965                int count = 0;
2966                for (String pkgName : deferPackages) {
2967                    PackageParser.Package pkg = null;
2968                    synchronized (mPackages) {
2969                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2970                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2971                            pkg = ps.pkg;
2972                        }
2973                    }
2974                    if (pkg != null) {
2975                        synchronized (mInstallLock) {
2976                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2977                                    true /* maybeMigrateAppData */);
2978                        }
2979                        count++;
2980                    }
2981                }
2982                traceLog.traceEnd();
2983                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2984            }, "prepareAppData");
2985
2986            // If this is first boot after an OTA, and a normal boot, then
2987            // we need to clear code cache directories.
2988            // Note that we do *not* clear the application profiles. These remain valid
2989            // across OTAs and are used to drive profile verification (post OTA) and
2990            // profile compilation (without waiting to collect a fresh set of profiles).
2991            if (mIsUpgrade && !onlyCore) {
2992                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2993                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2994                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2995                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2996                        // No apps are running this early, so no need to freeze
2997                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2998                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2999                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3000                    }
3001                }
3002                ver.fingerprint = Build.FINGERPRINT;
3003            }
3004
3005            checkDefaultBrowser();
3006
3007            // clear only after permissions and other defaults have been updated
3008            mExistingSystemPackages.clear();
3009            mPromoteSystemApps = false;
3010
3011            // All the changes are done during package scanning.
3012            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3013
3014            // can downgrade to reader
3015            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3016            mSettings.writeLPr();
3017            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3018            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3019                    SystemClock.uptimeMillis());
3020
3021            if (!mOnlyCore) {
3022                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3023                mRequiredInstallerPackage = getRequiredInstallerLPr();
3024                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3025                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3026                if (mIntentFilterVerifierComponent != null) {
3027                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3028                            mIntentFilterVerifierComponent);
3029                } else {
3030                    mIntentFilterVerifier = null;
3031                }
3032                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3033                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3034                        SharedLibraryInfo.VERSION_UNDEFINED);
3035                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3036                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3037                        SharedLibraryInfo.VERSION_UNDEFINED);
3038            } else {
3039                mRequiredVerifierPackage = null;
3040                mRequiredInstallerPackage = null;
3041                mRequiredUninstallerPackage = null;
3042                mIntentFilterVerifierComponent = null;
3043                mIntentFilterVerifier = null;
3044                mServicesSystemSharedLibraryPackageName = null;
3045                mSharedSystemSharedLibraryPackageName = null;
3046            }
3047
3048            mInstallerService = new PackageInstallerService(context, this);
3049            final Pair<ComponentName, String> instantAppResolverComponent =
3050                    getInstantAppResolverLPr();
3051            if (instantAppResolverComponent != null) {
3052                if (DEBUG_EPHEMERAL) {
3053                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3054                }
3055                mInstantAppResolverConnection = new EphemeralResolverConnection(
3056                        mContext, instantAppResolverComponent.first,
3057                        instantAppResolverComponent.second);
3058                mInstantAppResolverSettingsComponent =
3059                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3060            } else {
3061                mInstantAppResolverConnection = null;
3062                mInstantAppResolverSettingsComponent = null;
3063            }
3064            updateInstantAppInstallerLocked(null);
3065
3066            // Read and update the usage of dex files.
3067            // Do this at the end of PM init so that all the packages have their
3068            // data directory reconciled.
3069            // At this point we know the code paths of the packages, so we can validate
3070            // the disk file and build the internal cache.
3071            // The usage file is expected to be small so loading and verifying it
3072            // should take a fairly small time compare to the other activities (e.g. package
3073            // scanning).
3074            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3075            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3076            for (int userId : currentUserIds) {
3077                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3078            }
3079            mDexManager.load(userPackages);
3080            if (mIsUpgrade) {
3081                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3082                        (int) (SystemClock.uptimeMillis() - startTime));
3083            }
3084        } // synchronized (mPackages)
3085        } // synchronized (mInstallLock)
3086
3087        // Now after opening every single application zip, make sure they
3088        // are all flushed.  Not really needed, but keeps things nice and
3089        // tidy.
3090        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3091        Runtime.getRuntime().gc();
3092        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3093
3094        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3095        FallbackCategoryProvider.loadFallbacks();
3096        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3097
3098        // The initial scanning above does many calls into installd while
3099        // holding the mPackages lock, but we're mostly interested in yelling
3100        // once we have a booted system.
3101        mInstaller.setWarnIfHeld(mPackages);
3102
3103        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3104    }
3105
3106    /**
3107     * Uncompress and install stub applications.
3108     * <p>In order to save space on the system partition, some applications are shipped in a
3109     * compressed form. In addition the compressed bits for the full application, the
3110     * system image contains a tiny stub comprised of only the Android manifest.
3111     * <p>During the first boot, attempt to uncompress and install the full application. If
3112     * the application can't be installed for any reason, disable the stub and prevent
3113     * uncompressing the full application during future boots.
3114     * <p>In order to forcefully attempt an installation of a full application, go to app
3115     * settings and enable the application.
3116     */
3117    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3118        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3119            final String pkgName = stubSystemApps.get(i);
3120            // skip if the system package is already disabled
3121            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3122                stubSystemApps.remove(i);
3123                continue;
3124            }
3125            // skip if the package isn't installed (?!); this should never happen
3126            final PackageParser.Package pkg = mPackages.get(pkgName);
3127            if (pkg == null) {
3128                stubSystemApps.remove(i);
3129                continue;
3130            }
3131            // skip if the package has been disabled by the user
3132            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3133            if (ps != null) {
3134                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3135                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3136                    stubSystemApps.remove(i);
3137                    continue;
3138                }
3139            }
3140
3141            if (DEBUG_COMPRESSION) {
3142                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3143            }
3144
3145            // uncompress the binary to its eventual destination on /data
3146            final File scanFile = decompressPackage(pkg);
3147            if (scanFile == null) {
3148                continue;
3149            }
3150
3151            // install the package to replace the stub on /system
3152            try {
3153                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3154                removePackageLI(pkg, true /*chatty*/);
3155                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3156                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3157                        UserHandle.USER_SYSTEM, "android");
3158                stubSystemApps.remove(i);
3159                continue;
3160            } catch (PackageManagerException e) {
3161                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3162            }
3163
3164            // any failed attempt to install the package will be cleaned up later
3165        }
3166
3167        // disable any stub still left; these failed to install the full application
3168        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3169            final String pkgName = stubSystemApps.get(i);
3170            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3171            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3172                    UserHandle.USER_SYSTEM, "android");
3173            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3174        }
3175    }
3176
3177    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3178        if (DEBUG_COMPRESSION) {
3179            Slog.i(TAG, "Decompress file"
3180                    + "; src: " + srcFile.getAbsolutePath()
3181                    + ", dst: " + dstFile.getAbsolutePath());
3182        }
3183        try (
3184                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3185                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3186        ) {
3187            Streams.copy(fileIn, fileOut);
3188            Os.chmod(dstFile.getAbsolutePath(), 0644);
3189            return PackageManager.INSTALL_SUCCEEDED;
3190        } catch (IOException e) {
3191            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3192                    + "; src: " + srcFile.getAbsolutePath()
3193                    + ", dst: " + dstFile.getAbsolutePath());
3194        }
3195        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3196    }
3197
3198    private File[] getCompressedFiles(String codePath) {
3199        final File stubCodePath = new File(codePath);
3200        final String stubName = stubCodePath.getName();
3201
3202        // The layout of a compressed package on a given partition is as follows :
3203        //
3204        // Compressed artifacts:
3205        //
3206        // /partition/ModuleName/foo.gz
3207        // /partation/ModuleName/bar.gz
3208        //
3209        // Stub artifact:
3210        //
3211        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3212        //
3213        // In other words, stub is on the same partition as the compressed artifacts
3214        // and in a directory that's suffixed with "-Stub".
3215        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3216        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3217            return null;
3218        }
3219
3220        final File stubParentDir = stubCodePath.getParentFile();
3221        if (stubParentDir == null) {
3222            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3223            return null;
3224        }
3225
3226        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3227        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3228            @Override
3229            public boolean accept(File dir, String name) {
3230                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3231            }
3232        });
3233
3234        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3235            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3236        }
3237
3238        return files;
3239    }
3240
3241    private boolean compressedFileExists(String codePath) {
3242        final File[] compressedFiles = getCompressedFiles(codePath);
3243        return compressedFiles != null && compressedFiles.length > 0;
3244    }
3245
3246    /**
3247     * Decompresses the given package on the system image onto
3248     * the /data partition.
3249     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3250     */
3251    private File decompressPackage(PackageParser.Package pkg) {
3252        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3253        if (compressedFiles == null || compressedFiles.length == 0) {
3254            if (DEBUG_COMPRESSION) {
3255                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3256            }
3257            return null;
3258        }
3259        final File dstCodePath =
3260                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3261        int ret = PackageManager.INSTALL_SUCCEEDED;
3262        try {
3263            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3264            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3265            for (File srcFile : compressedFiles) {
3266                final String srcFileName = srcFile.getName();
3267                final String dstFileName = srcFileName.substring(
3268                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3269                final File dstFile = new File(dstCodePath, dstFileName);
3270                ret = decompressFile(srcFile, dstFile);
3271                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3272                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3273                            + "; pkg: " + pkg.packageName
3274                            + ", file: " + dstFileName);
3275                    break;
3276                }
3277            }
3278        } catch (ErrnoException e) {
3279            logCriticalInfo(Log.ERROR, "Failed to decompress"
3280                    + "; pkg: " + pkg.packageName
3281                    + ", err: " + e.errno);
3282        }
3283        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3284            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3285            NativeLibraryHelper.Handle handle = null;
3286            try {
3287                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3288                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3289                        null /*abiOverride*/);
3290            } catch (IOException e) {
3291                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3292                        + "; pkg: " + pkg.packageName);
3293                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3294            } finally {
3295                IoUtils.closeQuietly(handle);
3296            }
3297        }
3298        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3299            if (dstCodePath == null || !dstCodePath.exists()) {
3300                return null;
3301            }
3302            removeCodePathLI(dstCodePath);
3303            return null;
3304        }
3305        return dstCodePath;
3306    }
3307
3308    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3309        // we're only interested in updating the installer appliction when 1) it's not
3310        // already set or 2) the modified package is the installer
3311        if (mInstantAppInstallerActivity != null
3312                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3313                        .equals(modifiedPackage)) {
3314            return;
3315        }
3316        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3317    }
3318
3319    private static File preparePackageParserCache(boolean isUpgrade) {
3320        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3321            return null;
3322        }
3323
3324        // Disable package parsing on eng builds to allow for faster incremental development.
3325        if (Build.IS_ENG) {
3326            return null;
3327        }
3328
3329        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3330            Slog.i(TAG, "Disabling package parser cache due to system property.");
3331            return null;
3332        }
3333
3334        // The base directory for the package parser cache lives under /data/system/.
3335        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3336                "package_cache");
3337        if (cacheBaseDir == null) {
3338            return null;
3339        }
3340
3341        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3342        // This also serves to "GC" unused entries when the package cache version changes (which
3343        // can only happen during upgrades).
3344        if (isUpgrade) {
3345            FileUtils.deleteContents(cacheBaseDir);
3346        }
3347
3348
3349        // Return the versioned package cache directory. This is something like
3350        // "/data/system/package_cache/1"
3351        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3352
3353        // The following is a workaround to aid development on non-numbered userdebug
3354        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3355        // the system partition is newer.
3356        //
3357        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3358        // that starts with "eng." to signify that this is an engineering build and not
3359        // destined for release.
3360        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3361            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3362
3363            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3364            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3365            // in general and should not be used for production changes. In this specific case,
3366            // we know that they will work.
3367            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3368            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3369                FileUtils.deleteContents(cacheBaseDir);
3370                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3371            }
3372        }
3373
3374        return cacheDir;
3375    }
3376
3377    @Override
3378    public boolean isFirstBoot() {
3379        // allow instant applications
3380        return mFirstBoot;
3381    }
3382
3383    @Override
3384    public boolean isOnlyCoreApps() {
3385        // allow instant applications
3386        return mOnlyCore;
3387    }
3388
3389    @Override
3390    public boolean isUpgrade() {
3391        // allow instant applications
3392        return mIsUpgrade;
3393    }
3394
3395    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3396        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3397
3398        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3399                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3400                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3401        if (matches.size() == 1) {
3402            return matches.get(0).getComponentInfo().packageName;
3403        } else if (matches.size() == 0) {
3404            Log.e(TAG, "There should probably be a verifier, but, none were found");
3405            return null;
3406        }
3407        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3408    }
3409
3410    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3411        synchronized (mPackages) {
3412            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3413            if (libraryEntry == null) {
3414                throw new IllegalStateException("Missing required shared library:" + name);
3415            }
3416            return libraryEntry.apk;
3417        }
3418    }
3419
3420    private @NonNull String getRequiredInstallerLPr() {
3421        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3422        intent.addCategory(Intent.CATEGORY_DEFAULT);
3423        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3424
3425        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3426                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3427                UserHandle.USER_SYSTEM);
3428        if (matches.size() == 1) {
3429            ResolveInfo resolveInfo = matches.get(0);
3430            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3431                throw new RuntimeException("The installer must be a privileged app");
3432            }
3433            return matches.get(0).getComponentInfo().packageName;
3434        } else {
3435            throw new RuntimeException("There must be exactly one installer; found " + matches);
3436        }
3437    }
3438
3439    private @NonNull String getRequiredUninstallerLPr() {
3440        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3441        intent.addCategory(Intent.CATEGORY_DEFAULT);
3442        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3443
3444        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3445                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3446                UserHandle.USER_SYSTEM);
3447        if (resolveInfo == null ||
3448                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3449            throw new RuntimeException("There must be exactly one uninstaller; found "
3450                    + resolveInfo);
3451        }
3452        return resolveInfo.getComponentInfo().packageName;
3453    }
3454
3455    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3456        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3457
3458        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3459                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3460                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3461        ResolveInfo best = null;
3462        final int N = matches.size();
3463        for (int i = 0; i < N; i++) {
3464            final ResolveInfo cur = matches.get(i);
3465            final String packageName = cur.getComponentInfo().packageName;
3466            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3467                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3468                continue;
3469            }
3470
3471            if (best == null || cur.priority > best.priority) {
3472                best = cur;
3473            }
3474        }
3475
3476        if (best != null) {
3477            return best.getComponentInfo().getComponentName();
3478        }
3479        Slog.w(TAG, "Intent filter verifier not found");
3480        return null;
3481    }
3482
3483    @Override
3484    public @Nullable ComponentName getInstantAppResolverComponent() {
3485        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3486            return null;
3487        }
3488        synchronized (mPackages) {
3489            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3490            if (instantAppResolver == null) {
3491                return null;
3492            }
3493            return instantAppResolver.first;
3494        }
3495    }
3496
3497    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3498        final String[] packageArray =
3499                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3500        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3501            if (DEBUG_EPHEMERAL) {
3502                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3503            }
3504            return null;
3505        }
3506
3507        final int callingUid = Binder.getCallingUid();
3508        final int resolveFlags =
3509                MATCH_DIRECT_BOOT_AWARE
3510                | MATCH_DIRECT_BOOT_UNAWARE
3511                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3512        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3513        final Intent resolverIntent = new Intent(actionName);
3514        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3515                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3516        // temporarily look for the old action
3517        if (resolvers.size() == 0) {
3518            if (DEBUG_EPHEMERAL) {
3519                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3520            }
3521            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3522            resolverIntent.setAction(actionName);
3523            resolvers = queryIntentServicesInternal(resolverIntent, null,
3524                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3525        }
3526        final int N = resolvers.size();
3527        if (N == 0) {
3528            if (DEBUG_EPHEMERAL) {
3529                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3530            }
3531            return null;
3532        }
3533
3534        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3535        for (int i = 0; i < N; i++) {
3536            final ResolveInfo info = resolvers.get(i);
3537
3538            if (info.serviceInfo == null) {
3539                continue;
3540            }
3541
3542            final String packageName = info.serviceInfo.packageName;
3543            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3544                if (DEBUG_EPHEMERAL) {
3545                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3546                            + " pkg: " + packageName + ", info:" + info);
3547                }
3548                continue;
3549            }
3550
3551            if (DEBUG_EPHEMERAL) {
3552                Slog.v(TAG, "Ephemeral resolver found;"
3553                        + " pkg: " + packageName + ", info:" + info);
3554            }
3555            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3556        }
3557        if (DEBUG_EPHEMERAL) {
3558            Slog.v(TAG, "Ephemeral resolver NOT found");
3559        }
3560        return null;
3561    }
3562
3563    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3564        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3565        intent.addCategory(Intent.CATEGORY_DEFAULT);
3566        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3567
3568        final int resolveFlags =
3569                MATCH_DIRECT_BOOT_AWARE
3570                | MATCH_DIRECT_BOOT_UNAWARE
3571                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3572        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3573                resolveFlags, UserHandle.USER_SYSTEM);
3574        // temporarily look for the old action
3575        if (matches.isEmpty()) {
3576            if (DEBUG_EPHEMERAL) {
3577                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3578            }
3579            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3580            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3581                    resolveFlags, UserHandle.USER_SYSTEM);
3582        }
3583        Iterator<ResolveInfo> iter = matches.iterator();
3584        while (iter.hasNext()) {
3585            final ResolveInfo rInfo = iter.next();
3586            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3587            if (ps != null) {
3588                final PermissionsState permissionsState = ps.getPermissionsState();
3589                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3590                    continue;
3591                }
3592            }
3593            iter.remove();
3594        }
3595        if (matches.size() == 0) {
3596            return null;
3597        } else if (matches.size() == 1) {
3598            return (ActivityInfo) matches.get(0).getComponentInfo();
3599        } else {
3600            throw new RuntimeException(
3601                    "There must be at most one ephemeral installer; found " + matches);
3602        }
3603    }
3604
3605    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3606            @NonNull ComponentName resolver) {
3607        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3608                .addCategory(Intent.CATEGORY_DEFAULT)
3609                .setPackage(resolver.getPackageName());
3610        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3611        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3612                UserHandle.USER_SYSTEM);
3613        // temporarily look for the old action
3614        if (matches.isEmpty()) {
3615            if (DEBUG_EPHEMERAL) {
3616                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3617            }
3618            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3619            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3620                    UserHandle.USER_SYSTEM);
3621        }
3622        if (matches.isEmpty()) {
3623            return null;
3624        }
3625        return matches.get(0).getComponentInfo().getComponentName();
3626    }
3627
3628    private void primeDomainVerificationsLPw(int userId) {
3629        if (DEBUG_DOMAIN_VERIFICATION) {
3630            Slog.d(TAG, "Priming domain verifications in user " + userId);
3631        }
3632
3633        SystemConfig systemConfig = SystemConfig.getInstance();
3634        ArraySet<String> packages = systemConfig.getLinkedApps();
3635
3636        for (String packageName : packages) {
3637            PackageParser.Package pkg = mPackages.get(packageName);
3638            if (pkg != null) {
3639                if (!pkg.isSystemApp()) {
3640                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3641                    continue;
3642                }
3643
3644                ArraySet<String> domains = null;
3645                for (PackageParser.Activity a : pkg.activities) {
3646                    for (ActivityIntentInfo filter : a.intents) {
3647                        if (hasValidDomains(filter)) {
3648                            if (domains == null) {
3649                                domains = new ArraySet<String>();
3650                            }
3651                            domains.addAll(filter.getHostsList());
3652                        }
3653                    }
3654                }
3655
3656                if (domains != null && domains.size() > 0) {
3657                    if (DEBUG_DOMAIN_VERIFICATION) {
3658                        Slog.v(TAG, "      + " + packageName);
3659                    }
3660                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3661                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3662                    // and then 'always' in the per-user state actually used for intent resolution.
3663                    final IntentFilterVerificationInfo ivi;
3664                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3665                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3666                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3667                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3668                } else {
3669                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3670                            + "' does not handle web links");
3671                }
3672            } else {
3673                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3674            }
3675        }
3676
3677        scheduleWritePackageRestrictionsLocked(userId);
3678        scheduleWriteSettingsLocked();
3679    }
3680
3681    private void applyFactoryDefaultBrowserLPw(int userId) {
3682        // The default browser app's package name is stored in a string resource,
3683        // with a product-specific overlay used for vendor customization.
3684        String browserPkg = mContext.getResources().getString(
3685                com.android.internal.R.string.default_browser);
3686        if (!TextUtils.isEmpty(browserPkg)) {
3687            // non-empty string => required to be a known package
3688            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3689            if (ps == null) {
3690                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3691                browserPkg = null;
3692            } else {
3693                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3694            }
3695        }
3696
3697        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3698        // default.  If there's more than one, just leave everything alone.
3699        if (browserPkg == null) {
3700            calculateDefaultBrowserLPw(userId);
3701        }
3702    }
3703
3704    private void calculateDefaultBrowserLPw(int userId) {
3705        List<String> allBrowsers = resolveAllBrowserApps(userId);
3706        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3707        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3708    }
3709
3710    private List<String> resolveAllBrowserApps(int userId) {
3711        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3712        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3713                PackageManager.MATCH_ALL, userId);
3714
3715        final int count = list.size();
3716        List<String> result = new ArrayList<String>(count);
3717        for (int i=0; i<count; i++) {
3718            ResolveInfo info = list.get(i);
3719            if (info.activityInfo == null
3720                    || !info.handleAllWebDataURI
3721                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3722                    || result.contains(info.activityInfo.packageName)) {
3723                continue;
3724            }
3725            result.add(info.activityInfo.packageName);
3726        }
3727
3728        return result;
3729    }
3730
3731    private boolean packageIsBrowser(String packageName, int userId) {
3732        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3733                PackageManager.MATCH_ALL, userId);
3734        final int N = list.size();
3735        for (int i = 0; i < N; i++) {
3736            ResolveInfo info = list.get(i);
3737            if (packageName.equals(info.activityInfo.packageName)) {
3738                return true;
3739            }
3740        }
3741        return false;
3742    }
3743
3744    private void checkDefaultBrowser() {
3745        final int myUserId = UserHandle.myUserId();
3746        final String packageName = getDefaultBrowserPackageName(myUserId);
3747        if (packageName != null) {
3748            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3749            if (info == null) {
3750                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3751                synchronized (mPackages) {
3752                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3753                }
3754            }
3755        }
3756    }
3757
3758    @Override
3759    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3760            throws RemoteException {
3761        try {
3762            return super.onTransact(code, data, reply, flags);
3763        } catch (RuntimeException e) {
3764            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3765                Slog.wtf(TAG, "Package Manager Crash", e);
3766            }
3767            throw e;
3768        }
3769    }
3770
3771    static int[] appendInts(int[] cur, int[] add) {
3772        if (add == null) return cur;
3773        if (cur == null) return add;
3774        final int N = add.length;
3775        for (int i=0; i<N; i++) {
3776            cur = appendInt(cur, add[i]);
3777        }
3778        return cur;
3779    }
3780
3781    /**
3782     * Returns whether or not a full application can see an instant application.
3783     * <p>
3784     * Currently, there are three cases in which this can occur:
3785     * <ol>
3786     * <li>The calling application is a "special" process. The special
3787     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3788     *     and {@code 0}</li>
3789     * <li>The calling application has the permission
3790     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3791     * <li>The calling application is the default launcher on the
3792     *     system partition.</li>
3793     * </ol>
3794     */
3795    private boolean canViewInstantApps(int callingUid, int userId) {
3796        if (callingUid == Process.SYSTEM_UID
3797                || callingUid == Process.SHELL_UID
3798                || callingUid == Process.ROOT_UID) {
3799            return true;
3800        }
3801        if (mContext.checkCallingOrSelfPermission(
3802                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3803            return true;
3804        }
3805        if (mContext.checkCallingOrSelfPermission(
3806                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3807            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3808            if (homeComponent != null
3809                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3810                return true;
3811            }
3812        }
3813        return false;
3814    }
3815
3816    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3817        if (!sUserManager.exists(userId)) return null;
3818        if (ps == null) {
3819            return null;
3820        }
3821        PackageParser.Package p = ps.pkg;
3822        if (p == null) {
3823            return null;
3824        }
3825        final int callingUid = Binder.getCallingUid();
3826        // Filter out ephemeral app metadata:
3827        //   * The system/shell/root can see metadata for any app
3828        //   * An installed app can see metadata for 1) other installed apps
3829        //     and 2) ephemeral apps that have explicitly interacted with it
3830        //   * Ephemeral apps can only see their own data and exposed installed apps
3831        //   * Holding a signature permission allows seeing instant apps
3832        if (filterAppAccessLPr(ps, callingUid, userId)) {
3833            return null;
3834        }
3835
3836        final PermissionsState permissionsState = ps.getPermissionsState();
3837
3838        // Compute GIDs only if requested
3839        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3840                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3841        // Compute granted permissions only if package has requested permissions
3842        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3843                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3844        final PackageUserState state = ps.readUserState(userId);
3845
3846        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3847                && ps.isSystem()) {
3848            flags |= MATCH_ANY_USER;
3849        }
3850
3851        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3852                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3853
3854        if (packageInfo == null) {
3855            return null;
3856        }
3857
3858        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3859                resolveExternalPackageNameLPr(p);
3860
3861        return packageInfo;
3862    }
3863
3864    @Override
3865    public void checkPackageStartable(String packageName, int userId) {
3866        final int callingUid = Binder.getCallingUid();
3867        if (getInstantAppPackageName(callingUid) != null) {
3868            throw new SecurityException("Instant applications don't have access to this method");
3869        }
3870        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3871        synchronized (mPackages) {
3872            final PackageSetting ps = mSettings.mPackages.get(packageName);
3873            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3874                throw new SecurityException("Package " + packageName + " was not found!");
3875            }
3876
3877            if (!ps.getInstalled(userId)) {
3878                throw new SecurityException(
3879                        "Package " + packageName + " was not installed for user " + userId + "!");
3880            }
3881
3882            if (mSafeMode && !ps.isSystem()) {
3883                throw new SecurityException("Package " + packageName + " not a system app!");
3884            }
3885
3886            if (mFrozenPackages.contains(packageName)) {
3887                throw new SecurityException("Package " + packageName + " is currently frozen!");
3888            }
3889
3890            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3891                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3892            }
3893        }
3894    }
3895
3896    @Override
3897    public boolean isPackageAvailable(String packageName, int userId) {
3898        if (!sUserManager.exists(userId)) return false;
3899        final int callingUid = Binder.getCallingUid();
3900        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3901                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3902        synchronized (mPackages) {
3903            PackageParser.Package p = mPackages.get(packageName);
3904            if (p != null) {
3905                final PackageSetting ps = (PackageSetting) p.mExtras;
3906                if (filterAppAccessLPr(ps, callingUid, userId)) {
3907                    return false;
3908                }
3909                if (ps != null) {
3910                    final PackageUserState state = ps.readUserState(userId);
3911                    if (state != null) {
3912                        return PackageParser.isAvailable(state);
3913                    }
3914                }
3915            }
3916        }
3917        return false;
3918    }
3919
3920    @Override
3921    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3922        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3923                flags, Binder.getCallingUid(), userId);
3924    }
3925
3926    @Override
3927    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3928            int flags, int userId) {
3929        return getPackageInfoInternal(versionedPackage.getPackageName(),
3930                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3931    }
3932
3933    /**
3934     * Important: The provided filterCallingUid is used exclusively to filter out packages
3935     * that can be seen based on user state. It's typically the original caller uid prior
3936     * to clearing. Because it can only be provided by trusted code, it's value can be
3937     * trusted and will be used as-is; unlike userId which will be validated by this method.
3938     */
3939    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3940            int flags, int filterCallingUid, int userId) {
3941        if (!sUserManager.exists(userId)) return null;
3942        flags = updateFlagsForPackage(flags, userId, packageName);
3943        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3944                false /* requireFullPermission */, false /* checkShell */, "get package info");
3945
3946        // reader
3947        synchronized (mPackages) {
3948            // Normalize package name to handle renamed packages and static libs
3949            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3950
3951            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3952            if (matchFactoryOnly) {
3953                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3954                if (ps != null) {
3955                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3956                        return null;
3957                    }
3958                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3959                        return null;
3960                    }
3961                    return generatePackageInfo(ps, flags, userId);
3962                }
3963            }
3964
3965            PackageParser.Package p = mPackages.get(packageName);
3966            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3967                return null;
3968            }
3969            if (DEBUG_PACKAGE_INFO)
3970                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3971            if (p != null) {
3972                final PackageSetting ps = (PackageSetting) p.mExtras;
3973                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3974                    return null;
3975                }
3976                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3977                    return null;
3978                }
3979                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3980            }
3981            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3982                final PackageSetting ps = mSettings.mPackages.get(packageName);
3983                if (ps == null) return null;
3984                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3985                    return null;
3986                }
3987                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3988                    return null;
3989                }
3990                return generatePackageInfo(ps, flags, userId);
3991            }
3992        }
3993        return null;
3994    }
3995
3996    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3997        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3998            return true;
3999        }
4000        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4001            return true;
4002        }
4003        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4004            return true;
4005        }
4006        return false;
4007    }
4008
4009    private boolean isComponentVisibleToInstantApp(
4010            @Nullable ComponentName component, @ComponentType int type) {
4011        if (type == TYPE_ACTIVITY) {
4012            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4013            return activity != null
4014                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4015                    : false;
4016        } else if (type == TYPE_RECEIVER) {
4017            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4018            return activity != null
4019                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4020                    : false;
4021        } else if (type == TYPE_SERVICE) {
4022            final PackageParser.Service service = mServices.mServices.get(component);
4023            return service != null
4024                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4025                    : false;
4026        } else if (type == TYPE_PROVIDER) {
4027            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4028            return provider != null
4029                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4030                    : false;
4031        } else if (type == TYPE_UNKNOWN) {
4032            return isComponentVisibleToInstantApp(component);
4033        }
4034        return false;
4035    }
4036
4037    /**
4038     * Returns whether or not access to the application should be filtered.
4039     * <p>
4040     * Access may be limited based upon whether the calling or target applications
4041     * are instant applications.
4042     *
4043     * @see #canAccessInstantApps(int)
4044     */
4045    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4046            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4047        // if we're in an isolated process, get the real calling UID
4048        if (Process.isIsolated(callingUid)) {
4049            callingUid = mIsolatedOwners.get(callingUid);
4050        }
4051        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4052        final boolean callerIsInstantApp = instantAppPkgName != null;
4053        if (ps == null) {
4054            if (callerIsInstantApp) {
4055                // pretend the application exists, but, needs to be filtered
4056                return true;
4057            }
4058            return false;
4059        }
4060        // if the target and caller are the same application, don't filter
4061        if (isCallerSameApp(ps.name, callingUid)) {
4062            return false;
4063        }
4064        if (callerIsInstantApp) {
4065            // request for a specific component; if it hasn't been explicitly exposed, filter
4066            if (component != null) {
4067                return !isComponentVisibleToInstantApp(component, componentType);
4068            }
4069            // request for application; if no components have been explicitly exposed, filter
4070            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4071        }
4072        if (ps.getInstantApp(userId)) {
4073            // caller can see all components of all instant applications, don't filter
4074            if (canViewInstantApps(callingUid, userId)) {
4075                return false;
4076            }
4077            // request for a specific instant application component, filter
4078            if (component != null) {
4079                return true;
4080            }
4081            // request for an instant application; if the caller hasn't been granted access, filter
4082            return !mInstantAppRegistry.isInstantAccessGranted(
4083                    userId, UserHandle.getAppId(callingUid), ps.appId);
4084        }
4085        return false;
4086    }
4087
4088    /**
4089     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4090     */
4091    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4092        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4093    }
4094
4095    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4096            int flags) {
4097        // Callers can access only the libs they depend on, otherwise they need to explicitly
4098        // ask for the shared libraries given the caller is allowed to access all static libs.
4099        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4100            // System/shell/root get to see all static libs
4101            final int appId = UserHandle.getAppId(uid);
4102            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4103                    || appId == Process.ROOT_UID) {
4104                return false;
4105            }
4106        }
4107
4108        // No package means no static lib as it is always on internal storage
4109        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4110            return false;
4111        }
4112
4113        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4114                ps.pkg.staticSharedLibVersion);
4115        if (libEntry == null) {
4116            return false;
4117        }
4118
4119        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4120        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4121        if (uidPackageNames == null) {
4122            return true;
4123        }
4124
4125        for (String uidPackageName : uidPackageNames) {
4126            if (ps.name.equals(uidPackageName)) {
4127                return false;
4128            }
4129            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4130            if (uidPs != null) {
4131                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4132                        libEntry.info.getName());
4133                if (index < 0) {
4134                    continue;
4135                }
4136                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4137                    return false;
4138                }
4139            }
4140        }
4141        return true;
4142    }
4143
4144    @Override
4145    public String[] currentToCanonicalPackageNames(String[] names) {
4146        final int callingUid = Binder.getCallingUid();
4147        if (getInstantAppPackageName(callingUid) != null) {
4148            return names;
4149        }
4150        final String[] out = new String[names.length];
4151        // reader
4152        synchronized (mPackages) {
4153            final int callingUserId = UserHandle.getUserId(callingUid);
4154            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4155            for (int i=names.length-1; i>=0; i--) {
4156                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4157                boolean translateName = false;
4158                if (ps != null && ps.realName != null) {
4159                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4160                    translateName = !targetIsInstantApp
4161                            || canViewInstantApps
4162                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4163                                    UserHandle.getAppId(callingUid), ps.appId);
4164                }
4165                out[i] = translateName ? ps.realName : names[i];
4166            }
4167        }
4168        return out;
4169    }
4170
4171    @Override
4172    public String[] canonicalToCurrentPackageNames(String[] names) {
4173        final int callingUid = Binder.getCallingUid();
4174        if (getInstantAppPackageName(callingUid) != null) {
4175            return names;
4176        }
4177        final String[] out = new String[names.length];
4178        // reader
4179        synchronized (mPackages) {
4180            final int callingUserId = UserHandle.getUserId(callingUid);
4181            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4182            for (int i=names.length-1; i>=0; i--) {
4183                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4184                boolean translateName = false;
4185                if (cur != null) {
4186                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4187                    final boolean targetIsInstantApp =
4188                            ps != null && ps.getInstantApp(callingUserId);
4189                    translateName = !targetIsInstantApp
4190                            || canViewInstantApps
4191                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4192                                    UserHandle.getAppId(callingUid), ps.appId);
4193                }
4194                out[i] = translateName ? cur : names[i];
4195            }
4196        }
4197        return out;
4198    }
4199
4200    @Override
4201    public int getPackageUid(String packageName, int flags, int userId) {
4202        if (!sUserManager.exists(userId)) return -1;
4203        final int callingUid = Binder.getCallingUid();
4204        flags = updateFlagsForPackage(flags, userId, packageName);
4205        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4206                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4207
4208        // reader
4209        synchronized (mPackages) {
4210            final PackageParser.Package p = mPackages.get(packageName);
4211            if (p != null && p.isMatch(flags)) {
4212                PackageSetting ps = (PackageSetting) p.mExtras;
4213                if (filterAppAccessLPr(ps, callingUid, userId)) {
4214                    return -1;
4215                }
4216                return UserHandle.getUid(userId, p.applicationInfo.uid);
4217            }
4218            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4219                final PackageSetting ps = mSettings.mPackages.get(packageName);
4220                if (ps != null && ps.isMatch(flags)
4221                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4222                    return UserHandle.getUid(userId, ps.appId);
4223                }
4224            }
4225        }
4226
4227        return -1;
4228    }
4229
4230    @Override
4231    public int[] getPackageGids(String packageName, int flags, int userId) {
4232        if (!sUserManager.exists(userId)) return null;
4233        final int callingUid = Binder.getCallingUid();
4234        flags = updateFlagsForPackage(flags, userId, packageName);
4235        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4236                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4237
4238        // reader
4239        synchronized (mPackages) {
4240            final PackageParser.Package p = mPackages.get(packageName);
4241            if (p != null && p.isMatch(flags)) {
4242                PackageSetting ps = (PackageSetting) p.mExtras;
4243                if (filterAppAccessLPr(ps, callingUid, userId)) {
4244                    return null;
4245                }
4246                // TODO: Shouldn't this be checking for package installed state for userId and
4247                // return null?
4248                return ps.getPermissionsState().computeGids(userId);
4249            }
4250            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4251                final PackageSetting ps = mSettings.mPackages.get(packageName);
4252                if (ps != null && ps.isMatch(flags)
4253                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4254                    return ps.getPermissionsState().computeGids(userId);
4255                }
4256            }
4257        }
4258
4259        return null;
4260    }
4261
4262    @Override
4263    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4264        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4265    }
4266
4267    @Override
4268    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4269            int flags) {
4270        // TODO Move this to PermissionManager when mPermissionGroups is moved there
4271        synchronized (mPackages) {
4272            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4273                // This is thrown as NameNotFoundException
4274                return null;
4275            }
4276        }
4277        return new ParceledListSlice<>(
4278                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()));
4279    }
4280
4281    @Override
4282    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4283        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4284            return null;
4285        }
4286        // reader
4287        synchronized (mPackages) {
4288            return PackageParser.generatePermissionGroupInfo(
4289                    mPermissionGroups.get(name), flags);
4290        }
4291    }
4292
4293    @Override
4294    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4296            return ParceledListSlice.emptyList();
4297        }
4298        // reader
4299        synchronized (mPackages) {
4300            final int N = mPermissionGroups.size();
4301            ArrayList<PermissionGroupInfo> out
4302                    = new ArrayList<PermissionGroupInfo>(N);
4303            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4304                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4305            }
4306            return new ParceledListSlice<>(out);
4307        }
4308    }
4309
4310    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4311            int filterCallingUid, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        PackageSetting ps = mSettings.mPackages.get(packageName);
4314        if (ps != null) {
4315            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4316                return null;
4317            }
4318            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4319                return null;
4320            }
4321            if (ps.pkg == null) {
4322                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4323                if (pInfo != null) {
4324                    return pInfo.applicationInfo;
4325                }
4326                return null;
4327            }
4328            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4329                    ps.readUserState(userId), userId);
4330            if (ai != null) {
4331                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4332            }
4333            return ai;
4334        }
4335        return null;
4336    }
4337
4338    @Override
4339    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4340        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4341    }
4342
4343    /**
4344     * Important: The provided filterCallingUid is used exclusively to filter out applications
4345     * that can be seen based on user state. It's typically the original caller uid prior
4346     * to clearing. Because it can only be provided by trusted code, it's value can be
4347     * trusted and will be used as-is; unlike userId which will be validated by this method.
4348     */
4349    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4350            int filterCallingUid, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        flags = updateFlagsForApplication(flags, userId, packageName);
4353        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4354                false /* requireFullPermission */, false /* checkShell */, "get application info");
4355
4356        // writer
4357        synchronized (mPackages) {
4358            // Normalize package name to handle renamed packages and static libs
4359            packageName = resolveInternalPackageNameLPr(packageName,
4360                    PackageManager.VERSION_CODE_HIGHEST);
4361
4362            PackageParser.Package p = mPackages.get(packageName);
4363            if (DEBUG_PACKAGE_INFO) Log.v(
4364                    TAG, "getApplicationInfo " + packageName
4365                    + ": " + p);
4366            if (p != null) {
4367                PackageSetting ps = mSettings.mPackages.get(packageName);
4368                if (ps == null) return null;
4369                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4370                    return null;
4371                }
4372                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4373                    return null;
4374                }
4375                // Note: isEnabledLP() does not apply here - always return info
4376                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4377                        p, flags, ps.readUserState(userId), userId);
4378                if (ai != null) {
4379                    ai.packageName = resolveExternalPackageNameLPr(p);
4380                }
4381                return ai;
4382            }
4383            if ("android".equals(packageName)||"system".equals(packageName)) {
4384                return mAndroidApplication;
4385            }
4386            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4387                // Already generates the external package name
4388                return generateApplicationInfoFromSettingsLPw(packageName,
4389                        flags, filterCallingUid, userId);
4390            }
4391        }
4392        return null;
4393    }
4394
4395    private String normalizePackageNameLPr(String packageName) {
4396        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4397        return normalizedPackageName != null ? normalizedPackageName : packageName;
4398    }
4399
4400    @Override
4401    public void deletePreloadsFileCache() {
4402        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4403            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4404        }
4405        File dir = Environment.getDataPreloadsFileCacheDirectory();
4406        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4407        FileUtils.deleteContents(dir);
4408    }
4409
4410    @Override
4411    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4412            final int storageFlags, final IPackageDataObserver observer) {
4413        mContext.enforceCallingOrSelfPermission(
4414                android.Manifest.permission.CLEAR_APP_CACHE, null);
4415        mHandler.post(() -> {
4416            boolean success = false;
4417            try {
4418                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4419                success = true;
4420            } catch (IOException e) {
4421                Slog.w(TAG, e);
4422            }
4423            if (observer != null) {
4424                try {
4425                    observer.onRemoveCompleted(null, success);
4426                } catch (RemoteException e) {
4427                    Slog.w(TAG, e);
4428                }
4429            }
4430        });
4431    }
4432
4433    @Override
4434    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4435            final int storageFlags, final IntentSender pi) {
4436        mContext.enforceCallingOrSelfPermission(
4437                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4438        mHandler.post(() -> {
4439            boolean success = false;
4440            try {
4441                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4442                success = true;
4443            } catch (IOException e) {
4444                Slog.w(TAG, e);
4445            }
4446            if (pi != null) {
4447                try {
4448                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4449                } catch (SendIntentException e) {
4450                    Slog.w(TAG, e);
4451                }
4452            }
4453        });
4454    }
4455
4456    /**
4457     * Blocking call to clear various types of cached data across the system
4458     * until the requested bytes are available.
4459     */
4460    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4461        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4462        final File file = storage.findPathForUuid(volumeUuid);
4463        if (file.getUsableSpace() >= bytes) return;
4464
4465        if (ENABLE_FREE_CACHE_V2) {
4466            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4467                    volumeUuid);
4468            final boolean aggressive = (storageFlags
4469                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4470            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4471
4472            // 1. Pre-flight to determine if we have any chance to succeed
4473            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4474            if (internalVolume && (aggressive || SystemProperties
4475                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4476                deletePreloadsFileCache();
4477                if (file.getUsableSpace() >= bytes) return;
4478            }
4479
4480            // 3. Consider parsed APK data (aggressive only)
4481            if (internalVolume && aggressive) {
4482                FileUtils.deleteContents(mCacheDir);
4483                if (file.getUsableSpace() >= bytes) return;
4484            }
4485
4486            // 4. Consider cached app data (above quotas)
4487            try {
4488                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4489                        Installer.FLAG_FREE_CACHE_V2);
4490            } catch (InstallerException ignored) {
4491            }
4492            if (file.getUsableSpace() >= bytes) return;
4493
4494            // 5. Consider shared libraries with refcount=0 and age>min cache period
4495            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4496                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4497                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4498                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4499                return;
4500            }
4501
4502            // 6. Consider dexopt output (aggressive only)
4503            // TODO: Implement
4504
4505            // 7. Consider installed instant apps unused longer than min cache period
4506            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4507                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4508                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4509                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4510                return;
4511            }
4512
4513            // 8. Consider cached app data (below quotas)
4514            try {
4515                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4516                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4517            } catch (InstallerException ignored) {
4518            }
4519            if (file.getUsableSpace() >= bytes) return;
4520
4521            // 9. Consider DropBox entries
4522            // TODO: Implement
4523
4524            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4525            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4526                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4527                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4528                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4529                return;
4530            }
4531        } else {
4532            try {
4533                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4534            } catch (InstallerException ignored) {
4535            }
4536            if (file.getUsableSpace() >= bytes) return;
4537        }
4538
4539        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4540    }
4541
4542    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4543            throws IOException {
4544        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4545        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4546
4547        List<VersionedPackage> packagesToDelete = null;
4548        final long now = System.currentTimeMillis();
4549
4550        synchronized (mPackages) {
4551            final int[] allUsers = sUserManager.getUserIds();
4552            final int libCount = mSharedLibraries.size();
4553            for (int i = 0; i < libCount; i++) {
4554                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4555                if (versionedLib == null) {
4556                    continue;
4557                }
4558                final int versionCount = versionedLib.size();
4559                for (int j = 0; j < versionCount; j++) {
4560                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4561                    // Skip packages that are not static shared libs.
4562                    if (!libInfo.isStatic()) {
4563                        break;
4564                    }
4565                    // Important: We skip static shared libs used for some user since
4566                    // in such a case we need to keep the APK on the device. The check for
4567                    // a lib being used for any user is performed by the uninstall call.
4568                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4569                    // Resolve the package name - we use synthetic package names internally
4570                    final String internalPackageName = resolveInternalPackageNameLPr(
4571                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4572                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4573                    // Skip unused static shared libs cached less than the min period
4574                    // to prevent pruning a lib needed by a subsequently installed package.
4575                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4576                        continue;
4577                    }
4578                    if (packagesToDelete == null) {
4579                        packagesToDelete = new ArrayList<>();
4580                    }
4581                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4582                            declaringPackage.getVersionCode()));
4583                }
4584            }
4585        }
4586
4587        if (packagesToDelete != null) {
4588            final int packageCount = packagesToDelete.size();
4589            for (int i = 0; i < packageCount; i++) {
4590                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4591                // Delete the package synchronously (will fail of the lib used for any user).
4592                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4593                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4594                                == PackageManager.DELETE_SUCCEEDED) {
4595                    if (volume.getUsableSpace() >= neededSpace) {
4596                        return true;
4597                    }
4598                }
4599            }
4600        }
4601
4602        return false;
4603    }
4604
4605    /**
4606     * Update given flags based on encryption status of current user.
4607     */
4608    private int updateFlags(int flags, int userId) {
4609        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4610                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4611            // Caller expressed an explicit opinion about what encryption
4612            // aware/unaware components they want to see, so fall through and
4613            // give them what they want
4614        } else {
4615            // Caller expressed no opinion, so match based on user state
4616            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4617                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4618            } else {
4619                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4620            }
4621        }
4622        return flags;
4623    }
4624
4625    private UserManagerInternal getUserManagerInternal() {
4626        if (mUserManagerInternal == null) {
4627            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4628        }
4629        return mUserManagerInternal;
4630    }
4631
4632    private DeviceIdleController.LocalService getDeviceIdleController() {
4633        if (mDeviceIdleController == null) {
4634            mDeviceIdleController =
4635                    LocalServices.getService(DeviceIdleController.LocalService.class);
4636        }
4637        return mDeviceIdleController;
4638    }
4639
4640    /**
4641     * Update given flags when being used to request {@link PackageInfo}.
4642     */
4643    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4644        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4645        boolean triaged = true;
4646        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4647                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4648            // Caller is asking for component details, so they'd better be
4649            // asking for specific encryption matching behavior, or be triaged
4650            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4651                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4652                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4653                triaged = false;
4654            }
4655        }
4656        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4657                | PackageManager.MATCH_SYSTEM_ONLY
4658                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4659            triaged = false;
4660        }
4661        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4662            mPermissionManager.enforceCrossUserPermission(
4663                    Binder.getCallingUid(), userId, false, false,
4664                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4665                    + Debug.getCallers(5));
4666        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4667                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4668            // If the caller wants all packages and has a restricted profile associated with it,
4669            // then match all users. This is to make sure that launchers that need to access work
4670            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4671            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4672            flags |= PackageManager.MATCH_ANY_USER;
4673        }
4674        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4675            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4676                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4677        }
4678        return updateFlags(flags, userId);
4679    }
4680
4681    /**
4682     * Update given flags when being used to request {@link ApplicationInfo}.
4683     */
4684    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4685        return updateFlagsForPackage(flags, userId, cookie);
4686    }
4687
4688    /**
4689     * Update given flags when being used to request {@link ComponentInfo}.
4690     */
4691    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4692        if (cookie instanceof Intent) {
4693            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4694                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4695            }
4696        }
4697
4698        boolean triaged = true;
4699        // Caller is asking for component details, so they'd better be
4700        // asking for specific encryption matching behavior, or be triaged
4701        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4702                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4703                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4704            triaged = false;
4705        }
4706        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4707            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4708                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4709        }
4710
4711        return updateFlags(flags, userId);
4712    }
4713
4714    /**
4715     * Update given intent when being used to request {@link ResolveInfo}.
4716     */
4717    private Intent updateIntentForResolve(Intent intent) {
4718        if (intent.getSelector() != null) {
4719            intent = intent.getSelector();
4720        }
4721        if (DEBUG_PREFERRED) {
4722            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4723        }
4724        return intent;
4725    }
4726
4727    /**
4728     * Update given flags when being used to request {@link ResolveInfo}.
4729     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4730     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4731     * flag set. However, this flag is only honoured in three circumstances:
4732     * <ul>
4733     * <li>when called from a system process</li>
4734     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4735     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4736     * action and a {@code android.intent.category.BROWSABLE} category</li>
4737     * </ul>
4738     */
4739    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4740        return updateFlagsForResolve(flags, userId, intent, callingUid,
4741                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4742    }
4743    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4744            boolean wantInstantApps) {
4745        return updateFlagsForResolve(flags, userId, intent, callingUid,
4746                wantInstantApps, false /*onlyExposedExplicitly*/);
4747    }
4748    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4749            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4750        // Safe mode means we shouldn't match any third-party components
4751        if (mSafeMode) {
4752            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4753        }
4754        if (getInstantAppPackageName(callingUid) != null) {
4755            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4756            if (onlyExposedExplicitly) {
4757                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4758            }
4759            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4760            flags |= PackageManager.MATCH_INSTANT;
4761        } else {
4762            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4763            final boolean allowMatchInstant =
4764                    (wantInstantApps
4765                            && Intent.ACTION_VIEW.equals(intent.getAction())
4766                            && hasWebURI(intent))
4767                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4768            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4769                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4770            if (!allowMatchInstant) {
4771                flags &= ~PackageManager.MATCH_INSTANT;
4772            }
4773        }
4774        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4775    }
4776
4777    @Override
4778    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4779        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4780    }
4781
4782    /**
4783     * Important: The provided filterCallingUid is used exclusively to filter out activities
4784     * that can be seen based on user state. It's typically the original caller uid prior
4785     * to clearing. Because it can only be provided by trusted code, it's value can be
4786     * trusted and will be used as-is; unlike userId which will be validated by this method.
4787     */
4788    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4789            int filterCallingUid, int userId) {
4790        if (!sUserManager.exists(userId)) return null;
4791        flags = updateFlagsForComponent(flags, userId, component);
4792        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4793                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4794        synchronized (mPackages) {
4795            PackageParser.Activity a = mActivities.mActivities.get(component);
4796
4797            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4798            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4799                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4800                if (ps == null) return null;
4801                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4802                    return null;
4803                }
4804                return PackageParser.generateActivityInfo(
4805                        a, flags, ps.readUserState(userId), userId);
4806            }
4807            if (mResolveComponentName.equals(component)) {
4808                return PackageParser.generateActivityInfo(
4809                        mResolveActivity, flags, new PackageUserState(), userId);
4810            }
4811        }
4812        return null;
4813    }
4814
4815    @Override
4816    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4817            String resolvedType) {
4818        synchronized (mPackages) {
4819            if (component.equals(mResolveComponentName)) {
4820                // The resolver supports EVERYTHING!
4821                return true;
4822            }
4823            final int callingUid = Binder.getCallingUid();
4824            final int callingUserId = UserHandle.getUserId(callingUid);
4825            PackageParser.Activity a = mActivities.mActivities.get(component);
4826            if (a == null) {
4827                return false;
4828            }
4829            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4830            if (ps == null) {
4831                return false;
4832            }
4833            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4834                return false;
4835            }
4836            for (int i=0; i<a.intents.size(); i++) {
4837                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4838                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4839                    return true;
4840                }
4841            }
4842            return false;
4843        }
4844    }
4845
4846    @Override
4847    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4848        if (!sUserManager.exists(userId)) return null;
4849        final int callingUid = Binder.getCallingUid();
4850        flags = updateFlagsForComponent(flags, userId, component);
4851        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4852                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4853        synchronized (mPackages) {
4854            PackageParser.Activity a = mReceivers.mActivities.get(component);
4855            if (DEBUG_PACKAGE_INFO) Log.v(
4856                TAG, "getReceiverInfo " + component + ": " + a);
4857            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4858                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4859                if (ps == null) return null;
4860                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4861                    return null;
4862                }
4863                return PackageParser.generateActivityInfo(
4864                        a, flags, ps.readUserState(userId), userId);
4865            }
4866        }
4867        return null;
4868    }
4869
4870    @Override
4871    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4872            int flags, int userId) {
4873        if (!sUserManager.exists(userId)) return null;
4874        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4875        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4876            return null;
4877        }
4878
4879        flags = updateFlagsForPackage(flags, userId, null);
4880
4881        final boolean canSeeStaticLibraries =
4882                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4883                        == PERMISSION_GRANTED
4884                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4885                        == PERMISSION_GRANTED
4886                || canRequestPackageInstallsInternal(packageName,
4887                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4888                        false  /* throwIfPermNotDeclared*/)
4889                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4890                        == PERMISSION_GRANTED;
4891
4892        synchronized (mPackages) {
4893            List<SharedLibraryInfo> result = null;
4894
4895            final int libCount = mSharedLibraries.size();
4896            for (int i = 0; i < libCount; i++) {
4897                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4898                if (versionedLib == null) {
4899                    continue;
4900                }
4901
4902                final int versionCount = versionedLib.size();
4903                for (int j = 0; j < versionCount; j++) {
4904                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4905                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4906                        break;
4907                    }
4908                    final long identity = Binder.clearCallingIdentity();
4909                    try {
4910                        PackageInfo packageInfo = getPackageInfoVersioned(
4911                                libInfo.getDeclaringPackage(), flags
4912                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4913                        if (packageInfo == null) {
4914                            continue;
4915                        }
4916                    } finally {
4917                        Binder.restoreCallingIdentity(identity);
4918                    }
4919
4920                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4921                            libInfo.getVersion(), libInfo.getType(),
4922                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4923                            flags, userId));
4924
4925                    if (result == null) {
4926                        result = new ArrayList<>();
4927                    }
4928                    result.add(resLibInfo);
4929                }
4930            }
4931
4932            return result != null ? new ParceledListSlice<>(result) : null;
4933        }
4934    }
4935
4936    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4937            SharedLibraryInfo libInfo, int flags, int userId) {
4938        List<VersionedPackage> versionedPackages = null;
4939        final int packageCount = mSettings.mPackages.size();
4940        for (int i = 0; i < packageCount; i++) {
4941            PackageSetting ps = mSettings.mPackages.valueAt(i);
4942
4943            if (ps == null) {
4944                continue;
4945            }
4946
4947            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4948                continue;
4949            }
4950
4951            final String libName = libInfo.getName();
4952            if (libInfo.isStatic()) {
4953                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4954                if (libIdx < 0) {
4955                    continue;
4956                }
4957                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4958                    continue;
4959                }
4960                if (versionedPackages == null) {
4961                    versionedPackages = new ArrayList<>();
4962                }
4963                // If the dependent is a static shared lib, use the public package name
4964                String dependentPackageName = ps.name;
4965                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4966                    dependentPackageName = ps.pkg.manifestPackageName;
4967                }
4968                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4969            } else if (ps.pkg != null) {
4970                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4971                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4972                    if (versionedPackages == null) {
4973                        versionedPackages = new ArrayList<>();
4974                    }
4975                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4976                }
4977            }
4978        }
4979
4980        return versionedPackages;
4981    }
4982
4983    @Override
4984    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4985        if (!sUserManager.exists(userId)) return null;
4986        final int callingUid = Binder.getCallingUid();
4987        flags = updateFlagsForComponent(flags, userId, component);
4988        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4989                false /* requireFullPermission */, false /* checkShell */, "get service info");
4990        synchronized (mPackages) {
4991            PackageParser.Service s = mServices.mServices.get(component);
4992            if (DEBUG_PACKAGE_INFO) Log.v(
4993                TAG, "getServiceInfo " + component + ": " + s);
4994            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4995                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4996                if (ps == null) return null;
4997                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4998                    return null;
4999                }
5000                return PackageParser.generateServiceInfo(
5001                        s, flags, ps.readUserState(userId), userId);
5002            }
5003        }
5004        return null;
5005    }
5006
5007    @Override
5008    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5009        if (!sUserManager.exists(userId)) return null;
5010        final int callingUid = Binder.getCallingUid();
5011        flags = updateFlagsForComponent(flags, userId, component);
5012        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5013                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5014        synchronized (mPackages) {
5015            PackageParser.Provider p = mProviders.mProviders.get(component);
5016            if (DEBUG_PACKAGE_INFO) Log.v(
5017                TAG, "getProviderInfo " + component + ": " + p);
5018            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5019                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5020                if (ps == null) return null;
5021                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5022                    return null;
5023                }
5024                return PackageParser.generateProviderInfo(
5025                        p, flags, ps.readUserState(userId), userId);
5026            }
5027        }
5028        return null;
5029    }
5030
5031    @Override
5032    public String[] getSystemSharedLibraryNames() {
5033        // allow instant applications
5034        synchronized (mPackages) {
5035            Set<String> libs = null;
5036            final int libCount = mSharedLibraries.size();
5037            for (int i = 0; i < libCount; i++) {
5038                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5039                if (versionedLib == null) {
5040                    continue;
5041                }
5042                final int versionCount = versionedLib.size();
5043                for (int j = 0; j < versionCount; j++) {
5044                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5045                    if (!libEntry.info.isStatic()) {
5046                        if (libs == null) {
5047                            libs = new ArraySet<>();
5048                        }
5049                        libs.add(libEntry.info.getName());
5050                        break;
5051                    }
5052                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5053                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5054                            UserHandle.getUserId(Binder.getCallingUid()),
5055                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5056                        if (libs == null) {
5057                            libs = new ArraySet<>();
5058                        }
5059                        libs.add(libEntry.info.getName());
5060                        break;
5061                    }
5062                }
5063            }
5064
5065            if (libs != null) {
5066                String[] libsArray = new String[libs.size()];
5067                libs.toArray(libsArray);
5068                return libsArray;
5069            }
5070
5071            return null;
5072        }
5073    }
5074
5075    @Override
5076    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5077        // allow instant applications
5078        synchronized (mPackages) {
5079            return mServicesSystemSharedLibraryPackageName;
5080        }
5081    }
5082
5083    @Override
5084    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5085        // allow instant applications
5086        synchronized (mPackages) {
5087            return mSharedSystemSharedLibraryPackageName;
5088        }
5089    }
5090
5091    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5092        for (int i = userList.length - 1; i >= 0; --i) {
5093            final int userId = userList[i];
5094            // don't add instant app to the list of updates
5095            if (pkgSetting.getInstantApp(userId)) {
5096                continue;
5097            }
5098            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5099            if (changedPackages == null) {
5100                changedPackages = new SparseArray<>();
5101                mChangedPackages.put(userId, changedPackages);
5102            }
5103            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5104            if (sequenceNumbers == null) {
5105                sequenceNumbers = new HashMap<>();
5106                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5107            }
5108            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5109            if (sequenceNumber != null) {
5110                changedPackages.remove(sequenceNumber);
5111            }
5112            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5113            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5114        }
5115        mChangedPackagesSequenceNumber++;
5116    }
5117
5118    @Override
5119    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5120        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5121            return null;
5122        }
5123        synchronized (mPackages) {
5124            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5125                return null;
5126            }
5127            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5128            if (changedPackages == null) {
5129                return null;
5130            }
5131            final List<String> packageNames =
5132                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5133            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5134                final String packageName = changedPackages.get(i);
5135                if (packageName != null) {
5136                    packageNames.add(packageName);
5137                }
5138            }
5139            return packageNames.isEmpty()
5140                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5141        }
5142    }
5143
5144    @Override
5145    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5146        // allow instant applications
5147        ArrayList<FeatureInfo> res;
5148        synchronized (mAvailableFeatures) {
5149            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5150            res.addAll(mAvailableFeatures.values());
5151        }
5152        final FeatureInfo fi = new FeatureInfo();
5153        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5154                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5155        res.add(fi);
5156
5157        return new ParceledListSlice<>(res);
5158    }
5159
5160    @Override
5161    public boolean hasSystemFeature(String name, int version) {
5162        // allow instant applications
5163        synchronized (mAvailableFeatures) {
5164            final FeatureInfo feat = mAvailableFeatures.get(name);
5165            if (feat == null) {
5166                return false;
5167            } else {
5168                return feat.version >= version;
5169            }
5170        }
5171    }
5172
5173    @Override
5174    public int checkPermission(String permName, String pkgName, int userId) {
5175        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5176    }
5177
5178    @Override
5179    public int checkUidPermission(String permName, int uid) {
5180        final int callingUid = Binder.getCallingUid();
5181        final int callingUserId = UserHandle.getUserId(callingUid);
5182        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5183        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5184        final int userId = UserHandle.getUserId(uid);
5185        if (!sUserManager.exists(userId)) {
5186            return PackageManager.PERMISSION_DENIED;
5187        }
5188
5189        synchronized (mPackages) {
5190            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5191            if (obj != null) {
5192                if (obj instanceof SharedUserSetting) {
5193                    if (isCallerInstantApp) {
5194                        return PackageManager.PERMISSION_DENIED;
5195                    }
5196                } else if (obj instanceof PackageSetting) {
5197                    final PackageSetting ps = (PackageSetting) obj;
5198                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5199                        return PackageManager.PERMISSION_DENIED;
5200                    }
5201                }
5202                final SettingBase settingBase = (SettingBase) obj;
5203                final PermissionsState permissionsState = settingBase.getPermissionsState();
5204                if (permissionsState.hasPermission(permName, userId)) {
5205                    if (isUidInstantApp) {
5206                        if (mPermissionManager.isPermissionInstant(permName)) {
5207                            return PackageManager.PERMISSION_GRANTED;
5208                        }
5209                    } else {
5210                        return PackageManager.PERMISSION_GRANTED;
5211                    }
5212                }
5213                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5214                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5215                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5216                    return PackageManager.PERMISSION_GRANTED;
5217                }
5218            } else {
5219                ArraySet<String> perms = mSystemPermissions.get(uid);
5220                if (perms != null) {
5221                    if (perms.contains(permName)) {
5222                        return PackageManager.PERMISSION_GRANTED;
5223                    }
5224                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5225                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5226                        return PackageManager.PERMISSION_GRANTED;
5227                    }
5228                }
5229            }
5230        }
5231
5232        return PackageManager.PERMISSION_DENIED;
5233    }
5234
5235    @Override
5236    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5237        if (UserHandle.getCallingUserId() != userId) {
5238            mContext.enforceCallingPermission(
5239                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5240                    "isPermissionRevokedByPolicy for user " + userId);
5241        }
5242
5243        if (checkPermission(permission, packageName, userId)
5244                == PackageManager.PERMISSION_GRANTED) {
5245            return false;
5246        }
5247
5248        final int callingUid = Binder.getCallingUid();
5249        if (getInstantAppPackageName(callingUid) != null) {
5250            if (!isCallerSameApp(packageName, callingUid)) {
5251                return false;
5252            }
5253        } else {
5254            if (isInstantApp(packageName, userId)) {
5255                return false;
5256            }
5257        }
5258
5259        final long identity = Binder.clearCallingIdentity();
5260        try {
5261            final int flags = getPermissionFlags(permission, packageName, userId);
5262            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5263        } finally {
5264            Binder.restoreCallingIdentity(identity);
5265        }
5266    }
5267
5268    @Override
5269    public String getPermissionControllerPackageName() {
5270        synchronized (mPackages) {
5271            return mRequiredInstallerPackage;
5272        }
5273    }
5274
5275    boolean addPermission(PermissionInfo info, final boolean async) {
5276        return mPermissionManager.addPermission(
5277                info, async, getCallingUid(), new PermissionCallback() {
5278                    @Override
5279                    public void onPermissionChanged() {
5280                        if (!async) {
5281                            mSettings.writeLPr();
5282                        } else {
5283                            scheduleWriteSettingsLocked();
5284                        }
5285                    }
5286                });
5287    }
5288
5289    @Override
5290    public boolean addPermission(PermissionInfo info) {
5291        synchronized (mPackages) {
5292            return addPermission(info, false);
5293        }
5294    }
5295
5296    @Override
5297    public boolean addPermissionAsync(PermissionInfo info) {
5298        synchronized (mPackages) {
5299            return addPermission(info, true);
5300        }
5301    }
5302
5303    @Override
5304    public void removePermission(String permName) {
5305        mPermissionManager.removePermission(permName, getCallingUid(), mPermissionCallback);
5306    }
5307
5308    @Override
5309    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5310        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5311                getCallingUid(), userId, mPermissionCallback);
5312    }
5313
5314    @Override
5315    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5316        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5317                getCallingUid(), userId, mPermissionCallback);
5318    }
5319
5320    /**
5321     * Get the first event id for the permission.
5322     *
5323     * <p>There are four events for each permission: <ul>
5324     *     <li>Request permission: first id + 0</li>
5325     *     <li>Grant permission: first id + 1</li>
5326     *     <li>Request for permission denied: first id + 2</li>
5327     *     <li>Revoke permission: first id + 3</li>
5328     * </ul></p>
5329     *
5330     * @param name name of the permission
5331     *
5332     * @return The first event id for the permission
5333     */
5334    private static int getBaseEventId(@NonNull String name) {
5335        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5336
5337        if (eventIdIndex == -1) {
5338            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5339                    || Build.IS_USER) {
5340                Log.i(TAG, "Unknown permission " + name);
5341
5342                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5343            } else {
5344                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5345                //
5346                // Also update
5347                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5348                // - metrics_constants.proto
5349                throw new IllegalStateException("Unknown permission " + name);
5350            }
5351        }
5352
5353        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5354    }
5355
5356    /**
5357     * Log that a permission was revoked.
5358     *
5359     * @param context Context of the caller
5360     * @param name name of the permission
5361     * @param packageName package permission if for
5362     */
5363    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5364            @NonNull String packageName) {
5365        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5366    }
5367
5368    /**
5369     * Log that a permission request was granted.
5370     *
5371     * @param context Context of the caller
5372     * @param name name of the permission
5373     * @param packageName package permission if for
5374     */
5375    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5376            @NonNull String packageName) {
5377        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5378    }
5379
5380    @Override
5381    public void resetRuntimePermissions() {
5382        mContext.enforceCallingOrSelfPermission(
5383                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5384                "revokeRuntimePermission");
5385
5386        int callingUid = Binder.getCallingUid();
5387        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5388            mContext.enforceCallingOrSelfPermission(
5389                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5390                    "resetRuntimePermissions");
5391        }
5392
5393        synchronized (mPackages) {
5394            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5395            for (int userId : UserManagerService.getInstance().getUserIds()) {
5396                final int packageCount = mPackages.size();
5397                for (int i = 0; i < packageCount; i++) {
5398                    PackageParser.Package pkg = mPackages.valueAt(i);
5399                    if (!(pkg.mExtras instanceof PackageSetting)) {
5400                        continue;
5401                    }
5402                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5403                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5404                }
5405            }
5406        }
5407    }
5408
5409    @Override
5410    public int getPermissionFlags(String permName, String packageName, int userId) {
5411        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5412    }
5413
5414    @Override
5415    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5416            int flagValues, int userId) {
5417        mPermissionManager.updatePermissionFlags(
5418                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5419                mPermissionCallback);
5420    }
5421
5422    /**
5423     * Update the permission flags for all packages and runtime permissions of a user in order
5424     * to allow device or profile owner to remove POLICY_FIXED.
5425     */
5426    @Override
5427    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5428        synchronized (mPackages) {
5429            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5430                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5431                    mPermissionCallback);
5432            if (changed) {
5433                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5434            }
5435        }
5436    }
5437
5438    @Override
5439    public boolean shouldShowRequestPermissionRationale(String permissionName,
5440            String packageName, int userId) {
5441        if (UserHandle.getCallingUserId() != userId) {
5442            mContext.enforceCallingPermission(
5443                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5444                    "canShowRequestPermissionRationale for user " + userId);
5445        }
5446
5447        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5448        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5449            return false;
5450        }
5451
5452        if (checkPermission(permissionName, packageName, userId)
5453                == PackageManager.PERMISSION_GRANTED) {
5454            return false;
5455        }
5456
5457        final int flags;
5458
5459        final long identity = Binder.clearCallingIdentity();
5460        try {
5461            flags = getPermissionFlags(permissionName,
5462                    packageName, userId);
5463        } finally {
5464            Binder.restoreCallingIdentity(identity);
5465        }
5466
5467        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5468                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5469                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5470
5471        if ((flags & fixedFlags) != 0) {
5472            return false;
5473        }
5474
5475        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5476    }
5477
5478    @Override
5479    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5480        mContext.enforceCallingOrSelfPermission(
5481                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5482                "addOnPermissionsChangeListener");
5483
5484        synchronized (mPackages) {
5485            mOnPermissionChangeListeners.addListenerLocked(listener);
5486        }
5487    }
5488
5489    @Override
5490    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5491        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5492            throw new SecurityException("Instant applications don't have access to this method");
5493        }
5494        synchronized (mPackages) {
5495            mOnPermissionChangeListeners.removeListenerLocked(listener);
5496        }
5497    }
5498
5499    @Override
5500    public boolean isProtectedBroadcast(String actionName) {
5501        // allow instant applications
5502        synchronized (mProtectedBroadcasts) {
5503            if (mProtectedBroadcasts.contains(actionName)) {
5504                return true;
5505            } else if (actionName != null) {
5506                // TODO: remove these terrible hacks
5507                if (actionName.startsWith("android.net.netmon.lingerExpired")
5508                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5509                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5510                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5511                    return true;
5512                }
5513            }
5514        }
5515        return false;
5516    }
5517
5518    @Override
5519    public int checkSignatures(String pkg1, String pkg2) {
5520        synchronized (mPackages) {
5521            final PackageParser.Package p1 = mPackages.get(pkg1);
5522            final PackageParser.Package p2 = mPackages.get(pkg2);
5523            if (p1 == null || p1.mExtras == null
5524                    || p2 == null || p2.mExtras == null) {
5525                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5526            }
5527            final int callingUid = Binder.getCallingUid();
5528            final int callingUserId = UserHandle.getUserId(callingUid);
5529            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5530            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5531            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5532                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5533                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5534            }
5535            return compareSignatures(p1.mSignatures, p2.mSignatures);
5536        }
5537    }
5538
5539    @Override
5540    public int checkUidSignatures(int uid1, int uid2) {
5541        final int callingUid = Binder.getCallingUid();
5542        final int callingUserId = UserHandle.getUserId(callingUid);
5543        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5544        // Map to base uids.
5545        uid1 = UserHandle.getAppId(uid1);
5546        uid2 = UserHandle.getAppId(uid2);
5547        // reader
5548        synchronized (mPackages) {
5549            Signature[] s1;
5550            Signature[] s2;
5551            Object obj = mSettings.getUserIdLPr(uid1);
5552            if (obj != null) {
5553                if (obj instanceof SharedUserSetting) {
5554                    if (isCallerInstantApp) {
5555                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5556                    }
5557                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5558                } else if (obj instanceof PackageSetting) {
5559                    final PackageSetting ps = (PackageSetting) obj;
5560                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5561                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5562                    }
5563                    s1 = ps.signatures.mSignatures;
5564                } else {
5565                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5566                }
5567            } else {
5568                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5569            }
5570            obj = mSettings.getUserIdLPr(uid2);
5571            if (obj != null) {
5572                if (obj instanceof SharedUserSetting) {
5573                    if (isCallerInstantApp) {
5574                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5575                    }
5576                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5577                } else if (obj instanceof PackageSetting) {
5578                    final PackageSetting ps = (PackageSetting) obj;
5579                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5580                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5581                    }
5582                    s2 = ps.signatures.mSignatures;
5583                } else {
5584                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5585                }
5586            } else {
5587                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5588            }
5589            return compareSignatures(s1, s2);
5590        }
5591    }
5592
5593    /**
5594     * This method should typically only be used when granting or revoking
5595     * permissions, since the app may immediately restart after this call.
5596     * <p>
5597     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5598     * guard your work against the app being relaunched.
5599     */
5600    private void killUid(int appId, int userId, String reason) {
5601        final long identity = Binder.clearCallingIdentity();
5602        try {
5603            IActivityManager am = ActivityManager.getService();
5604            if (am != null) {
5605                try {
5606                    am.killUid(appId, userId, reason);
5607                } catch (RemoteException e) {
5608                    /* ignore - same process */
5609                }
5610            }
5611        } finally {
5612            Binder.restoreCallingIdentity(identity);
5613        }
5614    }
5615
5616    /**
5617     * Compares two sets of signatures. Returns:
5618     * <br />
5619     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5620     * <br />
5621     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5622     * <br />
5623     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5624     * <br />
5625     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5626     * <br />
5627     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5628     */
5629    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5630        if (s1 == null) {
5631            return s2 == null
5632                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5633                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5634        }
5635
5636        if (s2 == null) {
5637            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5638        }
5639
5640        if (s1.length != s2.length) {
5641            return PackageManager.SIGNATURE_NO_MATCH;
5642        }
5643
5644        // Since both signature sets are of size 1, we can compare without HashSets.
5645        if (s1.length == 1) {
5646            return s1[0].equals(s2[0]) ?
5647                    PackageManager.SIGNATURE_MATCH :
5648                    PackageManager.SIGNATURE_NO_MATCH;
5649        }
5650
5651        ArraySet<Signature> set1 = new ArraySet<Signature>();
5652        for (Signature sig : s1) {
5653            set1.add(sig);
5654        }
5655        ArraySet<Signature> set2 = new ArraySet<Signature>();
5656        for (Signature sig : s2) {
5657            set2.add(sig);
5658        }
5659        // Make sure s2 contains all signatures in s1.
5660        if (set1.equals(set2)) {
5661            return PackageManager.SIGNATURE_MATCH;
5662        }
5663        return PackageManager.SIGNATURE_NO_MATCH;
5664    }
5665
5666    /**
5667     * If the database version for this type of package (internal storage or
5668     * external storage) is less than the version where package signatures
5669     * were updated, return true.
5670     */
5671    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5672        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5673        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5674    }
5675
5676    /**
5677     * Used for backward compatibility to make sure any packages with
5678     * certificate chains get upgraded to the new style. {@code existingSigs}
5679     * will be in the old format (since they were stored on disk from before the
5680     * system upgrade) and {@code scannedSigs} will be in the newer format.
5681     */
5682    private int compareSignaturesCompat(PackageSignatures existingSigs,
5683            PackageParser.Package scannedPkg) {
5684        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5685            return PackageManager.SIGNATURE_NO_MATCH;
5686        }
5687
5688        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5689        for (Signature sig : existingSigs.mSignatures) {
5690            existingSet.add(sig);
5691        }
5692        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5693        for (Signature sig : scannedPkg.mSignatures) {
5694            try {
5695                Signature[] chainSignatures = sig.getChainSignatures();
5696                for (Signature chainSig : chainSignatures) {
5697                    scannedCompatSet.add(chainSig);
5698                }
5699            } catch (CertificateEncodingException e) {
5700                scannedCompatSet.add(sig);
5701            }
5702        }
5703        /*
5704         * Make sure the expanded scanned set contains all signatures in the
5705         * existing one.
5706         */
5707        if (scannedCompatSet.equals(existingSet)) {
5708            // Migrate the old signatures to the new scheme.
5709            existingSigs.assignSignatures(scannedPkg.mSignatures);
5710            // The new KeySets will be re-added later in the scanning process.
5711            synchronized (mPackages) {
5712                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5713            }
5714            return PackageManager.SIGNATURE_MATCH;
5715        }
5716        return PackageManager.SIGNATURE_NO_MATCH;
5717    }
5718
5719    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5720        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5721        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5722    }
5723
5724    private int compareSignaturesRecover(PackageSignatures existingSigs,
5725            PackageParser.Package scannedPkg) {
5726        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5727            return PackageManager.SIGNATURE_NO_MATCH;
5728        }
5729
5730        String msg = null;
5731        try {
5732            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5733                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5734                        + scannedPkg.packageName);
5735                return PackageManager.SIGNATURE_MATCH;
5736            }
5737        } catch (CertificateException e) {
5738            msg = e.getMessage();
5739        }
5740
5741        logCriticalInfo(Log.INFO,
5742                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5743        return PackageManager.SIGNATURE_NO_MATCH;
5744    }
5745
5746    @Override
5747    public List<String> getAllPackages() {
5748        final int callingUid = Binder.getCallingUid();
5749        final int callingUserId = UserHandle.getUserId(callingUid);
5750        synchronized (mPackages) {
5751            if (canViewInstantApps(callingUid, callingUserId)) {
5752                return new ArrayList<String>(mPackages.keySet());
5753            }
5754            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5755            final List<String> result = new ArrayList<>();
5756            if (instantAppPkgName != null) {
5757                // caller is an instant application; filter unexposed applications
5758                for (PackageParser.Package pkg : mPackages.values()) {
5759                    if (!pkg.visibleToInstantApps) {
5760                        continue;
5761                    }
5762                    result.add(pkg.packageName);
5763                }
5764            } else {
5765                // caller is a normal application; filter instant applications
5766                for (PackageParser.Package pkg : mPackages.values()) {
5767                    final PackageSetting ps =
5768                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5769                    if (ps != null
5770                            && ps.getInstantApp(callingUserId)
5771                            && !mInstantAppRegistry.isInstantAccessGranted(
5772                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5773                        continue;
5774                    }
5775                    result.add(pkg.packageName);
5776                }
5777            }
5778            return result;
5779        }
5780    }
5781
5782    @Override
5783    public String[] getPackagesForUid(int uid) {
5784        final int callingUid = Binder.getCallingUid();
5785        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5786        final int userId = UserHandle.getUserId(uid);
5787        uid = UserHandle.getAppId(uid);
5788        // reader
5789        synchronized (mPackages) {
5790            Object obj = mSettings.getUserIdLPr(uid);
5791            if (obj instanceof SharedUserSetting) {
5792                if (isCallerInstantApp) {
5793                    return null;
5794                }
5795                final SharedUserSetting sus = (SharedUserSetting) obj;
5796                final int N = sus.packages.size();
5797                String[] res = new String[N];
5798                final Iterator<PackageSetting> it = sus.packages.iterator();
5799                int i = 0;
5800                while (it.hasNext()) {
5801                    PackageSetting ps = it.next();
5802                    if (ps.getInstalled(userId)) {
5803                        res[i++] = ps.name;
5804                    } else {
5805                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5806                    }
5807                }
5808                return res;
5809            } else if (obj instanceof PackageSetting) {
5810                final PackageSetting ps = (PackageSetting) obj;
5811                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5812                    return new String[]{ps.name};
5813                }
5814            }
5815        }
5816        return null;
5817    }
5818
5819    @Override
5820    public String getNameForUid(int uid) {
5821        final int callingUid = Binder.getCallingUid();
5822        if (getInstantAppPackageName(callingUid) != null) {
5823            return null;
5824        }
5825        synchronized (mPackages) {
5826            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5827            if (obj instanceof SharedUserSetting) {
5828                final SharedUserSetting sus = (SharedUserSetting) obj;
5829                return sus.name + ":" + sus.userId;
5830            } else if (obj instanceof PackageSetting) {
5831                final PackageSetting ps = (PackageSetting) obj;
5832                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5833                    return null;
5834                }
5835                return ps.name;
5836            }
5837            return null;
5838        }
5839    }
5840
5841    @Override
5842    public String[] getNamesForUids(int[] uids) {
5843        if (uids == null || uids.length == 0) {
5844            return null;
5845        }
5846        final int callingUid = Binder.getCallingUid();
5847        if (getInstantAppPackageName(callingUid) != null) {
5848            return null;
5849        }
5850        final String[] names = new String[uids.length];
5851        synchronized (mPackages) {
5852            for (int i = uids.length - 1; i >= 0; i--) {
5853                final int uid = uids[i];
5854                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5855                if (obj instanceof SharedUserSetting) {
5856                    final SharedUserSetting sus = (SharedUserSetting) obj;
5857                    names[i] = "shared:" + sus.name;
5858                } else if (obj instanceof PackageSetting) {
5859                    final PackageSetting ps = (PackageSetting) obj;
5860                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5861                        names[i] = null;
5862                    } else {
5863                        names[i] = ps.name;
5864                    }
5865                } else {
5866                    names[i] = null;
5867                }
5868            }
5869        }
5870        return names;
5871    }
5872
5873    @Override
5874    public int getUidForSharedUser(String sharedUserName) {
5875        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5876            return -1;
5877        }
5878        if (sharedUserName == null) {
5879            return -1;
5880        }
5881        // reader
5882        synchronized (mPackages) {
5883            SharedUserSetting suid;
5884            try {
5885                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5886                if (suid != null) {
5887                    return suid.userId;
5888                }
5889            } catch (PackageManagerException ignore) {
5890                // can't happen, but, still need to catch it
5891            }
5892            return -1;
5893        }
5894    }
5895
5896    @Override
5897    public int getFlagsForUid(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.pkgFlags;
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.pkgFlags;
5913            }
5914        }
5915        return 0;
5916    }
5917
5918    @Override
5919    public int getPrivateFlagsForUid(int uid) {
5920        final int callingUid = Binder.getCallingUid();
5921        if (getInstantAppPackageName(callingUid) != null) {
5922            return 0;
5923        }
5924        synchronized (mPackages) {
5925            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5926            if (obj instanceof SharedUserSetting) {
5927                final SharedUserSetting sus = (SharedUserSetting) obj;
5928                return sus.pkgPrivateFlags;
5929            } else if (obj instanceof PackageSetting) {
5930                final PackageSetting ps = (PackageSetting) obj;
5931                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5932                    return 0;
5933                }
5934                return ps.pkgPrivateFlags;
5935            }
5936        }
5937        return 0;
5938    }
5939
5940    @Override
5941    public boolean isUidPrivileged(int uid) {
5942        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5943            return false;
5944        }
5945        uid = UserHandle.getAppId(uid);
5946        // reader
5947        synchronized (mPackages) {
5948            Object obj = mSettings.getUserIdLPr(uid);
5949            if (obj instanceof SharedUserSetting) {
5950                final SharedUserSetting sus = (SharedUserSetting) obj;
5951                final Iterator<PackageSetting> it = sus.packages.iterator();
5952                while (it.hasNext()) {
5953                    if (it.next().isPrivileged()) {
5954                        return true;
5955                    }
5956                }
5957            } else if (obj instanceof PackageSetting) {
5958                final PackageSetting ps = (PackageSetting) obj;
5959                return ps.isPrivileged();
5960            }
5961        }
5962        return false;
5963    }
5964
5965    @Override
5966    public String[] getAppOpPermissionPackages(String permissionName) {
5967        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5968            return null;
5969        }
5970        synchronized (mPackages) {
5971            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5972            if (pkgs == null) {
5973                return null;
5974            }
5975            return pkgs.toArray(new String[pkgs.size()]);
5976        }
5977    }
5978
5979    @Override
5980    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5981            int flags, int userId) {
5982        return resolveIntentInternal(
5983                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5984    }
5985
5986    /**
5987     * Normally instant apps can only be resolved when they're visible to the caller.
5988     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5989     * since we need to allow the system to start any installed application.
5990     */
5991    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5992            int flags, int userId, boolean resolveForStart) {
5993        try {
5994            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5995
5996            if (!sUserManager.exists(userId)) return null;
5997            final int callingUid = Binder.getCallingUid();
5998            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5999            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6000                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6001
6002            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6003            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6004                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6005            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6006
6007            final ResolveInfo bestChoice =
6008                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6009            return bestChoice;
6010        } finally {
6011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6012        }
6013    }
6014
6015    @Override
6016    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6017        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6018            throw new SecurityException(
6019                    "findPersistentPreferredActivity can only be run by the system");
6020        }
6021        if (!sUserManager.exists(userId)) {
6022            return null;
6023        }
6024        final int callingUid = Binder.getCallingUid();
6025        intent = updateIntentForResolve(intent);
6026        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6027        final int flags = updateFlagsForResolve(
6028                0, userId, intent, callingUid, false /*includeInstantApps*/);
6029        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6030                userId);
6031        synchronized (mPackages) {
6032            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6033                    userId);
6034        }
6035    }
6036
6037    @Override
6038    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6039            IntentFilter filter, int match, ComponentName activity) {
6040        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6041            return;
6042        }
6043        final int userId = UserHandle.getCallingUserId();
6044        if (DEBUG_PREFERRED) {
6045            Log.v(TAG, "setLastChosenActivity intent=" + intent
6046                + " resolvedType=" + resolvedType
6047                + " flags=" + flags
6048                + " filter=" + filter
6049                + " match=" + match
6050                + " activity=" + activity);
6051            filter.dump(new PrintStreamPrinter(System.out), "    ");
6052        }
6053        intent.setComponent(null);
6054        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6055                userId);
6056        // Find any earlier preferred or last chosen entries and nuke them
6057        findPreferredActivity(intent, resolvedType,
6058                flags, query, 0, false, true, false, userId);
6059        // Add the new activity as the last chosen for this filter
6060        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6061                "Setting last chosen");
6062    }
6063
6064    @Override
6065    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6066        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6067            return null;
6068        }
6069        final int userId = UserHandle.getCallingUserId();
6070        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6071        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6072                userId);
6073        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6074                false, false, false, userId);
6075    }
6076
6077    /**
6078     * Returns whether or not instant apps have been disabled remotely.
6079     */
6080    private boolean isEphemeralDisabled() {
6081        return mEphemeralAppsDisabled;
6082    }
6083
6084    private boolean isInstantAppAllowed(
6085            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6086            boolean skipPackageCheck) {
6087        if (mInstantAppResolverConnection == null) {
6088            return false;
6089        }
6090        if (mInstantAppInstallerActivity == null) {
6091            return false;
6092        }
6093        if (intent.getComponent() != null) {
6094            return false;
6095        }
6096        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6097            return false;
6098        }
6099        if (!skipPackageCheck && intent.getPackage() != null) {
6100            return false;
6101        }
6102        final boolean isWebUri = hasWebURI(intent);
6103        if (!isWebUri || intent.getData().getHost() == null) {
6104            return false;
6105        }
6106        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6107        // Or if there's already an ephemeral app installed that handles the action
6108        synchronized (mPackages) {
6109            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6110            for (int n = 0; n < count; n++) {
6111                final ResolveInfo info = resolvedActivities.get(n);
6112                final String packageName = info.activityInfo.packageName;
6113                final PackageSetting ps = mSettings.mPackages.get(packageName);
6114                if (ps != null) {
6115                    // only check domain verification status if the app is not a browser
6116                    if (!info.handleAllWebDataURI) {
6117                        // Try to get the status from User settings first
6118                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6119                        final int status = (int) (packedStatus >> 32);
6120                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6121                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6122                            if (DEBUG_EPHEMERAL) {
6123                                Slog.v(TAG, "DENY instant app;"
6124                                    + " pkg: " + packageName + ", status: " + status);
6125                            }
6126                            return false;
6127                        }
6128                    }
6129                    if (ps.getInstantApp(userId)) {
6130                        if (DEBUG_EPHEMERAL) {
6131                            Slog.v(TAG, "DENY instant app installed;"
6132                                    + " pkg: " + packageName);
6133                        }
6134                        return false;
6135                    }
6136                }
6137            }
6138        }
6139        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6140        return true;
6141    }
6142
6143    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6144            Intent origIntent, String resolvedType, String callingPackage,
6145            Bundle verificationBundle, int userId) {
6146        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6147                new InstantAppRequest(responseObj, origIntent, resolvedType,
6148                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6149        mHandler.sendMessage(msg);
6150    }
6151
6152    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6153            int flags, List<ResolveInfo> query, int userId) {
6154        if (query != null) {
6155            final int N = query.size();
6156            if (N == 1) {
6157                return query.get(0);
6158            } else if (N > 1) {
6159                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6160                // If there is more than one activity with the same priority,
6161                // then let the user decide between them.
6162                ResolveInfo r0 = query.get(0);
6163                ResolveInfo r1 = query.get(1);
6164                if (DEBUG_INTENT_MATCHING || debug) {
6165                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6166                            + r1.activityInfo.name + "=" + r1.priority);
6167                }
6168                // If the first activity has a higher priority, or a different
6169                // default, then it is always desirable to pick it.
6170                if (r0.priority != r1.priority
6171                        || r0.preferredOrder != r1.preferredOrder
6172                        || r0.isDefault != r1.isDefault) {
6173                    return query.get(0);
6174                }
6175                // If we have saved a preference for a preferred activity for
6176                // this Intent, use that.
6177                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6178                        flags, query, r0.priority, true, false, debug, userId);
6179                if (ri != null) {
6180                    return ri;
6181                }
6182                // If we have an ephemeral app, use it
6183                for (int i = 0; i < N; i++) {
6184                    ri = query.get(i);
6185                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6186                        final String packageName = ri.activityInfo.packageName;
6187                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6188                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6189                        final int status = (int)(packedStatus >> 32);
6190                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6191                            return ri;
6192                        }
6193                    }
6194                }
6195                ri = new ResolveInfo(mResolveInfo);
6196                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6197                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6198                // If all of the options come from the same package, show the application's
6199                // label and icon instead of the generic resolver's.
6200                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6201                // and then throw away the ResolveInfo itself, meaning that the caller loses
6202                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6203                // a fallback for this case; we only set the target package's resources on
6204                // the ResolveInfo, not the ActivityInfo.
6205                final String intentPackage = intent.getPackage();
6206                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6207                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6208                    ri.resolvePackageName = intentPackage;
6209                    if (userNeedsBadging(userId)) {
6210                        ri.noResourceId = true;
6211                    } else {
6212                        ri.icon = appi.icon;
6213                    }
6214                    ri.iconResourceId = appi.icon;
6215                    ri.labelRes = appi.labelRes;
6216                }
6217                ri.activityInfo.applicationInfo = new ApplicationInfo(
6218                        ri.activityInfo.applicationInfo);
6219                if (userId != 0) {
6220                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6221                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6222                }
6223                // Make sure that the resolver is displayable in car mode
6224                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6225                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6226                return ri;
6227            }
6228        }
6229        return null;
6230    }
6231
6232    /**
6233     * Return true if the given list is not empty and all of its contents have
6234     * an activityInfo with the given package name.
6235     */
6236    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6237        if (ArrayUtils.isEmpty(list)) {
6238            return false;
6239        }
6240        for (int i = 0, N = list.size(); i < N; i++) {
6241            final ResolveInfo ri = list.get(i);
6242            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6243            if (ai == null || !packageName.equals(ai.packageName)) {
6244                return false;
6245            }
6246        }
6247        return true;
6248    }
6249
6250    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6251            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6252        final int N = query.size();
6253        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6254                .get(userId);
6255        // Get the list of persistent preferred activities that handle the intent
6256        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6257        List<PersistentPreferredActivity> pprefs = ppir != null
6258                ? ppir.queryIntent(intent, resolvedType,
6259                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6260                        userId)
6261                : null;
6262        if (pprefs != null && pprefs.size() > 0) {
6263            final int M = pprefs.size();
6264            for (int i=0; i<M; i++) {
6265                final PersistentPreferredActivity ppa = pprefs.get(i);
6266                if (DEBUG_PREFERRED || debug) {
6267                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6268                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6269                            + "\n  component=" + ppa.mComponent);
6270                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6271                }
6272                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6273                        flags | MATCH_DISABLED_COMPONENTS, userId);
6274                if (DEBUG_PREFERRED || debug) {
6275                    Slog.v(TAG, "Found persistent preferred activity:");
6276                    if (ai != null) {
6277                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6278                    } else {
6279                        Slog.v(TAG, "  null");
6280                    }
6281                }
6282                if (ai == null) {
6283                    // This previously registered persistent preferred activity
6284                    // component is no longer known. Ignore it and do NOT remove it.
6285                    continue;
6286                }
6287                for (int j=0; j<N; j++) {
6288                    final ResolveInfo ri = query.get(j);
6289                    if (!ri.activityInfo.applicationInfo.packageName
6290                            .equals(ai.applicationInfo.packageName)) {
6291                        continue;
6292                    }
6293                    if (!ri.activityInfo.name.equals(ai.name)) {
6294                        continue;
6295                    }
6296                    //  Found a persistent preference that can handle the intent.
6297                    if (DEBUG_PREFERRED || debug) {
6298                        Slog.v(TAG, "Returning persistent preferred activity: " +
6299                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6300                    }
6301                    return ri;
6302                }
6303            }
6304        }
6305        return null;
6306    }
6307
6308    // TODO: handle preferred activities missing while user has amnesia
6309    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6310            List<ResolveInfo> query, int priority, boolean always,
6311            boolean removeMatches, boolean debug, int userId) {
6312        if (!sUserManager.exists(userId)) return null;
6313        final int callingUid = Binder.getCallingUid();
6314        flags = updateFlagsForResolve(
6315                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6316        intent = updateIntentForResolve(intent);
6317        // writer
6318        synchronized (mPackages) {
6319            // Try to find a matching persistent preferred activity.
6320            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6321                    debug, userId);
6322
6323            // If a persistent preferred activity matched, use it.
6324            if (pri != null) {
6325                return pri;
6326            }
6327
6328            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6329            // Get the list of preferred activities that handle the intent
6330            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6331            List<PreferredActivity> prefs = pir != null
6332                    ? pir.queryIntent(intent, resolvedType,
6333                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6334                            userId)
6335                    : null;
6336            if (prefs != null && prefs.size() > 0) {
6337                boolean changed = false;
6338                try {
6339                    // First figure out how good the original match set is.
6340                    // We will only allow preferred activities that came
6341                    // from the same match quality.
6342                    int match = 0;
6343
6344                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6345
6346                    final int N = query.size();
6347                    for (int j=0; j<N; j++) {
6348                        final ResolveInfo ri = query.get(j);
6349                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6350                                + ": 0x" + Integer.toHexString(match));
6351                        if (ri.match > match) {
6352                            match = ri.match;
6353                        }
6354                    }
6355
6356                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6357                            + Integer.toHexString(match));
6358
6359                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6360                    final int M = prefs.size();
6361                    for (int i=0; i<M; i++) {
6362                        final PreferredActivity pa = prefs.get(i);
6363                        if (DEBUG_PREFERRED || debug) {
6364                            Slog.v(TAG, "Checking PreferredActivity ds="
6365                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6366                                    + "\n  component=" + pa.mPref.mComponent);
6367                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6368                        }
6369                        if (pa.mPref.mMatch != match) {
6370                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6371                                    + Integer.toHexString(pa.mPref.mMatch));
6372                            continue;
6373                        }
6374                        // If it's not an "always" type preferred activity and that's what we're
6375                        // looking for, skip it.
6376                        if (always && !pa.mPref.mAlways) {
6377                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6378                            continue;
6379                        }
6380                        final ActivityInfo ai = getActivityInfo(
6381                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6382                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6383                                userId);
6384                        if (DEBUG_PREFERRED || debug) {
6385                            Slog.v(TAG, "Found preferred activity:");
6386                            if (ai != null) {
6387                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6388                            } else {
6389                                Slog.v(TAG, "  null");
6390                            }
6391                        }
6392                        if (ai == null) {
6393                            // This previously registered preferred activity
6394                            // component is no longer known.  Most likely an update
6395                            // to the app was installed and in the new version this
6396                            // component no longer exists.  Clean it up by removing
6397                            // it from the preferred activities list, and skip it.
6398                            Slog.w(TAG, "Removing dangling preferred activity: "
6399                                    + pa.mPref.mComponent);
6400                            pir.removeFilter(pa);
6401                            changed = true;
6402                            continue;
6403                        }
6404                        for (int j=0; j<N; j++) {
6405                            final ResolveInfo ri = query.get(j);
6406                            if (!ri.activityInfo.applicationInfo.packageName
6407                                    .equals(ai.applicationInfo.packageName)) {
6408                                continue;
6409                            }
6410                            if (!ri.activityInfo.name.equals(ai.name)) {
6411                                continue;
6412                            }
6413
6414                            if (removeMatches) {
6415                                pir.removeFilter(pa);
6416                                changed = true;
6417                                if (DEBUG_PREFERRED) {
6418                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6419                                }
6420                                break;
6421                            }
6422
6423                            // Okay we found a previously set preferred or last chosen app.
6424                            // If the result set is different from when this
6425                            // was created, and is not a subset of the preferred set, we need to
6426                            // clear it and re-ask the user their preference, if we're looking for
6427                            // an "always" type entry.
6428                            if (always && !pa.mPref.sameSet(query)) {
6429                                if (pa.mPref.isSuperset(query)) {
6430                                    // some components of the set are no longer present in
6431                                    // the query, but the preferred activity can still be reused
6432                                    if (DEBUG_PREFERRED) {
6433                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6434                                                + " still valid as only non-preferred components"
6435                                                + " were removed for " + intent + " type "
6436                                                + resolvedType);
6437                                    }
6438                                    // remove obsolete components and re-add the up-to-date filter
6439                                    PreferredActivity freshPa = new PreferredActivity(pa,
6440                                            pa.mPref.mMatch,
6441                                            pa.mPref.discardObsoleteComponents(query),
6442                                            pa.mPref.mComponent,
6443                                            pa.mPref.mAlways);
6444                                    pir.removeFilter(pa);
6445                                    pir.addFilter(freshPa);
6446                                    changed = true;
6447                                } else {
6448                                    Slog.i(TAG,
6449                                            "Result set changed, dropping preferred activity for "
6450                                                    + intent + " type " + resolvedType);
6451                                    if (DEBUG_PREFERRED) {
6452                                        Slog.v(TAG, "Removing preferred activity since set changed "
6453                                                + pa.mPref.mComponent);
6454                                    }
6455                                    pir.removeFilter(pa);
6456                                    // Re-add the filter as a "last chosen" entry (!always)
6457                                    PreferredActivity lastChosen = new PreferredActivity(
6458                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6459                                    pir.addFilter(lastChosen);
6460                                    changed = true;
6461                                    return null;
6462                                }
6463                            }
6464
6465                            // Yay! Either the set matched or we're looking for the last chosen
6466                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6467                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6468                            return ri;
6469                        }
6470                    }
6471                } finally {
6472                    if (changed) {
6473                        if (DEBUG_PREFERRED) {
6474                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6475                        }
6476                        scheduleWritePackageRestrictionsLocked(userId);
6477                    }
6478                }
6479            }
6480        }
6481        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6482        return null;
6483    }
6484
6485    /*
6486     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6487     */
6488    @Override
6489    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6490            int targetUserId) {
6491        mContext.enforceCallingOrSelfPermission(
6492                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6493        List<CrossProfileIntentFilter> matches =
6494                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6495        if (matches != null) {
6496            int size = matches.size();
6497            for (int i = 0; i < size; i++) {
6498                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6499            }
6500        }
6501        if (hasWebURI(intent)) {
6502            // cross-profile app linking works only towards the parent.
6503            final int callingUid = Binder.getCallingUid();
6504            final UserInfo parent = getProfileParent(sourceUserId);
6505            synchronized(mPackages) {
6506                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6507                        false /*includeInstantApps*/);
6508                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6509                        intent, resolvedType, flags, sourceUserId, parent.id);
6510                return xpDomainInfo != null;
6511            }
6512        }
6513        return false;
6514    }
6515
6516    private UserInfo getProfileParent(int userId) {
6517        final long identity = Binder.clearCallingIdentity();
6518        try {
6519            return sUserManager.getProfileParent(userId);
6520        } finally {
6521            Binder.restoreCallingIdentity(identity);
6522        }
6523    }
6524
6525    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6526            String resolvedType, int userId) {
6527        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6528        if (resolver != null) {
6529            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6530        }
6531        return null;
6532    }
6533
6534    @Override
6535    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6536            String resolvedType, int flags, int userId) {
6537        try {
6538            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6539
6540            return new ParceledListSlice<>(
6541                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6542        } finally {
6543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6544        }
6545    }
6546
6547    /**
6548     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6549     * instant, returns {@code null}.
6550     */
6551    private String getInstantAppPackageName(int callingUid) {
6552        synchronized (mPackages) {
6553            // If the caller is an isolated app use the owner's uid for the lookup.
6554            if (Process.isIsolated(callingUid)) {
6555                callingUid = mIsolatedOwners.get(callingUid);
6556            }
6557            final int appId = UserHandle.getAppId(callingUid);
6558            final Object obj = mSettings.getUserIdLPr(appId);
6559            if (obj instanceof PackageSetting) {
6560                final PackageSetting ps = (PackageSetting) obj;
6561                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6562                return isInstantApp ? ps.pkg.packageName : null;
6563            }
6564        }
6565        return null;
6566    }
6567
6568    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6569            String resolvedType, int flags, int userId) {
6570        return queryIntentActivitiesInternal(
6571                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6572                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6573    }
6574
6575    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6576            String resolvedType, int flags, int filterCallingUid, int userId,
6577            boolean resolveForStart, boolean allowDynamicSplits) {
6578        if (!sUserManager.exists(userId)) return Collections.emptyList();
6579        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6580        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6581                false /* requireFullPermission */, false /* checkShell */,
6582                "query intent activities");
6583        final String pkgName = intent.getPackage();
6584        ComponentName comp = intent.getComponent();
6585        if (comp == null) {
6586            if (intent.getSelector() != null) {
6587                intent = intent.getSelector();
6588                comp = intent.getComponent();
6589            }
6590        }
6591
6592        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6593                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6594        if (comp != null) {
6595            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6596            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6597            if (ai != null) {
6598                // When specifying an explicit component, we prevent the activity from being
6599                // used when either 1) the calling package is normal and the activity is within
6600                // an ephemeral application or 2) the calling package is ephemeral and the
6601                // activity is not visible to ephemeral applications.
6602                final boolean matchInstantApp =
6603                        (flags & PackageManager.MATCH_INSTANT) != 0;
6604                final boolean matchVisibleToInstantAppOnly =
6605                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6606                final boolean matchExplicitlyVisibleOnly =
6607                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6608                final boolean isCallerInstantApp =
6609                        instantAppPkgName != null;
6610                final boolean isTargetSameInstantApp =
6611                        comp.getPackageName().equals(instantAppPkgName);
6612                final boolean isTargetInstantApp =
6613                        (ai.applicationInfo.privateFlags
6614                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6615                final boolean isTargetVisibleToInstantApp =
6616                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6617                final boolean isTargetExplicitlyVisibleToInstantApp =
6618                        isTargetVisibleToInstantApp
6619                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6620                final boolean isTargetHiddenFromInstantApp =
6621                        !isTargetVisibleToInstantApp
6622                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6623                final boolean blockResolution =
6624                        !isTargetSameInstantApp
6625                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6626                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6627                                        && isTargetHiddenFromInstantApp));
6628                if (!blockResolution) {
6629                    final ResolveInfo ri = new ResolveInfo();
6630                    ri.activityInfo = ai;
6631                    list.add(ri);
6632                }
6633            }
6634            return applyPostResolutionFilter(
6635                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6636        }
6637
6638        // reader
6639        boolean sortResult = false;
6640        boolean addEphemeral = false;
6641        List<ResolveInfo> result;
6642        final boolean ephemeralDisabled = isEphemeralDisabled();
6643        synchronized (mPackages) {
6644            if (pkgName == null) {
6645                List<CrossProfileIntentFilter> matchingFilters =
6646                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6647                // Check for results that need to skip the current profile.
6648                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6649                        resolvedType, flags, userId);
6650                if (xpResolveInfo != null) {
6651                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6652                    xpResult.add(xpResolveInfo);
6653                    return applyPostResolutionFilter(
6654                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6655                            allowDynamicSplits, filterCallingUid, userId);
6656                }
6657
6658                // Check for results in the current profile.
6659                result = filterIfNotSystemUser(mActivities.queryIntent(
6660                        intent, resolvedType, flags, userId), userId);
6661                addEphemeral = !ephemeralDisabled
6662                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6663                // Check for cross profile results.
6664                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6665                xpResolveInfo = queryCrossProfileIntents(
6666                        matchingFilters, intent, resolvedType, flags, userId,
6667                        hasNonNegativePriorityResult);
6668                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6669                    boolean isVisibleToUser = filterIfNotSystemUser(
6670                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6671                    if (isVisibleToUser) {
6672                        result.add(xpResolveInfo);
6673                        sortResult = true;
6674                    }
6675                }
6676                if (hasWebURI(intent)) {
6677                    CrossProfileDomainInfo xpDomainInfo = null;
6678                    final UserInfo parent = getProfileParent(userId);
6679                    if (parent != null) {
6680                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6681                                flags, userId, parent.id);
6682                    }
6683                    if (xpDomainInfo != null) {
6684                        if (xpResolveInfo != null) {
6685                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6686                            // in the result.
6687                            result.remove(xpResolveInfo);
6688                        }
6689                        if (result.size() == 0 && !addEphemeral) {
6690                            // No result in current profile, but found candidate in parent user.
6691                            // And we are not going to add emphemeral app, so we can return the
6692                            // result straight away.
6693                            result.add(xpDomainInfo.resolveInfo);
6694                            return applyPostResolutionFilter(result, instantAppPkgName,
6695                                    allowDynamicSplits, filterCallingUid, userId);
6696                        }
6697                    } else if (result.size() <= 1 && !addEphemeral) {
6698                        // No result in parent user and <= 1 result in current profile, and we
6699                        // are not going to add emphemeral app, so we can return the result without
6700                        // further processing.
6701                        return applyPostResolutionFilter(result, instantAppPkgName,
6702                                allowDynamicSplits, filterCallingUid, userId);
6703                    }
6704                    // We have more than one candidate (combining results from current and parent
6705                    // profile), so we need filtering and sorting.
6706                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6707                            intent, flags, result, xpDomainInfo, userId);
6708                    sortResult = true;
6709                }
6710            } else {
6711                final PackageParser.Package pkg = mPackages.get(pkgName);
6712                result = null;
6713                if (pkg != null) {
6714                    result = filterIfNotSystemUser(
6715                            mActivities.queryIntentForPackage(
6716                                    intent, resolvedType, flags, pkg.activities, userId),
6717                            userId);
6718                }
6719                if (result == null || result.size() == 0) {
6720                    // the caller wants to resolve for a particular package; however, there
6721                    // were no installed results, so, try to find an ephemeral result
6722                    addEphemeral = !ephemeralDisabled
6723                            && isInstantAppAllowed(
6724                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6725                    if (result == null) {
6726                        result = new ArrayList<>();
6727                    }
6728                }
6729            }
6730        }
6731        if (addEphemeral) {
6732            result = maybeAddInstantAppInstaller(
6733                    result, intent, resolvedType, flags, userId, resolveForStart);
6734        }
6735        if (sortResult) {
6736            Collections.sort(result, mResolvePrioritySorter);
6737        }
6738        return applyPostResolutionFilter(
6739                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6740    }
6741
6742    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6743            String resolvedType, int flags, int userId, boolean resolveForStart) {
6744        // first, check to see if we've got an instant app already installed
6745        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6746        ResolveInfo localInstantApp = null;
6747        boolean blockResolution = false;
6748        if (!alreadyResolvedLocally) {
6749            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6750                    flags
6751                        | PackageManager.GET_RESOLVED_FILTER
6752                        | PackageManager.MATCH_INSTANT
6753                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6754                    userId);
6755            for (int i = instantApps.size() - 1; i >= 0; --i) {
6756                final ResolveInfo info = instantApps.get(i);
6757                final String packageName = info.activityInfo.packageName;
6758                final PackageSetting ps = mSettings.mPackages.get(packageName);
6759                if (ps.getInstantApp(userId)) {
6760                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6761                    final int status = (int)(packedStatus >> 32);
6762                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6763                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6764                        // there's a local instant application installed, but, the user has
6765                        // chosen to never use it; skip resolution and don't acknowledge
6766                        // an instant application is even available
6767                        if (DEBUG_EPHEMERAL) {
6768                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6769                        }
6770                        blockResolution = true;
6771                        break;
6772                    } else {
6773                        // we have a locally installed instant application; skip resolution
6774                        // but acknowledge there's an instant application available
6775                        if (DEBUG_EPHEMERAL) {
6776                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6777                        }
6778                        localInstantApp = info;
6779                        break;
6780                    }
6781                }
6782            }
6783        }
6784        // no app installed, let's see if one's available
6785        AuxiliaryResolveInfo auxiliaryResponse = null;
6786        if (!blockResolution) {
6787            if (localInstantApp == null) {
6788                // we don't have an instant app locally, resolve externally
6789                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6790                final InstantAppRequest requestObject = new InstantAppRequest(
6791                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6792                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6793                        resolveForStart);
6794                auxiliaryResponse =
6795                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6796                                mContext, mInstantAppResolverConnection, requestObject);
6797                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6798            } else {
6799                // we have an instant application locally, but, we can't admit that since
6800                // callers shouldn't be able to determine prior browsing. create a dummy
6801                // auxiliary response so the downstream code behaves as if there's an
6802                // instant application available externally. when it comes time to start
6803                // the instant application, we'll do the right thing.
6804                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6805                auxiliaryResponse = new AuxiliaryResolveInfo(
6806                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6807                        ai.versionCode, null /*failureIntent*/);
6808            }
6809        }
6810        if (auxiliaryResponse != null) {
6811            if (DEBUG_EPHEMERAL) {
6812                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6813            }
6814            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6815            final PackageSetting ps =
6816                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6817            if (ps != null) {
6818                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6819                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6820                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6821                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6822                // make sure this resolver is the default
6823                ephemeralInstaller.isDefault = true;
6824                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6825                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6826                // add a non-generic filter
6827                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6828                ephemeralInstaller.filter.addDataPath(
6829                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6830                ephemeralInstaller.isInstantAppAvailable = true;
6831                result.add(ephemeralInstaller);
6832            }
6833        }
6834        return result;
6835    }
6836
6837    private static class CrossProfileDomainInfo {
6838        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6839        ResolveInfo resolveInfo;
6840        /* Best domain verification status of the activities found in the other profile */
6841        int bestDomainVerificationStatus;
6842    }
6843
6844    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6845            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6846        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6847                sourceUserId)) {
6848            return null;
6849        }
6850        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6851                resolvedType, flags, parentUserId);
6852
6853        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6854            return null;
6855        }
6856        CrossProfileDomainInfo result = null;
6857        int size = resultTargetUser.size();
6858        for (int i = 0; i < size; i++) {
6859            ResolveInfo riTargetUser = resultTargetUser.get(i);
6860            // Intent filter verification is only for filters that specify a host. So don't return
6861            // those that handle all web uris.
6862            if (riTargetUser.handleAllWebDataURI) {
6863                continue;
6864            }
6865            String packageName = riTargetUser.activityInfo.packageName;
6866            PackageSetting ps = mSettings.mPackages.get(packageName);
6867            if (ps == null) {
6868                continue;
6869            }
6870            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6871            int status = (int)(verificationState >> 32);
6872            if (result == null) {
6873                result = new CrossProfileDomainInfo();
6874                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6875                        sourceUserId, parentUserId);
6876                result.bestDomainVerificationStatus = status;
6877            } else {
6878                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6879                        result.bestDomainVerificationStatus);
6880            }
6881        }
6882        // Don't consider matches with status NEVER across profiles.
6883        if (result != null && result.bestDomainVerificationStatus
6884                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6885            return null;
6886        }
6887        return result;
6888    }
6889
6890    /**
6891     * Verification statuses are ordered from the worse to the best, except for
6892     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6893     */
6894    private int bestDomainVerificationStatus(int status1, int status2) {
6895        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6896            return status2;
6897        }
6898        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6899            return status1;
6900        }
6901        return (int) MathUtils.max(status1, status2);
6902    }
6903
6904    private boolean isUserEnabled(int userId) {
6905        long callingId = Binder.clearCallingIdentity();
6906        try {
6907            UserInfo userInfo = sUserManager.getUserInfo(userId);
6908            return userInfo != null && userInfo.isEnabled();
6909        } finally {
6910            Binder.restoreCallingIdentity(callingId);
6911        }
6912    }
6913
6914    /**
6915     * Filter out activities with systemUserOnly flag set, when current user is not System.
6916     *
6917     * @return filtered list
6918     */
6919    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6920        if (userId == UserHandle.USER_SYSTEM) {
6921            return resolveInfos;
6922        }
6923        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6924            ResolveInfo info = resolveInfos.get(i);
6925            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6926                resolveInfos.remove(i);
6927            }
6928        }
6929        return resolveInfos;
6930    }
6931
6932    /**
6933     * Filters out ephemeral activities.
6934     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6935     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6936     *
6937     * @param resolveInfos The pre-filtered list of resolved activities
6938     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6939     *          is performed.
6940     * @return A filtered list of resolved activities.
6941     */
6942    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6943            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6944        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6945            final ResolveInfo info = resolveInfos.get(i);
6946            // allow activities that are defined in the provided package
6947            if (allowDynamicSplits
6948                    && info.activityInfo.splitName != null
6949                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6950                            info.activityInfo.splitName)) {
6951                // requested activity is defined in a split that hasn't been installed yet.
6952                // add the installer to the resolve list
6953                if (DEBUG_INSTALL) {
6954                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6955                }
6956                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6957                final ComponentName installFailureActivity = findInstallFailureActivity(
6958                        info.activityInfo.packageName,  filterCallingUid, userId);
6959                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6960                        info.activityInfo.packageName, info.activityInfo.splitName,
6961                        installFailureActivity,
6962                        info.activityInfo.applicationInfo.versionCode,
6963                        null /*failureIntent*/);
6964                // make sure this resolver is the default
6965                installerInfo.isDefault = true;
6966                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6967                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6968                // add a non-generic filter
6969                installerInfo.filter = new IntentFilter();
6970                // load resources from the correct package
6971                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6972                resolveInfos.set(i, installerInfo);
6973                continue;
6974            }
6975            // caller is a full app, don't need to apply any other filtering
6976            if (ephemeralPkgName == null) {
6977                continue;
6978            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6979                // caller is same app; don't need to apply any other filtering
6980                continue;
6981            }
6982            // allow activities that have been explicitly exposed to ephemeral apps
6983            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6984            if (!isEphemeralApp
6985                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6986                continue;
6987            }
6988            resolveInfos.remove(i);
6989        }
6990        return resolveInfos;
6991    }
6992
6993    /**
6994     * Returns the activity component that can handle install failures.
6995     * <p>By default, the instant application installer handles failures. However, an
6996     * application may want to handle failures on its own. Applications do this by
6997     * creating an activity with an intent filter that handles the action
6998     * {@link Intent#ACTION_INSTALL_FAILURE}.
6999     */
7000    private @Nullable ComponentName findInstallFailureActivity(
7001            String packageName, int filterCallingUid, int userId) {
7002        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7003        failureActivityIntent.setPackage(packageName);
7004        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7005        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7006                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7007                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7008        final int NR = result.size();
7009        if (NR > 0) {
7010            for (int i = 0; i < NR; i++) {
7011                final ResolveInfo info = result.get(i);
7012                if (info.activityInfo.splitName != null) {
7013                    continue;
7014                }
7015                return new ComponentName(packageName, info.activityInfo.name);
7016            }
7017        }
7018        return null;
7019    }
7020
7021    /**
7022     * @param resolveInfos list of resolve infos in descending priority order
7023     * @return if the list contains a resolve info with non-negative priority
7024     */
7025    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7026        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7027    }
7028
7029    private static boolean hasWebURI(Intent intent) {
7030        if (intent.getData() == null) {
7031            return false;
7032        }
7033        final String scheme = intent.getScheme();
7034        if (TextUtils.isEmpty(scheme)) {
7035            return false;
7036        }
7037        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7038    }
7039
7040    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7041            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7042            int userId) {
7043        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7044
7045        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7046            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7047                    candidates.size());
7048        }
7049
7050        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7051        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7052        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7053        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7054        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7055        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7056
7057        synchronized (mPackages) {
7058            final int count = candidates.size();
7059            // First, try to use linked apps. Partition the candidates into four lists:
7060            // one for the final results, one for the "do not use ever", one for "undefined status"
7061            // and finally one for "browser app type".
7062            for (int n=0; n<count; n++) {
7063                ResolveInfo info = candidates.get(n);
7064                String packageName = info.activityInfo.packageName;
7065                PackageSetting ps = mSettings.mPackages.get(packageName);
7066                if (ps != null) {
7067                    // Add to the special match all list (Browser use case)
7068                    if (info.handleAllWebDataURI) {
7069                        matchAllList.add(info);
7070                        continue;
7071                    }
7072                    // Try to get the status from User settings first
7073                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7074                    int status = (int)(packedStatus >> 32);
7075                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7076                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7077                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7078                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7079                                    + " : linkgen=" + linkGeneration);
7080                        }
7081                        // Use link-enabled generation as preferredOrder, i.e.
7082                        // prefer newly-enabled over earlier-enabled.
7083                        info.preferredOrder = linkGeneration;
7084                        alwaysList.add(info);
7085                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7086                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7087                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7088                        }
7089                        neverList.add(info);
7090                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7091                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7092                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7093                        }
7094                        alwaysAskList.add(info);
7095                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7096                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7097                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7098                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7099                        }
7100                        undefinedList.add(info);
7101                    }
7102                }
7103            }
7104
7105            // We'll want to include browser possibilities in a few cases
7106            boolean includeBrowser = false;
7107
7108            // First try to add the "always" resolution(s) for the current user, if any
7109            if (alwaysList.size() > 0) {
7110                result.addAll(alwaysList);
7111            } else {
7112                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7113                result.addAll(undefinedList);
7114                // Maybe add one for the other profile.
7115                if (xpDomainInfo != null && (
7116                        xpDomainInfo.bestDomainVerificationStatus
7117                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7118                    result.add(xpDomainInfo.resolveInfo);
7119                }
7120                includeBrowser = true;
7121            }
7122
7123            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7124            // If there were 'always' entries their preferred order has been set, so we also
7125            // back that off to make the alternatives equivalent
7126            if (alwaysAskList.size() > 0) {
7127                for (ResolveInfo i : result) {
7128                    i.preferredOrder = 0;
7129                }
7130                result.addAll(alwaysAskList);
7131                includeBrowser = true;
7132            }
7133
7134            if (includeBrowser) {
7135                // Also add browsers (all of them or only the default one)
7136                if (DEBUG_DOMAIN_VERIFICATION) {
7137                    Slog.v(TAG, "   ...including browsers in candidate set");
7138                }
7139                if ((matchFlags & MATCH_ALL) != 0) {
7140                    result.addAll(matchAllList);
7141                } else {
7142                    // Browser/generic handling case.  If there's a default browser, go straight
7143                    // to that (but only if there is no other higher-priority match).
7144                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7145                    int maxMatchPrio = 0;
7146                    ResolveInfo defaultBrowserMatch = null;
7147                    final int numCandidates = matchAllList.size();
7148                    for (int n = 0; n < numCandidates; n++) {
7149                        ResolveInfo info = matchAllList.get(n);
7150                        // track the highest overall match priority...
7151                        if (info.priority > maxMatchPrio) {
7152                            maxMatchPrio = info.priority;
7153                        }
7154                        // ...and the highest-priority default browser match
7155                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7156                            if (defaultBrowserMatch == null
7157                                    || (defaultBrowserMatch.priority < info.priority)) {
7158                                if (debug) {
7159                                    Slog.v(TAG, "Considering default browser match " + info);
7160                                }
7161                                defaultBrowserMatch = info;
7162                            }
7163                        }
7164                    }
7165                    if (defaultBrowserMatch != null
7166                            && defaultBrowserMatch.priority >= maxMatchPrio
7167                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7168                    {
7169                        if (debug) {
7170                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7171                        }
7172                        result.add(defaultBrowserMatch);
7173                    } else {
7174                        result.addAll(matchAllList);
7175                    }
7176                }
7177
7178                // If there is nothing selected, add all candidates and remove the ones that the user
7179                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7180                if (result.size() == 0) {
7181                    result.addAll(candidates);
7182                    result.removeAll(neverList);
7183                }
7184            }
7185        }
7186        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7187            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7188                    result.size());
7189            for (ResolveInfo info : result) {
7190                Slog.v(TAG, "  + " + info.activityInfo);
7191            }
7192        }
7193        return result;
7194    }
7195
7196    // Returns a packed value as a long:
7197    //
7198    // high 'int'-sized word: link status: undefined/ask/never/always.
7199    // low 'int'-sized word: relative priority among 'always' results.
7200    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7201        long result = ps.getDomainVerificationStatusForUser(userId);
7202        // if none available, get the master status
7203        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7204            if (ps.getIntentFilterVerificationInfo() != null) {
7205                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7206            }
7207        }
7208        return result;
7209    }
7210
7211    private ResolveInfo querySkipCurrentProfileIntents(
7212            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7213            int flags, int sourceUserId) {
7214        if (matchingFilters != null) {
7215            int size = matchingFilters.size();
7216            for (int i = 0; i < size; i ++) {
7217                CrossProfileIntentFilter filter = matchingFilters.get(i);
7218                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7219                    // Checking if there are activities in the target user that can handle the
7220                    // intent.
7221                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7222                            resolvedType, flags, sourceUserId);
7223                    if (resolveInfo != null) {
7224                        return resolveInfo;
7225                    }
7226                }
7227            }
7228        }
7229        return null;
7230    }
7231
7232    // Return matching ResolveInfo in target user if any.
7233    private ResolveInfo queryCrossProfileIntents(
7234            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7235            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7236        if (matchingFilters != null) {
7237            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7238            // match the same intent. For performance reasons, it is better not to
7239            // run queryIntent twice for the same userId
7240            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7241            int size = matchingFilters.size();
7242            for (int i = 0; i < size; i++) {
7243                CrossProfileIntentFilter filter = matchingFilters.get(i);
7244                int targetUserId = filter.getTargetUserId();
7245                boolean skipCurrentProfile =
7246                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7247                boolean skipCurrentProfileIfNoMatchFound =
7248                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7249                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7250                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7251                    // Checking if there are activities in the target user that can handle the
7252                    // intent.
7253                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7254                            resolvedType, flags, sourceUserId);
7255                    if (resolveInfo != null) return resolveInfo;
7256                    alreadyTriedUserIds.put(targetUserId, true);
7257                }
7258            }
7259        }
7260        return null;
7261    }
7262
7263    /**
7264     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7265     * will forward the intent to the filter's target user.
7266     * Otherwise, returns null.
7267     */
7268    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7269            String resolvedType, int flags, int sourceUserId) {
7270        int targetUserId = filter.getTargetUserId();
7271        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7272                resolvedType, flags, targetUserId);
7273        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7274            // If all the matches in the target profile are suspended, return null.
7275            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7276                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7277                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7278                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7279                            targetUserId);
7280                }
7281            }
7282        }
7283        return null;
7284    }
7285
7286    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7287            int sourceUserId, int targetUserId) {
7288        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7289        long ident = Binder.clearCallingIdentity();
7290        boolean targetIsProfile;
7291        try {
7292            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7293        } finally {
7294            Binder.restoreCallingIdentity(ident);
7295        }
7296        String className;
7297        if (targetIsProfile) {
7298            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7299        } else {
7300            className = FORWARD_INTENT_TO_PARENT;
7301        }
7302        ComponentName forwardingActivityComponentName = new ComponentName(
7303                mAndroidApplication.packageName, className);
7304        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7305                sourceUserId);
7306        if (!targetIsProfile) {
7307            forwardingActivityInfo.showUserIcon = targetUserId;
7308            forwardingResolveInfo.noResourceId = true;
7309        }
7310        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7311        forwardingResolveInfo.priority = 0;
7312        forwardingResolveInfo.preferredOrder = 0;
7313        forwardingResolveInfo.match = 0;
7314        forwardingResolveInfo.isDefault = true;
7315        forwardingResolveInfo.filter = filter;
7316        forwardingResolveInfo.targetUserId = targetUserId;
7317        return forwardingResolveInfo;
7318    }
7319
7320    @Override
7321    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7322            Intent[] specifics, String[] specificTypes, Intent intent,
7323            String resolvedType, int flags, int userId) {
7324        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7325                specificTypes, intent, resolvedType, flags, userId));
7326    }
7327
7328    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7329            Intent[] specifics, String[] specificTypes, Intent intent,
7330            String resolvedType, int flags, int userId) {
7331        if (!sUserManager.exists(userId)) return Collections.emptyList();
7332        final int callingUid = Binder.getCallingUid();
7333        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7334                false /*includeInstantApps*/);
7335        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7336                false /*requireFullPermission*/, false /*checkShell*/,
7337                "query intent activity options");
7338        final String resultsAction = intent.getAction();
7339
7340        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7341                | PackageManager.GET_RESOLVED_FILTER, userId);
7342
7343        if (DEBUG_INTENT_MATCHING) {
7344            Log.v(TAG, "Query " + intent + ": " + results);
7345        }
7346
7347        int specificsPos = 0;
7348        int N;
7349
7350        // todo: note that the algorithm used here is O(N^2).  This
7351        // isn't a problem in our current environment, but if we start running
7352        // into situations where we have more than 5 or 10 matches then this
7353        // should probably be changed to something smarter...
7354
7355        // First we go through and resolve each of the specific items
7356        // that were supplied, taking care of removing any corresponding
7357        // duplicate items in the generic resolve list.
7358        if (specifics != null) {
7359            for (int i=0; i<specifics.length; i++) {
7360                final Intent sintent = specifics[i];
7361                if (sintent == null) {
7362                    continue;
7363                }
7364
7365                if (DEBUG_INTENT_MATCHING) {
7366                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7367                }
7368
7369                String action = sintent.getAction();
7370                if (resultsAction != null && resultsAction.equals(action)) {
7371                    // If this action was explicitly requested, then don't
7372                    // remove things that have it.
7373                    action = null;
7374                }
7375
7376                ResolveInfo ri = null;
7377                ActivityInfo ai = null;
7378
7379                ComponentName comp = sintent.getComponent();
7380                if (comp == null) {
7381                    ri = resolveIntent(
7382                        sintent,
7383                        specificTypes != null ? specificTypes[i] : null,
7384                            flags, userId);
7385                    if (ri == null) {
7386                        continue;
7387                    }
7388                    if (ri == mResolveInfo) {
7389                        // ACK!  Must do something better with this.
7390                    }
7391                    ai = ri.activityInfo;
7392                    comp = new ComponentName(ai.applicationInfo.packageName,
7393                            ai.name);
7394                } else {
7395                    ai = getActivityInfo(comp, flags, userId);
7396                    if (ai == null) {
7397                        continue;
7398                    }
7399                }
7400
7401                // Look for any generic query activities that are duplicates
7402                // of this specific one, and remove them from the results.
7403                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7404                N = results.size();
7405                int j;
7406                for (j=specificsPos; j<N; j++) {
7407                    ResolveInfo sri = results.get(j);
7408                    if ((sri.activityInfo.name.equals(comp.getClassName())
7409                            && sri.activityInfo.applicationInfo.packageName.equals(
7410                                    comp.getPackageName()))
7411                        || (action != null && sri.filter.matchAction(action))) {
7412                        results.remove(j);
7413                        if (DEBUG_INTENT_MATCHING) Log.v(
7414                            TAG, "Removing duplicate item from " + j
7415                            + " due to specific " + specificsPos);
7416                        if (ri == null) {
7417                            ri = sri;
7418                        }
7419                        j--;
7420                        N--;
7421                    }
7422                }
7423
7424                // Add this specific item to its proper place.
7425                if (ri == null) {
7426                    ri = new ResolveInfo();
7427                    ri.activityInfo = ai;
7428                }
7429                results.add(specificsPos, ri);
7430                ri.specificIndex = i;
7431                specificsPos++;
7432            }
7433        }
7434
7435        // Now we go through the remaining generic results and remove any
7436        // duplicate actions that are found here.
7437        N = results.size();
7438        for (int i=specificsPos; i<N-1; i++) {
7439            final ResolveInfo rii = results.get(i);
7440            if (rii.filter == null) {
7441                continue;
7442            }
7443
7444            // Iterate over all of the actions of this result's intent
7445            // filter...  typically this should be just one.
7446            final Iterator<String> it = rii.filter.actionsIterator();
7447            if (it == null) {
7448                continue;
7449            }
7450            while (it.hasNext()) {
7451                final String action = it.next();
7452                if (resultsAction != null && resultsAction.equals(action)) {
7453                    // If this action was explicitly requested, then don't
7454                    // remove things that have it.
7455                    continue;
7456                }
7457                for (int j=i+1; j<N; j++) {
7458                    final ResolveInfo rij = results.get(j);
7459                    if (rij.filter != null && rij.filter.hasAction(action)) {
7460                        results.remove(j);
7461                        if (DEBUG_INTENT_MATCHING) Log.v(
7462                            TAG, "Removing duplicate item from " + j
7463                            + " due to action " + action + " at " + i);
7464                        j--;
7465                        N--;
7466                    }
7467                }
7468            }
7469
7470            // If the caller didn't request filter information, drop it now
7471            // so we don't have to marshall/unmarshall it.
7472            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7473                rii.filter = null;
7474            }
7475        }
7476
7477        // Filter out the caller activity if so requested.
7478        if (caller != null) {
7479            N = results.size();
7480            for (int i=0; i<N; i++) {
7481                ActivityInfo ainfo = results.get(i).activityInfo;
7482                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7483                        && caller.getClassName().equals(ainfo.name)) {
7484                    results.remove(i);
7485                    break;
7486                }
7487            }
7488        }
7489
7490        // If the caller didn't request filter information,
7491        // drop them now so we don't have to
7492        // marshall/unmarshall it.
7493        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7494            N = results.size();
7495            for (int i=0; i<N; i++) {
7496                results.get(i).filter = null;
7497            }
7498        }
7499
7500        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7501        return results;
7502    }
7503
7504    @Override
7505    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7506            String resolvedType, int flags, int userId) {
7507        return new ParceledListSlice<>(
7508                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7509                        false /*allowDynamicSplits*/));
7510    }
7511
7512    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7513            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7514        if (!sUserManager.exists(userId)) return Collections.emptyList();
7515        final int callingUid = Binder.getCallingUid();
7516        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7517                false /*requireFullPermission*/, false /*checkShell*/,
7518                "query intent receivers");
7519        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7520        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7521                false /*includeInstantApps*/);
7522        ComponentName comp = intent.getComponent();
7523        if (comp == null) {
7524            if (intent.getSelector() != null) {
7525                intent = intent.getSelector();
7526                comp = intent.getComponent();
7527            }
7528        }
7529        if (comp != null) {
7530            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7531            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7532            if (ai != null) {
7533                // When specifying an explicit component, we prevent the activity from being
7534                // used when either 1) the calling package is normal and the activity is within
7535                // an instant application or 2) the calling package is ephemeral and the
7536                // activity is not visible to instant applications.
7537                final boolean matchInstantApp =
7538                        (flags & PackageManager.MATCH_INSTANT) != 0;
7539                final boolean matchVisibleToInstantAppOnly =
7540                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7541                final boolean matchExplicitlyVisibleOnly =
7542                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7543                final boolean isCallerInstantApp =
7544                        instantAppPkgName != null;
7545                final boolean isTargetSameInstantApp =
7546                        comp.getPackageName().equals(instantAppPkgName);
7547                final boolean isTargetInstantApp =
7548                        (ai.applicationInfo.privateFlags
7549                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7550                final boolean isTargetVisibleToInstantApp =
7551                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7552                final boolean isTargetExplicitlyVisibleToInstantApp =
7553                        isTargetVisibleToInstantApp
7554                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7555                final boolean isTargetHiddenFromInstantApp =
7556                        !isTargetVisibleToInstantApp
7557                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7558                final boolean blockResolution =
7559                        !isTargetSameInstantApp
7560                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7561                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7562                                        && isTargetHiddenFromInstantApp));
7563                if (!blockResolution) {
7564                    ResolveInfo ri = new ResolveInfo();
7565                    ri.activityInfo = ai;
7566                    list.add(ri);
7567                }
7568            }
7569            return applyPostResolutionFilter(
7570                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7571        }
7572
7573        // reader
7574        synchronized (mPackages) {
7575            String pkgName = intent.getPackage();
7576            if (pkgName == null) {
7577                final List<ResolveInfo> result =
7578                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7579                return applyPostResolutionFilter(
7580                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7581            }
7582            final PackageParser.Package pkg = mPackages.get(pkgName);
7583            if (pkg != null) {
7584                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7585                        intent, resolvedType, flags, pkg.receivers, userId);
7586                return applyPostResolutionFilter(
7587                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7588            }
7589            return Collections.emptyList();
7590        }
7591    }
7592
7593    @Override
7594    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7595        final int callingUid = Binder.getCallingUid();
7596        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7597    }
7598
7599    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7600            int userId, int callingUid) {
7601        if (!sUserManager.exists(userId)) return null;
7602        flags = updateFlagsForResolve(
7603                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7604        List<ResolveInfo> query = queryIntentServicesInternal(
7605                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7606        if (query != null) {
7607            if (query.size() >= 1) {
7608                // If there is more than one service with the same priority,
7609                // just arbitrarily pick the first one.
7610                return query.get(0);
7611            }
7612        }
7613        return null;
7614    }
7615
7616    @Override
7617    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7618            String resolvedType, int flags, int userId) {
7619        final int callingUid = Binder.getCallingUid();
7620        return new ParceledListSlice<>(queryIntentServicesInternal(
7621                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7622    }
7623
7624    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7625            String resolvedType, int flags, int userId, int callingUid,
7626            boolean includeInstantApps) {
7627        if (!sUserManager.exists(userId)) return Collections.emptyList();
7628        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7629                false /*requireFullPermission*/, false /*checkShell*/,
7630                "query intent receivers");
7631        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7632        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7633        ComponentName comp = intent.getComponent();
7634        if (comp == null) {
7635            if (intent.getSelector() != null) {
7636                intent = intent.getSelector();
7637                comp = intent.getComponent();
7638            }
7639        }
7640        if (comp != null) {
7641            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7642            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7643            if (si != null) {
7644                // When specifying an explicit component, we prevent the service from being
7645                // used when either 1) the service is in an instant application and the
7646                // caller is not the same instant application or 2) the calling package is
7647                // ephemeral and the activity is not visible to ephemeral applications.
7648                final boolean matchInstantApp =
7649                        (flags & PackageManager.MATCH_INSTANT) != 0;
7650                final boolean matchVisibleToInstantAppOnly =
7651                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7652                final boolean isCallerInstantApp =
7653                        instantAppPkgName != null;
7654                final boolean isTargetSameInstantApp =
7655                        comp.getPackageName().equals(instantAppPkgName);
7656                final boolean isTargetInstantApp =
7657                        (si.applicationInfo.privateFlags
7658                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7659                final boolean isTargetHiddenFromInstantApp =
7660                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7661                final boolean blockResolution =
7662                        !isTargetSameInstantApp
7663                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7664                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7665                                        && isTargetHiddenFromInstantApp));
7666                if (!blockResolution) {
7667                    final ResolveInfo ri = new ResolveInfo();
7668                    ri.serviceInfo = si;
7669                    list.add(ri);
7670                }
7671            }
7672            return list;
7673        }
7674
7675        // reader
7676        synchronized (mPackages) {
7677            String pkgName = intent.getPackage();
7678            if (pkgName == null) {
7679                return applyPostServiceResolutionFilter(
7680                        mServices.queryIntent(intent, resolvedType, flags, userId),
7681                        instantAppPkgName);
7682            }
7683            final PackageParser.Package pkg = mPackages.get(pkgName);
7684            if (pkg != null) {
7685                return applyPostServiceResolutionFilter(
7686                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7687                                userId),
7688                        instantAppPkgName);
7689            }
7690            return Collections.emptyList();
7691        }
7692    }
7693
7694    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7695            String instantAppPkgName) {
7696        if (instantAppPkgName == null) {
7697            return resolveInfos;
7698        }
7699        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7700            final ResolveInfo info = resolveInfos.get(i);
7701            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7702            // allow services that are defined in the provided package
7703            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7704                if (info.serviceInfo.splitName != null
7705                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7706                                info.serviceInfo.splitName)) {
7707                    // requested service is defined in a split that hasn't been installed yet.
7708                    // add the installer to the resolve list
7709                    if (DEBUG_EPHEMERAL) {
7710                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7711                    }
7712                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7713                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7714                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7715                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7716                            null /*failureIntent*/);
7717                    // make sure this resolver is the default
7718                    installerInfo.isDefault = true;
7719                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7720                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7721                    // add a non-generic filter
7722                    installerInfo.filter = new IntentFilter();
7723                    // load resources from the correct package
7724                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7725                    resolveInfos.set(i, installerInfo);
7726                }
7727                continue;
7728            }
7729            // allow services that have been explicitly exposed to ephemeral apps
7730            if (!isEphemeralApp
7731                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7732                continue;
7733            }
7734            resolveInfos.remove(i);
7735        }
7736        return resolveInfos;
7737    }
7738
7739    @Override
7740    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7741            String resolvedType, int flags, int userId) {
7742        return new ParceledListSlice<>(
7743                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7744    }
7745
7746    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7747            Intent intent, String resolvedType, int flags, int userId) {
7748        if (!sUserManager.exists(userId)) return Collections.emptyList();
7749        final int callingUid = Binder.getCallingUid();
7750        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7751        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7752                false /*includeInstantApps*/);
7753        ComponentName comp = intent.getComponent();
7754        if (comp == null) {
7755            if (intent.getSelector() != null) {
7756                intent = intent.getSelector();
7757                comp = intent.getComponent();
7758            }
7759        }
7760        if (comp != null) {
7761            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7762            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7763            if (pi != null) {
7764                // When specifying an explicit component, we prevent the provider from being
7765                // used when either 1) the provider is in an instant application and the
7766                // caller is not the same instant application or 2) the calling package is an
7767                // instant application and the provider is not visible to instant applications.
7768                final boolean matchInstantApp =
7769                        (flags & PackageManager.MATCH_INSTANT) != 0;
7770                final boolean matchVisibleToInstantAppOnly =
7771                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7772                final boolean isCallerInstantApp =
7773                        instantAppPkgName != null;
7774                final boolean isTargetSameInstantApp =
7775                        comp.getPackageName().equals(instantAppPkgName);
7776                final boolean isTargetInstantApp =
7777                        (pi.applicationInfo.privateFlags
7778                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7779                final boolean isTargetHiddenFromInstantApp =
7780                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7781                final boolean blockResolution =
7782                        !isTargetSameInstantApp
7783                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7784                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7785                                        && isTargetHiddenFromInstantApp));
7786                if (!blockResolution) {
7787                    final ResolveInfo ri = new ResolveInfo();
7788                    ri.providerInfo = pi;
7789                    list.add(ri);
7790                }
7791            }
7792            return list;
7793        }
7794
7795        // reader
7796        synchronized (mPackages) {
7797            String pkgName = intent.getPackage();
7798            if (pkgName == null) {
7799                return applyPostContentProviderResolutionFilter(
7800                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7801                        instantAppPkgName);
7802            }
7803            final PackageParser.Package pkg = mPackages.get(pkgName);
7804            if (pkg != null) {
7805                return applyPostContentProviderResolutionFilter(
7806                        mProviders.queryIntentForPackage(
7807                        intent, resolvedType, flags, pkg.providers, userId),
7808                        instantAppPkgName);
7809            }
7810            return Collections.emptyList();
7811        }
7812    }
7813
7814    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7815            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7816        if (instantAppPkgName == null) {
7817            return resolveInfos;
7818        }
7819        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7820            final ResolveInfo info = resolveInfos.get(i);
7821            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7822            // allow providers that are defined in the provided package
7823            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7824                if (info.providerInfo.splitName != null
7825                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7826                                info.providerInfo.splitName)) {
7827                    // requested provider is defined in a split that hasn't been installed yet.
7828                    // add the installer to the resolve list
7829                    if (DEBUG_EPHEMERAL) {
7830                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7831                    }
7832                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7833                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7834                            info.providerInfo.packageName, info.providerInfo.splitName,
7835                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7836                            null /*failureIntent*/);
7837                    // make sure this resolver is the default
7838                    installerInfo.isDefault = true;
7839                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7840                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7841                    // add a non-generic filter
7842                    installerInfo.filter = new IntentFilter();
7843                    // load resources from the correct package
7844                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7845                    resolveInfos.set(i, installerInfo);
7846                }
7847                continue;
7848            }
7849            // allow providers that have been explicitly exposed to instant applications
7850            if (!isEphemeralApp
7851                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7852                continue;
7853            }
7854            resolveInfos.remove(i);
7855        }
7856        return resolveInfos;
7857    }
7858
7859    @Override
7860    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7861        final int callingUid = Binder.getCallingUid();
7862        if (getInstantAppPackageName(callingUid) != null) {
7863            return ParceledListSlice.emptyList();
7864        }
7865        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7866        flags = updateFlagsForPackage(flags, userId, null);
7867        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7868        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7869                true /* requireFullPermission */, false /* checkShell */,
7870                "get installed packages");
7871
7872        // writer
7873        synchronized (mPackages) {
7874            ArrayList<PackageInfo> list;
7875            if (listUninstalled) {
7876                list = new ArrayList<>(mSettings.mPackages.size());
7877                for (PackageSetting ps : mSettings.mPackages.values()) {
7878                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7879                        continue;
7880                    }
7881                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7882                        continue;
7883                    }
7884                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7885                    if (pi != null) {
7886                        list.add(pi);
7887                    }
7888                }
7889            } else {
7890                list = new ArrayList<>(mPackages.size());
7891                for (PackageParser.Package p : mPackages.values()) {
7892                    final PackageSetting ps = (PackageSetting) p.mExtras;
7893                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7894                        continue;
7895                    }
7896                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7897                        continue;
7898                    }
7899                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7900                            p.mExtras, flags, userId);
7901                    if (pi != null) {
7902                        list.add(pi);
7903                    }
7904                }
7905            }
7906
7907            return new ParceledListSlice<>(list);
7908        }
7909    }
7910
7911    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7912            String[] permissions, boolean[] tmp, int flags, int userId) {
7913        int numMatch = 0;
7914        final PermissionsState permissionsState = ps.getPermissionsState();
7915        for (int i=0; i<permissions.length; i++) {
7916            final String permission = permissions[i];
7917            if (permissionsState.hasPermission(permission, userId)) {
7918                tmp[i] = true;
7919                numMatch++;
7920            } else {
7921                tmp[i] = false;
7922            }
7923        }
7924        if (numMatch == 0) {
7925            return;
7926        }
7927        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7928
7929        // The above might return null in cases of uninstalled apps or install-state
7930        // skew across users/profiles.
7931        if (pi != null) {
7932            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7933                if (numMatch == permissions.length) {
7934                    pi.requestedPermissions = permissions;
7935                } else {
7936                    pi.requestedPermissions = new String[numMatch];
7937                    numMatch = 0;
7938                    for (int i=0; i<permissions.length; i++) {
7939                        if (tmp[i]) {
7940                            pi.requestedPermissions[numMatch] = permissions[i];
7941                            numMatch++;
7942                        }
7943                    }
7944                }
7945            }
7946            list.add(pi);
7947        }
7948    }
7949
7950    @Override
7951    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7952            String[] permissions, int flags, int userId) {
7953        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7954        flags = updateFlagsForPackage(flags, userId, permissions);
7955        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7956                true /* requireFullPermission */, false /* checkShell */,
7957                "get packages holding permissions");
7958        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7959
7960        // writer
7961        synchronized (mPackages) {
7962            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7963            boolean[] tmpBools = new boolean[permissions.length];
7964            if (listUninstalled) {
7965                for (PackageSetting ps : mSettings.mPackages.values()) {
7966                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7967                            userId);
7968                }
7969            } else {
7970                for (PackageParser.Package pkg : mPackages.values()) {
7971                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7972                    if (ps != null) {
7973                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7974                                userId);
7975                    }
7976                }
7977            }
7978
7979            return new ParceledListSlice<PackageInfo>(list);
7980        }
7981    }
7982
7983    @Override
7984    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7985        final int callingUid = Binder.getCallingUid();
7986        if (getInstantAppPackageName(callingUid) != null) {
7987            return ParceledListSlice.emptyList();
7988        }
7989        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7990        flags = updateFlagsForApplication(flags, userId, null);
7991        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7992
7993        // writer
7994        synchronized (mPackages) {
7995            ArrayList<ApplicationInfo> list;
7996            if (listUninstalled) {
7997                list = new ArrayList<>(mSettings.mPackages.size());
7998                for (PackageSetting ps : mSettings.mPackages.values()) {
7999                    ApplicationInfo ai;
8000                    int effectiveFlags = flags;
8001                    if (ps.isSystem()) {
8002                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8003                    }
8004                    if (ps.pkg != null) {
8005                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8006                            continue;
8007                        }
8008                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8009                            continue;
8010                        }
8011                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8012                                ps.readUserState(userId), userId);
8013                        if (ai != null) {
8014                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8015                        }
8016                    } else {
8017                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8018                        // and already converts to externally visible package name
8019                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8020                                callingUid, effectiveFlags, userId);
8021                    }
8022                    if (ai != null) {
8023                        list.add(ai);
8024                    }
8025                }
8026            } else {
8027                list = new ArrayList<>(mPackages.size());
8028                for (PackageParser.Package p : mPackages.values()) {
8029                    if (p.mExtras != null) {
8030                        PackageSetting ps = (PackageSetting) p.mExtras;
8031                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8032                            continue;
8033                        }
8034                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8035                            continue;
8036                        }
8037                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8038                                ps.readUserState(userId), userId);
8039                        if (ai != null) {
8040                            ai.packageName = resolveExternalPackageNameLPr(p);
8041                            list.add(ai);
8042                        }
8043                    }
8044                }
8045            }
8046
8047            return new ParceledListSlice<>(list);
8048        }
8049    }
8050
8051    @Override
8052    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8053        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8054            return null;
8055        }
8056        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8057            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8058                    "getEphemeralApplications");
8059        }
8060        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8061                true /* requireFullPermission */, false /* checkShell */,
8062                "getEphemeralApplications");
8063        synchronized (mPackages) {
8064            List<InstantAppInfo> instantApps = mInstantAppRegistry
8065                    .getInstantAppsLPr(userId);
8066            if (instantApps != null) {
8067                return new ParceledListSlice<>(instantApps);
8068            }
8069        }
8070        return null;
8071    }
8072
8073    @Override
8074    public boolean isInstantApp(String packageName, int userId) {
8075        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8076                true /* requireFullPermission */, false /* checkShell */,
8077                "isInstantApp");
8078        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8079            return false;
8080        }
8081
8082        synchronized (mPackages) {
8083            int callingUid = Binder.getCallingUid();
8084            if (Process.isIsolated(callingUid)) {
8085                callingUid = mIsolatedOwners.get(callingUid);
8086            }
8087            final PackageSetting ps = mSettings.mPackages.get(packageName);
8088            PackageParser.Package pkg = mPackages.get(packageName);
8089            final boolean returnAllowed =
8090                    ps != null
8091                    && (isCallerSameApp(packageName, callingUid)
8092                            || canViewInstantApps(callingUid, userId)
8093                            || mInstantAppRegistry.isInstantAccessGranted(
8094                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8095            if (returnAllowed) {
8096                return ps.getInstantApp(userId);
8097            }
8098        }
8099        return false;
8100    }
8101
8102    @Override
8103    public byte[] getInstantAppCookie(String packageName, int userId) {
8104        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8105            return null;
8106        }
8107
8108        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8109                true /* requireFullPermission */, false /* checkShell */,
8110                "getInstantAppCookie");
8111        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8112            return null;
8113        }
8114        synchronized (mPackages) {
8115            return mInstantAppRegistry.getInstantAppCookieLPw(
8116                    packageName, userId);
8117        }
8118    }
8119
8120    @Override
8121    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8122        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8123            return true;
8124        }
8125
8126        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8127                true /* requireFullPermission */, true /* checkShell */,
8128                "setInstantAppCookie");
8129        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8130            return false;
8131        }
8132        synchronized (mPackages) {
8133            return mInstantAppRegistry.setInstantAppCookieLPw(
8134                    packageName, cookie, userId);
8135        }
8136    }
8137
8138    @Override
8139    public Bitmap getInstantAppIcon(String packageName, int userId) {
8140        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8141            return null;
8142        }
8143
8144        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8145            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8146                    "getInstantAppIcon");
8147        }
8148        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8149                true /* requireFullPermission */, false /* checkShell */,
8150                "getInstantAppIcon");
8151
8152        synchronized (mPackages) {
8153            return mInstantAppRegistry.getInstantAppIconLPw(
8154                    packageName, userId);
8155        }
8156    }
8157
8158    private boolean isCallerSameApp(String packageName, int uid) {
8159        PackageParser.Package pkg = mPackages.get(packageName);
8160        return pkg != null
8161                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8162    }
8163
8164    @Override
8165    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8166        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8167            return ParceledListSlice.emptyList();
8168        }
8169        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8170    }
8171
8172    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8173        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8174
8175        // reader
8176        synchronized (mPackages) {
8177            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8178            final int userId = UserHandle.getCallingUserId();
8179            while (i.hasNext()) {
8180                final PackageParser.Package p = i.next();
8181                if (p.applicationInfo == null) continue;
8182
8183                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8184                        && !p.applicationInfo.isDirectBootAware();
8185                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8186                        && p.applicationInfo.isDirectBootAware();
8187
8188                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8189                        && (!mSafeMode || isSystemApp(p))
8190                        && (matchesUnaware || matchesAware)) {
8191                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8192                    if (ps != null) {
8193                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8194                                ps.readUserState(userId), userId);
8195                        if (ai != null) {
8196                            finalList.add(ai);
8197                        }
8198                    }
8199                }
8200            }
8201        }
8202
8203        return finalList;
8204    }
8205
8206    @Override
8207    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8208        return resolveContentProviderInternal(name, flags, userId);
8209    }
8210
8211    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8212        if (!sUserManager.exists(userId)) return null;
8213        flags = updateFlagsForComponent(flags, userId, name);
8214        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8215        // reader
8216        synchronized (mPackages) {
8217            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8218            PackageSetting ps = provider != null
8219                    ? mSettings.mPackages.get(provider.owner.packageName)
8220                    : null;
8221            if (ps != null) {
8222                final boolean isInstantApp = ps.getInstantApp(userId);
8223                // normal application; filter out instant application provider
8224                if (instantAppPkgName == null && isInstantApp) {
8225                    return null;
8226                }
8227                // instant application; filter out other instant applications
8228                if (instantAppPkgName != null
8229                        && isInstantApp
8230                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8231                    return null;
8232                }
8233                // instant application; filter out non-exposed provider
8234                if (instantAppPkgName != null
8235                        && !isInstantApp
8236                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8237                    return null;
8238                }
8239                // provider not enabled
8240                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8241                    return null;
8242                }
8243                return PackageParser.generateProviderInfo(
8244                        provider, flags, ps.readUserState(userId), userId);
8245            }
8246            return null;
8247        }
8248    }
8249
8250    /**
8251     * @deprecated
8252     */
8253    @Deprecated
8254    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8255        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8256            return;
8257        }
8258        // reader
8259        synchronized (mPackages) {
8260            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8261                    .entrySet().iterator();
8262            final int userId = UserHandle.getCallingUserId();
8263            while (i.hasNext()) {
8264                Map.Entry<String, PackageParser.Provider> entry = i.next();
8265                PackageParser.Provider p = entry.getValue();
8266                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8267
8268                if (ps != null && p.syncable
8269                        && (!mSafeMode || (p.info.applicationInfo.flags
8270                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8271                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8272                            ps.readUserState(userId), userId);
8273                    if (info != null) {
8274                        outNames.add(entry.getKey());
8275                        outInfo.add(info);
8276                    }
8277                }
8278            }
8279        }
8280    }
8281
8282    @Override
8283    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8284            int uid, int flags, String metaDataKey) {
8285        final int callingUid = Binder.getCallingUid();
8286        final int userId = processName != null ? UserHandle.getUserId(uid)
8287                : UserHandle.getCallingUserId();
8288        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8289        flags = updateFlagsForComponent(flags, userId, processName);
8290        ArrayList<ProviderInfo> finalList = null;
8291        // reader
8292        synchronized (mPackages) {
8293            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8294            while (i.hasNext()) {
8295                final PackageParser.Provider p = i.next();
8296                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8297                if (ps != null && p.info.authority != null
8298                        && (processName == null
8299                                || (p.info.processName.equals(processName)
8300                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8301                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8302
8303                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8304                    // parameter.
8305                    if (metaDataKey != null
8306                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8307                        continue;
8308                    }
8309                    final ComponentName component =
8310                            new ComponentName(p.info.packageName, p.info.name);
8311                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8312                        continue;
8313                    }
8314                    if (finalList == null) {
8315                        finalList = new ArrayList<ProviderInfo>(3);
8316                    }
8317                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8318                            ps.readUserState(userId), userId);
8319                    if (info != null) {
8320                        finalList.add(info);
8321                    }
8322                }
8323            }
8324        }
8325
8326        if (finalList != null) {
8327            Collections.sort(finalList, mProviderInitOrderSorter);
8328            return new ParceledListSlice<ProviderInfo>(finalList);
8329        }
8330
8331        return ParceledListSlice.emptyList();
8332    }
8333
8334    @Override
8335    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8336        // reader
8337        synchronized (mPackages) {
8338            final int callingUid = Binder.getCallingUid();
8339            final int callingUserId = UserHandle.getUserId(callingUid);
8340            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8341            if (ps == null) return null;
8342            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8343                return null;
8344            }
8345            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8346            return PackageParser.generateInstrumentationInfo(i, flags);
8347        }
8348    }
8349
8350    @Override
8351    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8352            String targetPackage, int flags) {
8353        final int callingUid = Binder.getCallingUid();
8354        final int callingUserId = UserHandle.getUserId(callingUid);
8355        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8356        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8357            return ParceledListSlice.emptyList();
8358        }
8359        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8360    }
8361
8362    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8363            int flags) {
8364        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8365
8366        // reader
8367        synchronized (mPackages) {
8368            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8369            while (i.hasNext()) {
8370                final PackageParser.Instrumentation p = i.next();
8371                if (targetPackage == null
8372                        || targetPackage.equals(p.info.targetPackage)) {
8373                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8374                            flags);
8375                    if (ii != null) {
8376                        finalList.add(ii);
8377                    }
8378                }
8379            }
8380        }
8381
8382        return finalList;
8383    }
8384
8385    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8386        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8387        try {
8388            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8389        } finally {
8390            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8391        }
8392    }
8393
8394    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8395        final File[] files = dir.listFiles();
8396        if (ArrayUtils.isEmpty(files)) {
8397            Log.d(TAG, "No files in app dir " + dir);
8398            return;
8399        }
8400
8401        if (DEBUG_PACKAGE_SCANNING) {
8402            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8403                    + " flags=0x" + Integer.toHexString(parseFlags));
8404        }
8405        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8406                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8407                mParallelPackageParserCallback);
8408
8409        // Submit files for parsing in parallel
8410        int fileCount = 0;
8411        for (File file : files) {
8412            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8413                    && !PackageInstallerService.isStageName(file.getName());
8414            if (!isPackage) {
8415                // Ignore entries which are not packages
8416                continue;
8417            }
8418            parallelPackageParser.submit(file, parseFlags);
8419            fileCount++;
8420        }
8421
8422        // Process results one by one
8423        for (; fileCount > 0; fileCount--) {
8424            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8425            Throwable throwable = parseResult.throwable;
8426            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8427
8428            if (throwable == null) {
8429                // Static shared libraries have synthetic package names
8430                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8431                    renameStaticSharedLibraryPackage(parseResult.pkg);
8432                }
8433                try {
8434                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8435                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8436                                currentTime, null);
8437                    }
8438                } catch (PackageManagerException e) {
8439                    errorCode = e.error;
8440                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8441                }
8442            } else if (throwable instanceof PackageParser.PackageParserException) {
8443                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8444                        throwable;
8445                errorCode = e.error;
8446                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8447            } else {
8448                throw new IllegalStateException("Unexpected exception occurred while parsing "
8449                        + parseResult.scanFile, throwable);
8450            }
8451
8452            // Delete invalid userdata apps
8453            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8454                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8455                logCriticalInfo(Log.WARN,
8456                        "Deleting invalid package at " + parseResult.scanFile);
8457                removeCodePathLI(parseResult.scanFile);
8458            }
8459        }
8460        parallelPackageParser.close();
8461    }
8462
8463    private static File getSettingsProblemFile() {
8464        File dataDir = Environment.getDataDirectory();
8465        File systemDir = new File(dataDir, "system");
8466        File fname = new File(systemDir, "uiderrors.txt");
8467        return fname;
8468    }
8469
8470    public static void reportSettingsProblem(int priority, String msg) {
8471        logCriticalInfo(priority, msg);
8472    }
8473
8474    public static void logCriticalInfo(int priority, String msg) {
8475        Slog.println(priority, TAG, msg);
8476        EventLogTags.writePmCriticalInfo(msg);
8477        try {
8478            File fname = getSettingsProblemFile();
8479            FileOutputStream out = new FileOutputStream(fname, true);
8480            PrintWriter pw = new FastPrintWriter(out);
8481            SimpleDateFormat formatter = new SimpleDateFormat();
8482            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8483            pw.println(dateString + ": " + msg);
8484            pw.close();
8485            FileUtils.setPermissions(
8486                    fname.toString(),
8487                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8488                    -1, -1);
8489        } catch (java.io.IOException e) {
8490        }
8491    }
8492
8493    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8494        if (srcFile.isDirectory()) {
8495            final File baseFile = new File(pkg.baseCodePath);
8496            long maxModifiedTime = baseFile.lastModified();
8497            if (pkg.splitCodePaths != null) {
8498                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8499                    final File splitFile = new File(pkg.splitCodePaths[i]);
8500                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8501                }
8502            }
8503            return maxModifiedTime;
8504        }
8505        return srcFile.lastModified();
8506    }
8507
8508    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8509            final int policyFlags) throws PackageManagerException {
8510        // When upgrading from pre-N MR1, verify the package time stamp using the package
8511        // directory and not the APK file.
8512        final long lastModifiedTime = mIsPreNMR1Upgrade
8513                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8514        if (ps != null
8515                && ps.codePath.equals(srcFile)
8516                && ps.timeStamp == lastModifiedTime
8517                && !isCompatSignatureUpdateNeeded(pkg)
8518                && !isRecoverSignatureUpdateNeeded(pkg)) {
8519            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8520            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8521            ArraySet<PublicKey> signingKs;
8522            synchronized (mPackages) {
8523                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8524            }
8525            if (ps.signatures.mSignatures != null
8526                    && ps.signatures.mSignatures.length != 0
8527                    && signingKs != null) {
8528                // Optimization: reuse the existing cached certificates
8529                // if the package appears to be unchanged.
8530                pkg.mSignatures = ps.signatures.mSignatures;
8531                pkg.mSigningKeys = signingKs;
8532                return;
8533            }
8534
8535            Slog.w(TAG, "PackageSetting for " + ps.name
8536                    + " is missing signatures.  Collecting certs again to recover them.");
8537        } else {
8538            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8539        }
8540
8541        try {
8542            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8543            PackageParser.collectCertificates(pkg, policyFlags);
8544        } catch (PackageParserException e) {
8545            throw PackageManagerException.from(e);
8546        } finally {
8547            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8548        }
8549    }
8550
8551    /**
8552     *  Traces a package scan.
8553     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8554     */
8555    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8556            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8557        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8558        try {
8559            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8560        } finally {
8561            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8562        }
8563    }
8564
8565    /**
8566     *  Scans a package and returns the newly parsed package.
8567     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8568     */
8569    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8570            long currentTime, UserHandle user) throws PackageManagerException {
8571        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8572        PackageParser pp = new PackageParser();
8573        pp.setSeparateProcesses(mSeparateProcesses);
8574        pp.setOnlyCoreApps(mOnlyCore);
8575        pp.setDisplayMetrics(mMetrics);
8576        pp.setCallback(mPackageParserCallback);
8577
8578        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8579            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8580        }
8581
8582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8583        final PackageParser.Package pkg;
8584        try {
8585            pkg = pp.parsePackage(scanFile, parseFlags);
8586        } catch (PackageParserException e) {
8587            throw PackageManagerException.from(e);
8588        } finally {
8589            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8590        }
8591
8592        // Static shared libraries have synthetic package names
8593        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8594            renameStaticSharedLibraryPackage(pkg);
8595        }
8596
8597        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8598    }
8599
8600    /**
8601     *  Scans a package and returns the newly parsed package.
8602     *  @throws PackageManagerException on a parse error.
8603     */
8604    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8605            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8606            throws PackageManagerException {
8607        // If the package has children and this is the first dive in the function
8608        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8609        // packages (parent and children) would be successfully scanned before the
8610        // actual scan since scanning mutates internal state and we want to atomically
8611        // install the package and its children.
8612        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8613            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8614                scanFlags |= SCAN_CHECK_ONLY;
8615            }
8616        } else {
8617            scanFlags &= ~SCAN_CHECK_ONLY;
8618        }
8619
8620        // Scan the parent
8621        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8622                scanFlags, currentTime, user);
8623
8624        // Scan the children
8625        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8626        for (int i = 0; i < childCount; i++) {
8627            PackageParser.Package childPackage = pkg.childPackages.get(i);
8628            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8629                    currentTime, user);
8630        }
8631
8632
8633        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8634            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8635        }
8636
8637        return scannedPkg;
8638    }
8639
8640    /**
8641     *  Scans a package and returns the newly parsed package.
8642     *  @throws PackageManagerException on a parse error.
8643     */
8644    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8645            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8646            throws PackageManagerException {
8647        PackageSetting ps = null;
8648        PackageSetting updatedPkg;
8649        // reader
8650        synchronized (mPackages) {
8651            // Look to see if we already know about this package.
8652            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8653            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8654                // This package has been renamed to its original name.  Let's
8655                // use that.
8656                ps = mSettings.getPackageLPr(oldName);
8657            }
8658            // If there was no original package, see one for the real package name.
8659            if (ps == null) {
8660                ps = mSettings.getPackageLPr(pkg.packageName);
8661            }
8662            // Check to see if this package could be hiding/updating a system
8663            // package.  Must look for it either under the original or real
8664            // package name depending on our state.
8665            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8666            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8667
8668            // If this is a package we don't know about on the system partition, we
8669            // may need to remove disabled child packages on the system partition
8670            // or may need to not add child packages if the parent apk is updated
8671            // on the data partition and no longer defines this child package.
8672            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8673                // If this is a parent package for an updated system app and this system
8674                // app got an OTA update which no longer defines some of the child packages
8675                // we have to prune them from the disabled system packages.
8676                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8677                if (disabledPs != null) {
8678                    final int scannedChildCount = (pkg.childPackages != null)
8679                            ? pkg.childPackages.size() : 0;
8680                    final int disabledChildCount = disabledPs.childPackageNames != null
8681                            ? disabledPs.childPackageNames.size() : 0;
8682                    for (int i = 0; i < disabledChildCount; i++) {
8683                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8684                        boolean disabledPackageAvailable = false;
8685                        for (int j = 0; j < scannedChildCount; j++) {
8686                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8687                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8688                                disabledPackageAvailable = true;
8689                                break;
8690                            }
8691                         }
8692                         if (!disabledPackageAvailable) {
8693                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8694                         }
8695                    }
8696                }
8697            }
8698        }
8699
8700        final boolean isUpdatedPkg = updatedPkg != null;
8701        final boolean isUpdatedSystemPkg = isUpdatedPkg
8702                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8703        boolean isUpdatedPkgBetter = false;
8704        // First check if this is a system package that may involve an update
8705        if (isUpdatedSystemPkg) {
8706            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8707            // it needs to drop FLAG_PRIVILEGED.
8708            if (locationIsPrivileged(scanFile)) {
8709                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8710            } else {
8711                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8712            }
8713            // If new package is not located in "/oem" (e.g. due to an OTA),
8714            // it needs to drop FLAG_OEM.
8715            if (locationIsOem(scanFile)) {
8716                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8717            } else {
8718                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8719            }
8720
8721            if (ps != null && !ps.codePath.equals(scanFile)) {
8722                // The path has changed from what was last scanned...  check the
8723                // version of the new path against what we have stored to determine
8724                // what to do.
8725                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8726                if (pkg.mVersionCode <= ps.versionCode) {
8727                    // The system package has been updated and the code path does not match
8728                    // Ignore entry. Skip it.
8729                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8730                            + " ignored: updated version " + ps.versionCode
8731                            + " better than this " + pkg.mVersionCode);
8732                    if (!updatedPkg.codePath.equals(scanFile)) {
8733                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8734                                + ps.name + " changing from " + updatedPkg.codePathString
8735                                + " to " + scanFile);
8736                        updatedPkg.codePath = scanFile;
8737                        updatedPkg.codePathString = scanFile.toString();
8738                        updatedPkg.resourcePath = scanFile;
8739                        updatedPkg.resourcePathString = scanFile.toString();
8740                    }
8741                    updatedPkg.pkg = pkg;
8742                    updatedPkg.versionCode = pkg.mVersionCode;
8743
8744                    // Update the disabled system child packages to point to the package too.
8745                    final int childCount = updatedPkg.childPackageNames != null
8746                            ? updatedPkg.childPackageNames.size() : 0;
8747                    for (int i = 0; i < childCount; i++) {
8748                        String childPackageName = updatedPkg.childPackageNames.get(i);
8749                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8750                                childPackageName);
8751                        if (updatedChildPkg != null) {
8752                            updatedChildPkg.pkg = pkg;
8753                            updatedChildPkg.versionCode = pkg.mVersionCode;
8754                        }
8755                    }
8756                } else {
8757                    // The current app on the system partition is better than
8758                    // what we have updated to on the data partition; switch
8759                    // back to the system partition version.
8760                    // At this point, its safely assumed that package installation for
8761                    // apps in system partition will go through. If not there won't be a working
8762                    // version of the app
8763                    // writer
8764                    synchronized (mPackages) {
8765                        // Just remove the loaded entries from package lists.
8766                        mPackages.remove(ps.name);
8767                    }
8768
8769                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8770                            + " reverting from " + ps.codePathString
8771                            + ": new version " + pkg.mVersionCode
8772                            + " better than installed " + ps.versionCode);
8773
8774                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8775                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8776                    synchronized (mInstallLock) {
8777                        args.cleanUpResourcesLI();
8778                    }
8779                    synchronized (mPackages) {
8780                        mSettings.enableSystemPackageLPw(ps.name);
8781                    }
8782                    isUpdatedPkgBetter = true;
8783                }
8784            }
8785        }
8786
8787        String resourcePath = null;
8788        String baseResourcePath = null;
8789        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8790            if (ps != null && ps.resourcePathString != null) {
8791                resourcePath = ps.resourcePathString;
8792                baseResourcePath = ps.resourcePathString;
8793            } else {
8794                // Should not happen at all. Just log an error.
8795                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8796            }
8797        } else {
8798            resourcePath = pkg.codePath;
8799            baseResourcePath = pkg.baseCodePath;
8800        }
8801
8802        // Set application objects path explicitly.
8803        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8804        pkg.setApplicationInfoCodePath(pkg.codePath);
8805        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8806        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8807        pkg.setApplicationInfoResourcePath(resourcePath);
8808        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8809        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8810
8811        // throw an exception if we have an update to a system application, but, it's not more
8812        // recent than the package we've already scanned
8813        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8814            // Set CPU Abis to application info.
8815            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8816                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8817                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8818            } else {
8819                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8820                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8821            }
8822
8823            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8824                    + scanFile + " ignored: updated version " + ps.versionCode
8825                    + " better than this " + pkg.mVersionCode);
8826        }
8827
8828        if (isUpdatedPkg) {
8829            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8830            // initially
8831            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8832
8833            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8834            // flag set initially
8835            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8836                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8837            }
8838
8839            // An updated OEM app will not have the PARSE_IS_OEM
8840            // flag set initially
8841            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8842                policyFlags |= PackageParser.PARSE_IS_OEM;
8843            }
8844        }
8845
8846        // Verify certificates against what was last scanned
8847        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8848
8849        /*
8850         * A new system app appeared, but we already had a non-system one of the
8851         * same name installed earlier.
8852         */
8853        boolean shouldHideSystemApp = false;
8854        if (!isUpdatedPkg && ps != null
8855                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8856            /*
8857             * Check to make sure the signatures match first. If they don't,
8858             * wipe the installed application and its data.
8859             */
8860            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8861                    != PackageManager.SIGNATURE_MATCH) {
8862                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8863                        + " signatures don't match existing userdata copy; removing");
8864                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8865                        "scanPackageInternalLI")) {
8866                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8867                }
8868                ps = null;
8869            } else {
8870                /*
8871                 * If the newly-added system app is an older version than the
8872                 * already installed version, hide it. It will be scanned later
8873                 * and re-added like an update.
8874                 */
8875                if (pkg.mVersionCode <= ps.versionCode) {
8876                    shouldHideSystemApp = true;
8877                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8878                            + " but new version " + pkg.mVersionCode + " better than installed "
8879                            + ps.versionCode + "; hiding system");
8880                } else {
8881                    /*
8882                     * The newly found system app is a newer version that the
8883                     * one previously installed. Simply remove the
8884                     * already-installed application and replace it with our own
8885                     * while keeping the application data.
8886                     */
8887                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8888                            + " reverting from " + ps.codePathString + ": new version "
8889                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8890                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8891                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8892                    synchronized (mInstallLock) {
8893                        args.cleanUpResourcesLI();
8894                    }
8895                }
8896            }
8897        }
8898
8899        // The apk is forward locked (not public) if its code and resources
8900        // are kept in different files. (except for app in either system or
8901        // vendor path).
8902        // TODO grab this value from PackageSettings
8903        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8904            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8905                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8906            }
8907        }
8908
8909        final int userId = ((user == null) ? 0 : user.getIdentifier());
8910        if (ps != null && ps.getInstantApp(userId)) {
8911            scanFlags |= SCAN_AS_INSTANT_APP;
8912        }
8913        if (ps != null && ps.getVirtulalPreload(userId)) {
8914            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8915        }
8916
8917        // Note that we invoke the following method only if we are about to unpack an application
8918        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8919                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8920
8921        /*
8922         * If the system app should be overridden by a previously installed
8923         * data, hide the system app now and let the /data/app scan pick it up
8924         * again.
8925         */
8926        if (shouldHideSystemApp) {
8927            synchronized (mPackages) {
8928                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8929            }
8930        }
8931
8932        return scannedPkg;
8933    }
8934
8935    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8936        // Derive the new package synthetic package name
8937        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8938                + pkg.staticSharedLibVersion);
8939    }
8940
8941    private static String fixProcessName(String defProcessName,
8942            String processName) {
8943        if (processName == null) {
8944            return defProcessName;
8945        }
8946        return processName;
8947    }
8948
8949    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8950            throws PackageManagerException {
8951        if (pkgSetting.signatures.mSignatures != null) {
8952            // Already existing package. Make sure signatures match
8953            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8954                    == PackageManager.SIGNATURE_MATCH;
8955            if (!match) {
8956                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8957                        == PackageManager.SIGNATURE_MATCH;
8958            }
8959            if (!match) {
8960                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8961                        == PackageManager.SIGNATURE_MATCH;
8962            }
8963            if (!match) {
8964                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8965                        + pkg.packageName + " signatures do not match the "
8966                        + "previously installed version; ignoring!");
8967            }
8968        }
8969
8970        // Check for shared user signatures
8971        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8972            // Already existing package. Make sure signatures match
8973            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8974                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8975            if (!match) {
8976                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8977                        == PackageManager.SIGNATURE_MATCH;
8978            }
8979            if (!match) {
8980                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8981                        == PackageManager.SIGNATURE_MATCH;
8982            }
8983            if (!match) {
8984                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8985                        "Package " + pkg.packageName
8986                        + " has no signatures that match those in shared user "
8987                        + pkgSetting.sharedUser.name + "; ignoring!");
8988            }
8989        }
8990    }
8991
8992    /**
8993     * Enforces that only the system UID or root's UID can call a method exposed
8994     * via Binder.
8995     *
8996     * @param message used as message if SecurityException is thrown
8997     * @throws SecurityException if the caller is not system or root
8998     */
8999    private static final void enforceSystemOrRoot(String message) {
9000        final int uid = Binder.getCallingUid();
9001        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9002            throw new SecurityException(message);
9003        }
9004    }
9005
9006    @Override
9007    public void performFstrimIfNeeded() {
9008        enforceSystemOrRoot("Only the system can request fstrim");
9009
9010        // Before everything else, see whether we need to fstrim.
9011        try {
9012            IStorageManager sm = PackageHelper.getStorageManager();
9013            if (sm != null) {
9014                boolean doTrim = false;
9015                final long interval = android.provider.Settings.Global.getLong(
9016                        mContext.getContentResolver(),
9017                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9018                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9019                if (interval > 0) {
9020                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9021                    if (timeSinceLast > interval) {
9022                        doTrim = true;
9023                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9024                                + "; running immediately");
9025                    }
9026                }
9027                if (doTrim) {
9028                    final boolean dexOptDialogShown;
9029                    synchronized (mPackages) {
9030                        dexOptDialogShown = mDexOptDialogShown;
9031                    }
9032                    if (!isFirstBoot() && dexOptDialogShown) {
9033                        try {
9034                            ActivityManager.getService().showBootMessage(
9035                                    mContext.getResources().getString(
9036                                            R.string.android_upgrading_fstrim), true);
9037                        } catch (RemoteException e) {
9038                        }
9039                    }
9040                    sm.runMaintenance();
9041                }
9042            } else {
9043                Slog.e(TAG, "storageManager service unavailable!");
9044            }
9045        } catch (RemoteException e) {
9046            // Can't happen; StorageManagerService is local
9047        }
9048    }
9049
9050    @Override
9051    public void updatePackagesIfNeeded() {
9052        enforceSystemOrRoot("Only the system can request package update");
9053
9054        // We need to re-extract after an OTA.
9055        boolean causeUpgrade = isUpgrade();
9056
9057        // First boot or factory reset.
9058        // Note: we also handle devices that are upgrading to N right now as if it is their
9059        //       first boot, as they do not have profile data.
9060        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9061
9062        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9063        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9064
9065        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9066            return;
9067        }
9068
9069        List<PackageParser.Package> pkgs;
9070        synchronized (mPackages) {
9071            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9072        }
9073
9074        final long startTime = System.nanoTime();
9075        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9076                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9077                    false /* bootComplete */);
9078
9079        final int elapsedTimeSeconds =
9080                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9081
9082        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9083        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9084        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9085        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9086        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9087    }
9088
9089    /*
9090     * Return the prebuilt profile path given a package base code path.
9091     */
9092    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9093        return pkg.baseCodePath + ".prof";
9094    }
9095
9096    /**
9097     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9098     * containing statistics about the invocation. The array consists of three elements,
9099     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9100     * and {@code numberOfPackagesFailed}.
9101     */
9102    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9103            String compilerFilter, boolean bootComplete) {
9104
9105        int numberOfPackagesVisited = 0;
9106        int numberOfPackagesOptimized = 0;
9107        int numberOfPackagesSkipped = 0;
9108        int numberOfPackagesFailed = 0;
9109        final int numberOfPackagesToDexopt = pkgs.size();
9110
9111        for (PackageParser.Package pkg : pkgs) {
9112            numberOfPackagesVisited++;
9113
9114            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9115                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9116                // that are already compiled.
9117                File profileFile = new File(getPrebuildProfilePath(pkg));
9118                // Copy profile if it exists.
9119                if (profileFile.exists()) {
9120                    try {
9121                        // We could also do this lazily before calling dexopt in
9122                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9123                        // is that we don't have a good way to say "do this only once".
9124                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9125                                pkg.applicationInfo.uid, pkg.packageName)) {
9126                            Log.e(TAG, "Installer failed to copy system profile!");
9127                        }
9128                    } catch (Exception e) {
9129                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9130                                e);
9131                    }
9132                }
9133            }
9134
9135            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9136                if (DEBUG_DEXOPT) {
9137                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9138                }
9139                numberOfPackagesSkipped++;
9140                continue;
9141            }
9142
9143            if (DEBUG_DEXOPT) {
9144                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9145                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9146            }
9147
9148            if (showDialog) {
9149                try {
9150                    ActivityManager.getService().showBootMessage(
9151                            mContext.getResources().getString(R.string.android_upgrading_apk,
9152                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9153                } catch (RemoteException e) {
9154                }
9155                synchronized (mPackages) {
9156                    mDexOptDialogShown = true;
9157                }
9158            }
9159
9160            // If the OTA updates a system app which was previously preopted to a non-preopted state
9161            // the app might end up being verified at runtime. That's because by default the apps
9162            // are verify-profile but for preopted apps there's no profile.
9163            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9164            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9165            // filter (by default 'quicken').
9166            // Note that at this stage unused apps are already filtered.
9167            if (isSystemApp(pkg) &&
9168                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9169                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9170                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9171            }
9172
9173            // checkProfiles is false to avoid merging profiles during boot which
9174            // might interfere with background compilation (b/28612421).
9175            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9176            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9177            // trade-off worth doing to save boot time work.
9178            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9179            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9180                    pkg.packageName,
9181                    compilerFilter,
9182                    dexoptFlags));
9183
9184            switch (primaryDexOptStaus) {
9185                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9186                    numberOfPackagesOptimized++;
9187                    break;
9188                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9189                    numberOfPackagesSkipped++;
9190                    break;
9191                case PackageDexOptimizer.DEX_OPT_FAILED:
9192                    numberOfPackagesFailed++;
9193                    break;
9194                default:
9195                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9196                    break;
9197            }
9198        }
9199
9200        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9201                numberOfPackagesFailed };
9202    }
9203
9204    @Override
9205    public void notifyPackageUse(String packageName, int reason) {
9206        synchronized (mPackages) {
9207            final int callingUid = Binder.getCallingUid();
9208            final int callingUserId = UserHandle.getUserId(callingUid);
9209            if (getInstantAppPackageName(callingUid) != null) {
9210                if (!isCallerSameApp(packageName, callingUid)) {
9211                    return;
9212                }
9213            } else {
9214                if (isInstantApp(packageName, callingUserId)) {
9215                    return;
9216                }
9217            }
9218            notifyPackageUseLocked(packageName, reason);
9219        }
9220    }
9221
9222    private void notifyPackageUseLocked(String packageName, int reason) {
9223        final PackageParser.Package p = mPackages.get(packageName);
9224        if (p == null) {
9225            return;
9226        }
9227        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9228    }
9229
9230    @Override
9231    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9232            List<String> classPaths, String loaderIsa) {
9233        int userId = UserHandle.getCallingUserId();
9234        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9235        if (ai == null) {
9236            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9237                + loadingPackageName + ", user=" + userId);
9238            return;
9239        }
9240        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9241    }
9242
9243    @Override
9244    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9245            IDexModuleRegisterCallback callback) {
9246        int userId = UserHandle.getCallingUserId();
9247        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9248        DexManager.RegisterDexModuleResult result;
9249        if (ai == null) {
9250            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9251                     " calling user. package=" + packageName + ", user=" + userId);
9252            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9253        } else {
9254            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9255        }
9256
9257        if (callback != null) {
9258            mHandler.post(() -> {
9259                try {
9260                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9261                } catch (RemoteException e) {
9262                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9263                }
9264            });
9265        }
9266    }
9267
9268    /**
9269     * Ask the package manager to perform a dex-opt with the given compiler filter.
9270     *
9271     * Note: exposed only for the shell command to allow moving packages explicitly to a
9272     *       definite state.
9273     */
9274    @Override
9275    public boolean performDexOptMode(String packageName,
9276            boolean checkProfiles, String targetCompilerFilter, boolean force,
9277            boolean bootComplete, String splitName) {
9278        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9279                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9280                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9281        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9282                splitName, flags));
9283    }
9284
9285    /**
9286     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9287     * secondary dex files belonging to the given package.
9288     *
9289     * Note: exposed only for the shell command to allow moving packages explicitly to a
9290     *       definite state.
9291     */
9292    @Override
9293    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9294            boolean force) {
9295        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9296                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9297                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9298                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9299        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9300    }
9301
9302    /*package*/ boolean performDexOpt(DexoptOptions options) {
9303        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9304            return false;
9305        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9306            return false;
9307        }
9308
9309        if (options.isDexoptOnlySecondaryDex()) {
9310            return mDexManager.dexoptSecondaryDex(options);
9311        } else {
9312            int dexoptStatus = performDexOptWithStatus(options);
9313            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9314        }
9315    }
9316
9317    /**
9318     * Perform dexopt on the given package and return one of following result:
9319     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9320     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9321     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9322     */
9323    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9324        return performDexOptTraced(options);
9325    }
9326
9327    private int performDexOptTraced(DexoptOptions options) {
9328        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9329        try {
9330            return performDexOptInternal(options);
9331        } finally {
9332            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9333        }
9334    }
9335
9336    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9337    // if the package can now be considered up to date for the given filter.
9338    private int performDexOptInternal(DexoptOptions options) {
9339        PackageParser.Package p;
9340        synchronized (mPackages) {
9341            p = mPackages.get(options.getPackageName());
9342            if (p == null) {
9343                // Package could not be found. Report failure.
9344                return PackageDexOptimizer.DEX_OPT_FAILED;
9345            }
9346            mPackageUsage.maybeWriteAsync(mPackages);
9347            mCompilerStats.maybeWriteAsync();
9348        }
9349        long callingId = Binder.clearCallingIdentity();
9350        try {
9351            synchronized (mInstallLock) {
9352                return performDexOptInternalWithDependenciesLI(p, options);
9353            }
9354        } finally {
9355            Binder.restoreCallingIdentity(callingId);
9356        }
9357    }
9358
9359    public ArraySet<String> getOptimizablePackages() {
9360        ArraySet<String> pkgs = new ArraySet<String>();
9361        synchronized (mPackages) {
9362            for (PackageParser.Package p : mPackages.values()) {
9363                if (PackageDexOptimizer.canOptimizePackage(p)) {
9364                    pkgs.add(p.packageName);
9365                }
9366            }
9367        }
9368        return pkgs;
9369    }
9370
9371    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9372            DexoptOptions options) {
9373        // Select the dex optimizer based on the force parameter.
9374        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9375        //       allocate an object here.
9376        PackageDexOptimizer pdo = options.isForce()
9377                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9378                : mPackageDexOptimizer;
9379
9380        // Dexopt all dependencies first. Note: we ignore the return value and march on
9381        // on errors.
9382        // Note that we are going to call performDexOpt on those libraries as many times as
9383        // they are referenced in packages. When we do a batch of performDexOpt (for example
9384        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9385        // and the first package that uses the library will dexopt it. The
9386        // others will see that the compiled code for the library is up to date.
9387        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9388        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9389        if (!deps.isEmpty()) {
9390            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9391                    options.getCompilerFilter(), options.getSplitName(),
9392                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9393            for (PackageParser.Package depPackage : deps) {
9394                // TODO: Analyze and investigate if we (should) profile libraries.
9395                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9396                        getOrCreateCompilerPackageStats(depPackage),
9397                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9398            }
9399        }
9400        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9401                getOrCreateCompilerPackageStats(p),
9402                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9403    }
9404
9405    /**
9406     * Reconcile the information we have about the secondary dex files belonging to
9407     * {@code packagName} and the actual dex files. For all dex files that were
9408     * deleted, update the internal records and delete the generated oat files.
9409     */
9410    @Override
9411    public void reconcileSecondaryDexFiles(String packageName) {
9412        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9413            return;
9414        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9415            return;
9416        }
9417        mDexManager.reconcileSecondaryDexFiles(packageName);
9418    }
9419
9420    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9421    // a reference there.
9422    /*package*/ DexManager getDexManager() {
9423        return mDexManager;
9424    }
9425
9426    /**
9427     * Execute the background dexopt job immediately.
9428     */
9429    @Override
9430    public boolean runBackgroundDexoptJob() {
9431        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9432            return false;
9433        }
9434        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9435    }
9436
9437    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9438        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9439                || p.usesStaticLibraries != null) {
9440            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9441            Set<String> collectedNames = new HashSet<>();
9442            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9443
9444            retValue.remove(p);
9445
9446            return retValue;
9447        } else {
9448            return Collections.emptyList();
9449        }
9450    }
9451
9452    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9453            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9454        if (!collectedNames.contains(p.packageName)) {
9455            collectedNames.add(p.packageName);
9456            collected.add(p);
9457
9458            if (p.usesLibraries != null) {
9459                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9460                        null, collected, collectedNames);
9461            }
9462            if (p.usesOptionalLibraries != null) {
9463                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9464                        null, collected, collectedNames);
9465            }
9466            if (p.usesStaticLibraries != null) {
9467                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9468                        p.usesStaticLibrariesVersions, collected, collectedNames);
9469            }
9470        }
9471    }
9472
9473    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9474            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9475        final int libNameCount = libs.size();
9476        for (int i = 0; i < libNameCount; i++) {
9477            String libName = libs.get(i);
9478            int version = (versions != null && versions.length == libNameCount)
9479                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9480            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9481            if (libPkg != null) {
9482                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9483            }
9484        }
9485    }
9486
9487    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9488        synchronized (mPackages) {
9489            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9490            if (libEntry != null) {
9491                return mPackages.get(libEntry.apk);
9492            }
9493            return null;
9494        }
9495    }
9496
9497    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9498        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9499        if (versionedLib == null) {
9500            return null;
9501        }
9502        return versionedLib.get(version);
9503    }
9504
9505    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9506        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9507                pkg.staticSharedLibName);
9508        if (versionedLib == null) {
9509            return null;
9510        }
9511        int previousLibVersion = -1;
9512        final int versionCount = versionedLib.size();
9513        for (int i = 0; i < versionCount; i++) {
9514            final int libVersion = versionedLib.keyAt(i);
9515            if (libVersion < pkg.staticSharedLibVersion) {
9516                previousLibVersion = Math.max(previousLibVersion, libVersion);
9517            }
9518        }
9519        if (previousLibVersion >= 0) {
9520            return versionedLib.get(previousLibVersion);
9521        }
9522        return null;
9523    }
9524
9525    public void shutdown() {
9526        mPackageUsage.writeNow(mPackages);
9527        mCompilerStats.writeNow();
9528        mDexManager.writePackageDexUsageNow();
9529    }
9530
9531    @Override
9532    public void dumpProfiles(String packageName) {
9533        PackageParser.Package pkg;
9534        synchronized (mPackages) {
9535            pkg = mPackages.get(packageName);
9536            if (pkg == null) {
9537                throw new IllegalArgumentException("Unknown package: " + packageName);
9538            }
9539        }
9540        /* Only the shell, root, or the app user should be able to dump profiles. */
9541        int callingUid = Binder.getCallingUid();
9542        if (callingUid != Process.SHELL_UID &&
9543            callingUid != Process.ROOT_UID &&
9544            callingUid != pkg.applicationInfo.uid) {
9545            throw new SecurityException("dumpProfiles");
9546        }
9547
9548        synchronized (mInstallLock) {
9549            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9550            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9551            try {
9552                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9553                String codePaths = TextUtils.join(";", allCodePaths);
9554                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9555            } catch (InstallerException e) {
9556                Slog.w(TAG, "Failed to dump profiles", e);
9557            }
9558            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9559        }
9560    }
9561
9562    @Override
9563    public void forceDexOpt(String packageName) {
9564        enforceSystemOrRoot("forceDexOpt");
9565
9566        PackageParser.Package pkg;
9567        synchronized (mPackages) {
9568            pkg = mPackages.get(packageName);
9569            if (pkg == null) {
9570                throw new IllegalArgumentException("Unknown package: " + packageName);
9571            }
9572        }
9573
9574        synchronized (mInstallLock) {
9575            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9576
9577            // Whoever is calling forceDexOpt wants a compiled package.
9578            // Don't use profiles since that may cause compilation to be skipped.
9579            final int res = performDexOptInternalWithDependenciesLI(
9580                    pkg,
9581                    new DexoptOptions(packageName,
9582                            getDefaultCompilerFilter(),
9583                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9584
9585            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9586            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9587                throw new IllegalStateException("Failed to dexopt: " + res);
9588            }
9589        }
9590    }
9591
9592    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9593        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9594            Slog.w(TAG, "Unable to update from " + oldPkg.name
9595                    + " to " + newPkg.packageName
9596                    + ": old package not in system partition");
9597            return false;
9598        } else if (mPackages.get(oldPkg.name) != null) {
9599            Slog.w(TAG, "Unable to update from " + oldPkg.name
9600                    + " to " + newPkg.packageName
9601                    + ": old package still exists");
9602            return false;
9603        }
9604        return true;
9605    }
9606
9607    void removeCodePathLI(File codePath) {
9608        if (codePath.isDirectory()) {
9609            try {
9610                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9611            } catch (InstallerException e) {
9612                Slog.w(TAG, "Failed to remove code path", e);
9613            }
9614        } else {
9615            codePath.delete();
9616        }
9617    }
9618
9619    private int[] resolveUserIds(int userId) {
9620        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9621    }
9622
9623    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9624        if (pkg == null) {
9625            Slog.wtf(TAG, "Package was null!", new Throwable());
9626            return;
9627        }
9628        clearAppDataLeafLIF(pkg, userId, flags);
9629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9630        for (int i = 0; i < childCount; i++) {
9631            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9632        }
9633    }
9634
9635    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9636        final PackageSetting ps;
9637        synchronized (mPackages) {
9638            ps = mSettings.mPackages.get(pkg.packageName);
9639        }
9640        for (int realUserId : resolveUserIds(userId)) {
9641            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9642            try {
9643                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9644                        ceDataInode);
9645            } catch (InstallerException e) {
9646                Slog.w(TAG, String.valueOf(e));
9647            }
9648        }
9649    }
9650
9651    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9652        if (pkg == null) {
9653            Slog.wtf(TAG, "Package was null!", new Throwable());
9654            return;
9655        }
9656        destroyAppDataLeafLIF(pkg, userId, flags);
9657        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9658        for (int i = 0; i < childCount; i++) {
9659            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9660        }
9661    }
9662
9663    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9664        final PackageSetting ps;
9665        synchronized (mPackages) {
9666            ps = mSettings.mPackages.get(pkg.packageName);
9667        }
9668        for (int realUserId : resolveUserIds(userId)) {
9669            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9670            try {
9671                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9672                        ceDataInode);
9673            } catch (InstallerException e) {
9674                Slog.w(TAG, String.valueOf(e));
9675            }
9676            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9677        }
9678    }
9679
9680    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9681        if (pkg == null) {
9682            Slog.wtf(TAG, "Package was null!", new Throwable());
9683            return;
9684        }
9685        destroyAppProfilesLeafLIF(pkg);
9686        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9687        for (int i = 0; i < childCount; i++) {
9688            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9689        }
9690    }
9691
9692    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9693        try {
9694            mInstaller.destroyAppProfiles(pkg.packageName);
9695        } catch (InstallerException e) {
9696            Slog.w(TAG, String.valueOf(e));
9697        }
9698    }
9699
9700    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9701        if (pkg == null) {
9702            Slog.wtf(TAG, "Package was null!", new Throwable());
9703            return;
9704        }
9705        clearAppProfilesLeafLIF(pkg);
9706        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9707        for (int i = 0; i < childCount; i++) {
9708            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9709        }
9710    }
9711
9712    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9713        try {
9714            mInstaller.clearAppProfiles(pkg.packageName);
9715        } catch (InstallerException e) {
9716            Slog.w(TAG, String.valueOf(e));
9717        }
9718    }
9719
9720    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9721            long lastUpdateTime) {
9722        // Set parent install/update time
9723        PackageSetting ps = (PackageSetting) pkg.mExtras;
9724        if (ps != null) {
9725            ps.firstInstallTime = firstInstallTime;
9726            ps.lastUpdateTime = lastUpdateTime;
9727        }
9728        // Set children install/update time
9729        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9730        for (int i = 0; i < childCount; i++) {
9731            PackageParser.Package childPkg = pkg.childPackages.get(i);
9732            ps = (PackageSetting) childPkg.mExtras;
9733            if (ps != null) {
9734                ps.firstInstallTime = firstInstallTime;
9735                ps.lastUpdateTime = lastUpdateTime;
9736            }
9737        }
9738    }
9739
9740    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9741            PackageParser.Package changingLib) {
9742        if (file.path != null) {
9743            usesLibraryFiles.add(file.path);
9744            return;
9745        }
9746        PackageParser.Package p = mPackages.get(file.apk);
9747        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9748            // If we are doing this while in the middle of updating a library apk,
9749            // then we need to make sure to use that new apk for determining the
9750            // dependencies here.  (We haven't yet finished committing the new apk
9751            // to the package manager state.)
9752            if (p == null || p.packageName.equals(changingLib.packageName)) {
9753                p = changingLib;
9754            }
9755        }
9756        if (p != null) {
9757            usesLibraryFiles.addAll(p.getAllCodePaths());
9758            if (p.usesLibraryFiles != null) {
9759                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9760            }
9761        }
9762    }
9763
9764    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9765            PackageParser.Package changingLib) throws PackageManagerException {
9766        if (pkg == null) {
9767            return;
9768        }
9769        ArraySet<String> usesLibraryFiles = null;
9770        if (pkg.usesLibraries != null) {
9771            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9772                    null, null, pkg.packageName, changingLib, true,
9773                    pkg.applicationInfo.targetSdkVersion, null);
9774        }
9775        if (pkg.usesStaticLibraries != null) {
9776            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9777                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9778                    pkg.packageName, changingLib, true,
9779                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9780        }
9781        if (pkg.usesOptionalLibraries != null) {
9782            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9783                    null, null, pkg.packageName, changingLib, false,
9784                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9785        }
9786        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9787            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9788        } else {
9789            pkg.usesLibraryFiles = null;
9790        }
9791    }
9792
9793    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9794            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9795            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9796            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
9797            throws PackageManagerException {
9798        final int libCount = requestedLibraries.size();
9799        for (int i = 0; i < libCount; i++) {
9800            final String libName = requestedLibraries.get(i);
9801            final int libVersion = requiredVersions != null ? requiredVersions[i]
9802                    : SharedLibraryInfo.VERSION_UNDEFINED;
9803            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9804            if (libEntry == null) {
9805                if (required) {
9806                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9807                            "Package " + packageName + " requires unavailable shared library "
9808                                    + libName + "; failing!");
9809                } else if (DEBUG_SHARED_LIBRARIES) {
9810                    Slog.i(TAG, "Package " + packageName
9811                            + " desires unavailable shared library "
9812                            + libName + "; ignoring!");
9813                }
9814            } else {
9815                if (requiredVersions != null && requiredCertDigests != null) {
9816                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9817                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9818                            "Package " + packageName + " requires unavailable static shared"
9819                                    + " library " + libName + " version "
9820                                    + libEntry.info.getVersion() + "; failing!");
9821                    }
9822
9823                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9824                    if (libPkg == null) {
9825                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9826                                "Package " + packageName + " requires unavailable static shared"
9827                                        + " library; failing!");
9828                    }
9829
9830                    final String[] expectedCertDigests = requiredCertDigests[i];
9831                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9832                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9833                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9834                            : PackageUtils.computeSignaturesSha256Digests(
9835                                    new Signature[]{libPkg.mSignatures[0]});
9836
9837                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9838                    // target O we don't parse the "additional-certificate" tags similarly
9839                    // how we only consider all certs only for apps targeting O (see above).
9840                    // Therefore, the size check is safe to make.
9841                    if (expectedCertDigests.length != libCertDigests.length) {
9842                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9843                                "Package " + packageName + " requires differently signed" +
9844                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9845                    }
9846
9847                    // Use a predictable order as signature order may vary
9848                    Arrays.sort(libCertDigests);
9849                    Arrays.sort(expectedCertDigests);
9850
9851                    final int certCount = libCertDigests.length;
9852                    for (int j = 0; j < certCount; j++) {
9853                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9854                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9855                                    "Package " + packageName + " requires differently signed" +
9856                                            " static shared library; failing!");
9857                        }
9858                    }
9859                }
9860
9861                if (outUsedLibraries == null) {
9862                    outUsedLibraries = new ArraySet<>();
9863                }
9864                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9865            }
9866        }
9867        return outUsedLibraries;
9868    }
9869
9870    private static boolean hasString(List<String> list, List<String> which) {
9871        if (list == null) {
9872            return false;
9873        }
9874        for (int i=list.size()-1; i>=0; i--) {
9875            for (int j=which.size()-1; j>=0; j--) {
9876                if (which.get(j).equals(list.get(i))) {
9877                    return true;
9878                }
9879            }
9880        }
9881        return false;
9882    }
9883
9884    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9885            PackageParser.Package changingPkg) {
9886        ArrayList<PackageParser.Package> res = null;
9887        for (PackageParser.Package pkg : mPackages.values()) {
9888            if (changingPkg != null
9889                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9890                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9891                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9892                            changingPkg.staticSharedLibName)) {
9893                return null;
9894            }
9895            if (res == null) {
9896                res = new ArrayList<>();
9897            }
9898            res.add(pkg);
9899            try {
9900                updateSharedLibrariesLPr(pkg, changingPkg);
9901            } catch (PackageManagerException e) {
9902                // If a system app update or an app and a required lib missing we
9903                // delete the package and for updated system apps keep the data as
9904                // it is better for the user to reinstall than to be in an limbo
9905                // state. Also libs disappearing under an app should never happen
9906                // - just in case.
9907                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9908                    final int flags = pkg.isUpdatedSystemApp()
9909                            ? PackageManager.DELETE_KEEP_DATA : 0;
9910                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9911                            flags , null, true, null);
9912                }
9913                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9914            }
9915        }
9916        return res;
9917    }
9918
9919    /**
9920     * Derive the value of the {@code cpuAbiOverride} based on the provided
9921     * value and an optional stored value from the package settings.
9922     */
9923    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9924        String cpuAbiOverride = null;
9925
9926        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9927            cpuAbiOverride = null;
9928        } else if (abiOverride != null) {
9929            cpuAbiOverride = abiOverride;
9930        } else if (settings != null) {
9931            cpuAbiOverride = settings.cpuAbiOverrideString;
9932        }
9933
9934        return cpuAbiOverride;
9935    }
9936
9937    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9938            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9939                    throws PackageManagerException {
9940        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9941        // If the package has children and this is the first dive in the function
9942        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9943        // whether all packages (parent and children) would be successfully scanned
9944        // before the actual scan since scanning mutates internal state and we want
9945        // to atomically install the package and its children.
9946        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9947            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9948                scanFlags |= SCAN_CHECK_ONLY;
9949            }
9950        } else {
9951            scanFlags &= ~SCAN_CHECK_ONLY;
9952        }
9953
9954        final PackageParser.Package scannedPkg;
9955        try {
9956            // Scan the parent
9957            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9958            // Scan the children
9959            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9960            for (int i = 0; i < childCount; i++) {
9961                PackageParser.Package childPkg = pkg.childPackages.get(i);
9962                scanPackageLI(childPkg, policyFlags,
9963                        scanFlags, currentTime, user);
9964            }
9965        } finally {
9966            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9967        }
9968
9969        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9970            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9971        }
9972
9973        return scannedPkg;
9974    }
9975
9976    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9977            int scanFlags, long currentTime, @Nullable UserHandle user)
9978                    throws PackageManagerException {
9979        boolean success = false;
9980        try {
9981            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9982                    currentTime, user);
9983            success = true;
9984            return res;
9985        } finally {
9986            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9987                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9988                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9989                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9990                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9991            }
9992        }
9993    }
9994
9995    /**
9996     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9997     */
9998    private static boolean apkHasCode(String fileName) {
9999        StrictJarFile jarFile = null;
10000        try {
10001            jarFile = new StrictJarFile(fileName,
10002                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10003            return jarFile.findEntry("classes.dex") != null;
10004        } catch (IOException ignore) {
10005        } finally {
10006            try {
10007                if (jarFile != null) {
10008                    jarFile.close();
10009                }
10010            } catch (IOException ignore) {}
10011        }
10012        return false;
10013    }
10014
10015    /**
10016     * Enforces code policy for the package. This ensures that if an APK has
10017     * declared hasCode="true" in its manifest that the APK actually contains
10018     * code.
10019     *
10020     * @throws PackageManagerException If bytecode could not be found when it should exist
10021     */
10022    private static void assertCodePolicy(PackageParser.Package pkg)
10023            throws PackageManagerException {
10024        final boolean shouldHaveCode =
10025                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10026        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10027            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10028                    "Package " + pkg.baseCodePath + " code is missing");
10029        }
10030
10031        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10032            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10033                final boolean splitShouldHaveCode =
10034                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10035                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10036                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10037                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10038                }
10039            }
10040        }
10041    }
10042
10043    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10044            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10045                    throws PackageManagerException {
10046        if (DEBUG_PACKAGE_SCANNING) {
10047            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10048                Log.d(TAG, "Scanning package " + pkg.packageName);
10049        }
10050
10051        applyPolicy(pkg, policyFlags);
10052
10053        assertPackageIsValid(pkg, policyFlags, scanFlags);
10054
10055        if (Build.IS_DEBUGGABLE &&
10056                pkg.isPrivilegedApp() &&
10057                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10058            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10059        }
10060
10061        // Initialize package source and resource directories
10062        final File scanFile = new File(pkg.codePath);
10063        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10064        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10065
10066        SharedUserSetting suid = null;
10067        PackageSetting pkgSetting = null;
10068
10069        // Getting the package setting may have a side-effect, so if we
10070        // are only checking if scan would succeed, stash a copy of the
10071        // old setting to restore at the end.
10072        PackageSetting nonMutatedPs = null;
10073
10074        // We keep references to the derived CPU Abis from settings in oder to reuse
10075        // them in the case where we're not upgrading or booting for the first time.
10076        String primaryCpuAbiFromSettings = null;
10077        String secondaryCpuAbiFromSettings = null;
10078
10079        // writer
10080        synchronized (mPackages) {
10081            if (pkg.mSharedUserId != null) {
10082                // SIDE EFFECTS; may potentially allocate a new shared user
10083                suid = mSettings.getSharedUserLPw(
10084                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10085                if (DEBUG_PACKAGE_SCANNING) {
10086                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10087                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10088                                + "): packages=" + suid.packages);
10089                }
10090            }
10091
10092            // Check if we are renaming from an original package name.
10093            PackageSetting origPackage = null;
10094            String realName = null;
10095            if (pkg.mOriginalPackages != null) {
10096                // This package may need to be renamed to a previously
10097                // installed name.  Let's check on that...
10098                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10099                if (pkg.mOriginalPackages.contains(renamed)) {
10100                    // This package had originally been installed as the
10101                    // original name, and we have already taken care of
10102                    // transitioning to the new one.  Just update the new
10103                    // one to continue using the old name.
10104                    realName = pkg.mRealPackage;
10105                    if (!pkg.packageName.equals(renamed)) {
10106                        // Callers into this function may have already taken
10107                        // care of renaming the package; only do it here if
10108                        // it is not already done.
10109                        pkg.setPackageName(renamed);
10110                    }
10111                } else {
10112                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10113                        if ((origPackage = mSettings.getPackageLPr(
10114                                pkg.mOriginalPackages.get(i))) != null) {
10115                            // We do have the package already installed under its
10116                            // original name...  should we use it?
10117                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10118                                // New package is not compatible with original.
10119                                origPackage = null;
10120                                continue;
10121                            } else if (origPackage.sharedUser != null) {
10122                                // Make sure uid is compatible between packages.
10123                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10124                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10125                                            + " to " + pkg.packageName + ": old uid "
10126                                            + origPackage.sharedUser.name
10127                                            + " differs from " + pkg.mSharedUserId);
10128                                    origPackage = null;
10129                                    continue;
10130                                }
10131                                // TODO: Add case when shared user id is added [b/28144775]
10132                            } else {
10133                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10134                                        + pkg.packageName + " to old name " + origPackage.name);
10135                            }
10136                            break;
10137                        }
10138                    }
10139                }
10140            }
10141
10142            if (mTransferedPackages.contains(pkg.packageName)) {
10143                Slog.w(TAG, "Package " + pkg.packageName
10144                        + " was transferred to another, but its .apk remains");
10145            }
10146
10147            // See comments in nonMutatedPs declaration
10148            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10149                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10150                if (foundPs != null) {
10151                    nonMutatedPs = new PackageSetting(foundPs);
10152                }
10153            }
10154
10155            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10156                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10157                if (foundPs != null) {
10158                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10159                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10160                }
10161            }
10162
10163            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10164            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10165                PackageManagerService.reportSettingsProblem(Log.WARN,
10166                        "Package " + pkg.packageName + " shared user changed from "
10167                                + (pkgSetting.sharedUser != null
10168                                        ? pkgSetting.sharedUser.name : "<nothing>")
10169                                + " to "
10170                                + (suid != null ? suid.name : "<nothing>")
10171                                + "; replacing with new");
10172                pkgSetting = null;
10173            }
10174            final PackageSetting oldPkgSetting =
10175                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10176            final PackageSetting disabledPkgSetting =
10177                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10178
10179            String[] usesStaticLibraries = null;
10180            if (pkg.usesStaticLibraries != null) {
10181                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10182                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10183            }
10184
10185            if (pkgSetting == null) {
10186                final String parentPackageName = (pkg.parentPackage != null)
10187                        ? pkg.parentPackage.packageName : null;
10188                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10189                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10190                // REMOVE SharedUserSetting from method; update in a separate call
10191                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10192                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10193                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10194                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10195                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10196                        true /*allowInstall*/, instantApp, virtualPreload,
10197                        parentPackageName, pkg.getChildPackageNames(),
10198                        UserManagerService.getInstance(), usesStaticLibraries,
10199                        pkg.usesStaticLibrariesVersions);
10200                // SIDE EFFECTS; updates system state; move elsewhere
10201                if (origPackage != null) {
10202                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10203                }
10204                mSettings.addUserToSettingLPw(pkgSetting);
10205            } else {
10206                // REMOVE SharedUserSetting from method; update in a separate call.
10207                //
10208                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10209                // secondaryCpuAbi are not known at this point so we always update them
10210                // to null here, only to reset them at a later point.
10211                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10212                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10213                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10214                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10215                        UserManagerService.getInstance(), usesStaticLibraries,
10216                        pkg.usesStaticLibrariesVersions);
10217            }
10218            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10219            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10220
10221            // SIDE EFFECTS; modifies system state; move elsewhere
10222            if (pkgSetting.origPackage != null) {
10223                // If we are first transitioning from an original package,
10224                // fix up the new package's name now.  We need to do this after
10225                // looking up the package under its new name, so getPackageLP
10226                // can take care of fiddling things correctly.
10227                pkg.setPackageName(origPackage.name);
10228
10229                // File a report about this.
10230                String msg = "New package " + pkgSetting.realName
10231                        + " renamed to replace old package " + pkgSetting.name;
10232                reportSettingsProblem(Log.WARN, msg);
10233
10234                // Make a note of it.
10235                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10236                    mTransferedPackages.add(origPackage.name);
10237                }
10238
10239                // No longer need to retain this.
10240                pkgSetting.origPackage = null;
10241            }
10242
10243            // SIDE EFFECTS; modifies system state; move elsewhere
10244            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10245                // Make a note of it.
10246                mTransferedPackages.add(pkg.packageName);
10247            }
10248
10249            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10250                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10251            }
10252
10253            if ((scanFlags & SCAN_BOOTING) == 0
10254                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10255                // Check all shared libraries and map to their actual file path.
10256                // We only do this here for apps not on a system dir, because those
10257                // are the only ones that can fail an install due to this.  We
10258                // will take care of the system apps by updating all of their
10259                // library paths after the scan is done. Also during the initial
10260                // scan don't update any libs as we do this wholesale after all
10261                // apps are scanned to avoid dependency based scanning.
10262                updateSharedLibrariesLPr(pkg, null);
10263            }
10264
10265            if (mFoundPolicyFile) {
10266                SELinuxMMAC.assignSeInfoValue(pkg);
10267            }
10268            pkg.applicationInfo.uid = pkgSetting.appId;
10269            pkg.mExtras = pkgSetting;
10270
10271
10272            // Static shared libs have same package with different versions where
10273            // we internally use a synthetic package name to allow multiple versions
10274            // of the same package, therefore we need to compare signatures against
10275            // the package setting for the latest library version.
10276            PackageSetting signatureCheckPs = pkgSetting;
10277            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10278                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10279                if (libraryEntry != null) {
10280                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10281                }
10282            }
10283
10284            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10285                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10286                    // We just determined the app is signed correctly, so bring
10287                    // over the latest parsed certs.
10288                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10289                } else {
10290                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10291                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10292                                "Package " + pkg.packageName + " upgrade keys do not match the "
10293                                + "previously installed version");
10294                    } else {
10295                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10296                        String msg = "System package " + pkg.packageName
10297                                + " signature changed; retaining data.";
10298                        reportSettingsProblem(Log.WARN, msg);
10299                    }
10300                }
10301            } else {
10302                try {
10303                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10304                    verifySignaturesLP(signatureCheckPs, pkg);
10305                    // We just determined the app is signed correctly, so bring
10306                    // over the latest parsed certs.
10307                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10308                } catch (PackageManagerException e) {
10309                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10310                        throw e;
10311                    }
10312                    // The signature has changed, but this package is in the system
10313                    // image...  let's recover!
10314                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10315                    // However...  if this package is part of a shared user, but it
10316                    // doesn't match the signature of the shared user, let's fail.
10317                    // What this means is that you can't change the signatures
10318                    // associated with an overall shared user, which doesn't seem all
10319                    // that unreasonable.
10320                    if (signatureCheckPs.sharedUser != null) {
10321                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10322                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10323                            throw new PackageManagerException(
10324                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10325                                    "Signature mismatch for shared user: "
10326                                            + pkgSetting.sharedUser);
10327                        }
10328                    }
10329                    // File a report about this.
10330                    String msg = "System package " + pkg.packageName
10331                            + " signature changed; retaining data.";
10332                    reportSettingsProblem(Log.WARN, msg);
10333                }
10334            }
10335
10336            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10337                // This package wants to adopt ownership of permissions from
10338                // another package.
10339                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10340                    final String origName = pkg.mAdoptPermissions.get(i);
10341                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10342                    if (orig != null) {
10343                        if (verifyPackageUpdateLPr(orig, pkg)) {
10344                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10345                                    + pkg.packageName);
10346                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10347                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10348                        }
10349                    }
10350                }
10351            }
10352        }
10353
10354        pkg.applicationInfo.processName = fixProcessName(
10355                pkg.applicationInfo.packageName,
10356                pkg.applicationInfo.processName);
10357
10358        if (pkg != mPlatformPackage) {
10359            // Get all of our default paths setup
10360            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10361        }
10362
10363        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10364
10365        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10366            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10367                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10368                final boolean extractNativeLibs = !pkg.isLibrary();
10369                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10370                        mAppLib32InstallDir);
10371                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10372
10373                // Some system apps still use directory structure for native libraries
10374                // in which case we might end up not detecting abi solely based on apk
10375                // structure. Try to detect abi based on directory structure.
10376                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10377                        pkg.applicationInfo.primaryCpuAbi == null) {
10378                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10379                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10380                }
10381            } else {
10382                // This is not a first boot or an upgrade, don't bother deriving the
10383                // ABI during the scan. Instead, trust the value that was stored in the
10384                // package setting.
10385                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10386                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10387
10388                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10389
10390                if (DEBUG_ABI_SELECTION) {
10391                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10392                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10393                        pkg.applicationInfo.secondaryCpuAbi);
10394                }
10395            }
10396        } else {
10397            if ((scanFlags & SCAN_MOVE) != 0) {
10398                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10399                // but we already have this packages package info in the PackageSetting. We just
10400                // use that and derive the native library path based on the new codepath.
10401                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10402                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10403            }
10404
10405            // Set native library paths again. For moves, the path will be updated based on the
10406            // ABIs we've determined above. For non-moves, the path will be updated based on the
10407            // ABIs we determined during compilation, but the path will depend on the final
10408            // package path (after the rename away from the stage path).
10409            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10410        }
10411
10412        // This is a special case for the "system" package, where the ABI is
10413        // dictated by the zygote configuration (and init.rc). We should keep track
10414        // of this ABI so that we can deal with "normal" applications that run under
10415        // the same UID correctly.
10416        if (mPlatformPackage == pkg) {
10417            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10418                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10419        }
10420
10421        // If there's a mismatch between the abi-override in the package setting
10422        // and the abiOverride specified for the install. Warn about this because we
10423        // would've already compiled the app without taking the package setting into
10424        // account.
10425        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10426            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10427                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10428                        " for package " + pkg.packageName);
10429            }
10430        }
10431
10432        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10433        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10434        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10435
10436        // Copy the derived override back to the parsed package, so that we can
10437        // update the package settings accordingly.
10438        pkg.cpuAbiOverride = cpuAbiOverride;
10439
10440        if (DEBUG_ABI_SELECTION) {
10441            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10442                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10443                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10444        }
10445
10446        // Push the derived path down into PackageSettings so we know what to
10447        // clean up at uninstall time.
10448        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10449
10450        if (DEBUG_ABI_SELECTION) {
10451            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10452                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10453                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10454        }
10455
10456        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10457        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10458            // We don't do this here during boot because we can do it all
10459            // at once after scanning all existing packages.
10460            //
10461            // We also do this *before* we perform dexopt on this package, so that
10462            // we can avoid redundant dexopts, and also to make sure we've got the
10463            // code and package path correct.
10464            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10465        }
10466
10467        if (mFactoryTest && pkg.requestedPermissions.contains(
10468                android.Manifest.permission.FACTORY_TEST)) {
10469            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10470        }
10471
10472        if (isSystemApp(pkg)) {
10473            pkgSetting.isOrphaned = true;
10474        }
10475
10476        // Take care of first install / last update times.
10477        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10478        if (currentTime != 0) {
10479            if (pkgSetting.firstInstallTime == 0) {
10480                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10481            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10482                pkgSetting.lastUpdateTime = currentTime;
10483            }
10484        } else if (pkgSetting.firstInstallTime == 0) {
10485            // We need *something*.  Take time time stamp of the file.
10486            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10487        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10488            if (scanFileTime != pkgSetting.timeStamp) {
10489                // A package on the system image has changed; consider this
10490                // to be an update.
10491                pkgSetting.lastUpdateTime = scanFileTime;
10492            }
10493        }
10494        pkgSetting.setTimeStamp(scanFileTime);
10495
10496        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10497            if (nonMutatedPs != null) {
10498                synchronized (mPackages) {
10499                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10500                }
10501            }
10502        } else {
10503            final int userId = user == null ? 0 : user.getIdentifier();
10504            // Modify state for the given package setting
10505            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10506                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10507            if (pkgSetting.getInstantApp(userId)) {
10508                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10509            }
10510        }
10511        return pkg;
10512    }
10513
10514    /**
10515     * Applies policy to the parsed package based upon the given policy flags.
10516     * Ensures the package is in a good state.
10517     * <p>
10518     * Implementation detail: This method must NOT have any side effect. It would
10519     * ideally be static, but, it requires locks to read system state.
10520     */
10521    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10522        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10523            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10524            if (pkg.applicationInfo.isDirectBootAware()) {
10525                // we're direct boot aware; set for all components
10526                for (PackageParser.Service s : pkg.services) {
10527                    s.info.encryptionAware = s.info.directBootAware = true;
10528                }
10529                for (PackageParser.Provider p : pkg.providers) {
10530                    p.info.encryptionAware = p.info.directBootAware = true;
10531                }
10532                for (PackageParser.Activity a : pkg.activities) {
10533                    a.info.encryptionAware = a.info.directBootAware = true;
10534                }
10535                for (PackageParser.Activity r : pkg.receivers) {
10536                    r.info.encryptionAware = r.info.directBootAware = true;
10537                }
10538            }
10539            if (compressedFileExists(pkg.codePath)) {
10540                pkg.isStub = true;
10541            }
10542        } else {
10543            // Only allow system apps to be flagged as core apps.
10544            pkg.coreApp = false;
10545            // clear flags not applicable to regular apps
10546            pkg.applicationInfo.privateFlags &=
10547                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10548            pkg.applicationInfo.privateFlags &=
10549                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10550        }
10551        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10552
10553        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10554            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10555        }
10556
10557        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10558            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10559        }
10560
10561        if (!isSystemApp(pkg)) {
10562            // Only system apps can use these features.
10563            pkg.mOriginalPackages = null;
10564            pkg.mRealPackage = null;
10565            pkg.mAdoptPermissions = null;
10566        }
10567    }
10568
10569    /**
10570     * Asserts the parsed package is valid according to the given policy. If the
10571     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10572     * <p>
10573     * Implementation detail: This method must NOT have any side effects. It would
10574     * ideally be static, but, it requires locks to read system state.
10575     *
10576     * @throws PackageManagerException If the package fails any of the validation checks
10577     */
10578    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10579            throws PackageManagerException {
10580        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10581            assertCodePolicy(pkg);
10582        }
10583
10584        if (pkg.applicationInfo.getCodePath() == null ||
10585                pkg.applicationInfo.getResourcePath() == null) {
10586            // Bail out. The resource and code paths haven't been set.
10587            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10588                    "Code and resource paths haven't been set correctly");
10589        }
10590
10591        // Make sure we're not adding any bogus keyset info
10592        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10593        ksms.assertScannedPackageValid(pkg);
10594
10595        synchronized (mPackages) {
10596            // The special "android" package can only be defined once
10597            if (pkg.packageName.equals("android")) {
10598                if (mAndroidApplication != null) {
10599                    Slog.w(TAG, "*************************************************");
10600                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10601                    Slog.w(TAG, " codePath=" + pkg.codePath);
10602                    Slog.w(TAG, "*************************************************");
10603                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10604                            "Core android package being redefined.  Skipping.");
10605                }
10606            }
10607
10608            // A package name must be unique; don't allow duplicates
10609            if (mPackages.containsKey(pkg.packageName)) {
10610                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10611                        "Application package " + pkg.packageName
10612                        + " already installed.  Skipping duplicate.");
10613            }
10614
10615            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10616                // Static libs have a synthetic package name containing the version
10617                // but we still want the base name to be unique.
10618                if (mPackages.containsKey(pkg.manifestPackageName)) {
10619                    throw new PackageManagerException(
10620                            "Duplicate static shared lib provider package");
10621                }
10622
10623                // Static shared libraries should have at least O target SDK
10624                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10625                    throw new PackageManagerException(
10626                            "Packages declaring static-shared libs must target O SDK or higher");
10627                }
10628
10629                // Package declaring static a shared lib cannot be instant apps
10630                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10631                    throw new PackageManagerException(
10632                            "Packages declaring static-shared libs cannot be instant apps");
10633                }
10634
10635                // Package declaring static a shared lib cannot be renamed since the package
10636                // name is synthetic and apps can't code around package manager internals.
10637                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10638                    throw new PackageManagerException(
10639                            "Packages declaring static-shared libs cannot be renamed");
10640                }
10641
10642                // Package declaring static a shared lib cannot declare child packages
10643                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10644                    throw new PackageManagerException(
10645                            "Packages declaring static-shared libs cannot have child packages");
10646                }
10647
10648                // Package declaring static a shared lib cannot declare dynamic libs
10649                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10650                    throw new PackageManagerException(
10651                            "Packages declaring static-shared libs cannot declare dynamic libs");
10652                }
10653
10654                // Package declaring static a shared lib cannot declare shared users
10655                if (pkg.mSharedUserId != null) {
10656                    throw new PackageManagerException(
10657                            "Packages declaring static-shared libs cannot declare shared users");
10658                }
10659
10660                // Static shared libs cannot declare activities
10661                if (!pkg.activities.isEmpty()) {
10662                    throw new PackageManagerException(
10663                            "Static shared libs cannot declare activities");
10664                }
10665
10666                // Static shared libs cannot declare services
10667                if (!pkg.services.isEmpty()) {
10668                    throw new PackageManagerException(
10669                            "Static shared libs cannot declare services");
10670                }
10671
10672                // Static shared libs cannot declare providers
10673                if (!pkg.providers.isEmpty()) {
10674                    throw new PackageManagerException(
10675                            "Static shared libs cannot declare content providers");
10676                }
10677
10678                // Static shared libs cannot declare receivers
10679                if (!pkg.receivers.isEmpty()) {
10680                    throw new PackageManagerException(
10681                            "Static shared libs cannot declare broadcast receivers");
10682                }
10683
10684                // Static shared libs cannot declare permission groups
10685                if (!pkg.permissionGroups.isEmpty()) {
10686                    throw new PackageManagerException(
10687                            "Static shared libs cannot declare permission groups");
10688                }
10689
10690                // Static shared libs cannot declare permissions
10691                if (!pkg.permissions.isEmpty()) {
10692                    throw new PackageManagerException(
10693                            "Static shared libs cannot declare permissions");
10694                }
10695
10696                // Static shared libs cannot declare protected broadcasts
10697                if (pkg.protectedBroadcasts != null) {
10698                    throw new PackageManagerException(
10699                            "Static shared libs cannot declare protected broadcasts");
10700                }
10701
10702                // Static shared libs cannot be overlay targets
10703                if (pkg.mOverlayTarget != null) {
10704                    throw new PackageManagerException(
10705                            "Static shared libs cannot be overlay targets");
10706                }
10707
10708                // The version codes must be ordered as lib versions
10709                int minVersionCode = Integer.MIN_VALUE;
10710                int maxVersionCode = Integer.MAX_VALUE;
10711
10712                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10713                        pkg.staticSharedLibName);
10714                if (versionedLib != null) {
10715                    final int versionCount = versionedLib.size();
10716                    for (int i = 0; i < versionCount; i++) {
10717                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10718                        final int libVersionCode = libInfo.getDeclaringPackage()
10719                                .getVersionCode();
10720                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10721                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10722                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10723                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10724                        } else {
10725                            minVersionCode = maxVersionCode = libVersionCode;
10726                            break;
10727                        }
10728                    }
10729                }
10730                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10731                    throw new PackageManagerException("Static shared"
10732                            + " lib version codes must be ordered as lib versions");
10733                }
10734            }
10735
10736            // Only privileged apps and updated privileged apps can add child packages.
10737            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10738                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10739                    throw new PackageManagerException("Only privileged apps can add child "
10740                            + "packages. Ignoring package " + pkg.packageName);
10741                }
10742                final int childCount = pkg.childPackages.size();
10743                for (int i = 0; i < childCount; i++) {
10744                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10745                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10746                            childPkg.packageName)) {
10747                        throw new PackageManagerException("Can't override child of "
10748                                + "another disabled app. Ignoring package " + pkg.packageName);
10749                    }
10750                }
10751            }
10752
10753            // If we're only installing presumed-existing packages, require that the
10754            // scanned APK is both already known and at the path previously established
10755            // for it.  Previously unknown packages we pick up normally, but if we have an
10756            // a priori expectation about this package's install presence, enforce it.
10757            // With a singular exception for new system packages. When an OTA contains
10758            // a new system package, we allow the codepath to change from a system location
10759            // to the user-installed location. If we don't allow this change, any newer,
10760            // user-installed version of the application will be ignored.
10761            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10762                if (mExpectingBetter.containsKey(pkg.packageName)) {
10763                    logCriticalInfo(Log.WARN,
10764                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10765                } else {
10766                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10767                    if (known != null) {
10768                        if (DEBUG_PACKAGE_SCANNING) {
10769                            Log.d(TAG, "Examining " + pkg.codePath
10770                                    + " and requiring known paths " + known.codePathString
10771                                    + " & " + known.resourcePathString);
10772                        }
10773                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10774                                || !pkg.applicationInfo.getResourcePath().equals(
10775                                        known.resourcePathString)) {
10776                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10777                                    "Application package " + pkg.packageName
10778                                    + " found at " + pkg.applicationInfo.getCodePath()
10779                                    + " but expected at " + known.codePathString
10780                                    + "; ignoring.");
10781                        }
10782                    } else {
10783                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10784                                "Application package " + pkg.packageName
10785                                + " not found; ignoring.");
10786                    }
10787                }
10788            }
10789
10790            // Verify that this new package doesn't have any content providers
10791            // that conflict with existing packages.  Only do this if the
10792            // package isn't already installed, since we don't want to break
10793            // things that are installed.
10794            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10795                final int N = pkg.providers.size();
10796                int i;
10797                for (i=0; i<N; i++) {
10798                    PackageParser.Provider p = pkg.providers.get(i);
10799                    if (p.info.authority != null) {
10800                        String names[] = p.info.authority.split(";");
10801                        for (int j = 0; j < names.length; j++) {
10802                            if (mProvidersByAuthority.containsKey(names[j])) {
10803                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10804                                final String otherPackageName =
10805                                        ((other != null && other.getComponentName() != null) ?
10806                                                other.getComponentName().getPackageName() : "?");
10807                                throw new PackageManagerException(
10808                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10809                                        "Can't install because provider name " + names[j]
10810                                                + " (in package " + pkg.applicationInfo.packageName
10811                                                + ") is already used by " + otherPackageName);
10812                            }
10813                        }
10814                    }
10815                }
10816            }
10817        }
10818    }
10819
10820    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10821            int type, String declaringPackageName, int declaringVersionCode) {
10822        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10823        if (versionedLib == null) {
10824            versionedLib = new SparseArray<>();
10825            mSharedLibraries.put(name, versionedLib);
10826            if (type == SharedLibraryInfo.TYPE_STATIC) {
10827                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10828            }
10829        } else if (versionedLib.indexOfKey(version) >= 0) {
10830            return false;
10831        }
10832        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10833                version, type, declaringPackageName, declaringVersionCode);
10834        versionedLib.put(version, libEntry);
10835        return true;
10836    }
10837
10838    private boolean removeSharedLibraryLPw(String name, int version) {
10839        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10840        if (versionedLib == null) {
10841            return false;
10842        }
10843        final int libIdx = versionedLib.indexOfKey(version);
10844        if (libIdx < 0) {
10845            return false;
10846        }
10847        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10848        versionedLib.remove(version);
10849        if (versionedLib.size() <= 0) {
10850            mSharedLibraries.remove(name);
10851            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10852                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10853                        .getPackageName());
10854            }
10855        }
10856        return true;
10857    }
10858
10859    /**
10860     * Adds a scanned package to the system. When this method is finished, the package will
10861     * be available for query, resolution, etc...
10862     */
10863    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10864            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10865        final String pkgName = pkg.packageName;
10866        if (mCustomResolverComponentName != null &&
10867                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10868            setUpCustomResolverActivity(pkg);
10869        }
10870
10871        if (pkg.packageName.equals("android")) {
10872            synchronized (mPackages) {
10873                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10874                    // Set up information for our fall-back user intent resolution activity.
10875                    mPlatformPackage = pkg;
10876                    pkg.mVersionCode = mSdkVersion;
10877                    mAndroidApplication = pkg.applicationInfo;
10878                    if (!mResolverReplaced) {
10879                        mResolveActivity.applicationInfo = mAndroidApplication;
10880                        mResolveActivity.name = ResolverActivity.class.getName();
10881                        mResolveActivity.packageName = mAndroidApplication.packageName;
10882                        mResolveActivity.processName = "system:ui";
10883                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10884                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10885                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10886                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10887                        mResolveActivity.exported = true;
10888                        mResolveActivity.enabled = true;
10889                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10890                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10891                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10892                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10893                                | ActivityInfo.CONFIG_ORIENTATION
10894                                | ActivityInfo.CONFIG_KEYBOARD
10895                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10896                        mResolveInfo.activityInfo = mResolveActivity;
10897                        mResolveInfo.priority = 0;
10898                        mResolveInfo.preferredOrder = 0;
10899                        mResolveInfo.match = 0;
10900                        mResolveComponentName = new ComponentName(
10901                                mAndroidApplication.packageName, mResolveActivity.name);
10902                    }
10903                }
10904            }
10905        }
10906
10907        ArrayList<PackageParser.Package> clientLibPkgs = null;
10908        // writer
10909        synchronized (mPackages) {
10910            boolean hasStaticSharedLibs = false;
10911
10912            // Any app can add new static shared libraries
10913            if (pkg.staticSharedLibName != null) {
10914                // Static shared libs don't allow renaming as they have synthetic package
10915                // names to allow install of multiple versions, so use name from manifest.
10916                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10917                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10918                        pkg.manifestPackageName, pkg.mVersionCode)) {
10919                    hasStaticSharedLibs = true;
10920                } else {
10921                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10922                                + pkg.staticSharedLibName + " already exists; skipping");
10923                }
10924                // Static shared libs cannot be updated once installed since they
10925                // use synthetic package name which includes the version code, so
10926                // not need to update other packages's shared lib dependencies.
10927            }
10928
10929            if (!hasStaticSharedLibs
10930                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10931                // Only system apps can add new dynamic shared libraries.
10932                if (pkg.libraryNames != null) {
10933                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10934                        String name = pkg.libraryNames.get(i);
10935                        boolean allowed = false;
10936                        if (pkg.isUpdatedSystemApp()) {
10937                            // New library entries can only be added through the
10938                            // system image.  This is important to get rid of a lot
10939                            // of nasty edge cases: for example if we allowed a non-
10940                            // system update of the app to add a library, then uninstalling
10941                            // the update would make the library go away, and assumptions
10942                            // we made such as through app install filtering would now
10943                            // have allowed apps on the device which aren't compatible
10944                            // with it.  Better to just have the restriction here, be
10945                            // conservative, and create many fewer cases that can negatively
10946                            // impact the user experience.
10947                            final PackageSetting sysPs = mSettings
10948                                    .getDisabledSystemPkgLPr(pkg.packageName);
10949                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10950                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10951                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10952                                        allowed = true;
10953                                        break;
10954                                    }
10955                                }
10956                            }
10957                        } else {
10958                            allowed = true;
10959                        }
10960                        if (allowed) {
10961                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10962                                    SharedLibraryInfo.VERSION_UNDEFINED,
10963                                    SharedLibraryInfo.TYPE_DYNAMIC,
10964                                    pkg.packageName, pkg.mVersionCode)) {
10965                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10966                                        + name + " already exists; skipping");
10967                            }
10968                        } else {
10969                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10970                                    + name + " that is not declared on system image; skipping");
10971                        }
10972                    }
10973
10974                    if ((scanFlags & SCAN_BOOTING) == 0) {
10975                        // If we are not booting, we need to update any applications
10976                        // that are clients of our shared library.  If we are booting,
10977                        // this will all be done once the scan is complete.
10978                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10979                    }
10980                }
10981            }
10982        }
10983
10984        if ((scanFlags & SCAN_BOOTING) != 0) {
10985            // No apps can run during boot scan, so they don't need to be frozen
10986        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10987            // Caller asked to not kill app, so it's probably not frozen
10988        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10989            // Caller asked us to ignore frozen check for some reason; they
10990            // probably didn't know the package name
10991        } else {
10992            // We're doing major surgery on this package, so it better be frozen
10993            // right now to keep it from launching
10994            checkPackageFrozen(pkgName);
10995        }
10996
10997        // Also need to kill any apps that are dependent on the library.
10998        if (clientLibPkgs != null) {
10999            for (int i=0; i<clientLibPkgs.size(); i++) {
11000                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11001                killApplication(clientPkg.applicationInfo.packageName,
11002                        clientPkg.applicationInfo.uid, "update lib");
11003            }
11004        }
11005
11006        // writer
11007        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11008
11009        synchronized (mPackages) {
11010            // We don't expect installation to fail beyond this point
11011
11012            // Add the new setting to mSettings
11013            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11014            // Add the new setting to mPackages
11015            mPackages.put(pkg.applicationInfo.packageName, pkg);
11016            // Make sure we don't accidentally delete its data.
11017            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11018            while (iter.hasNext()) {
11019                PackageCleanItem item = iter.next();
11020                if (pkgName.equals(item.packageName)) {
11021                    iter.remove();
11022                }
11023            }
11024
11025            // Add the package's KeySets to the global KeySetManagerService
11026            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11027            ksms.addScannedPackageLPw(pkg);
11028
11029            int N = pkg.providers.size();
11030            StringBuilder r = null;
11031            int i;
11032            for (i=0; i<N; i++) {
11033                PackageParser.Provider p = pkg.providers.get(i);
11034                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11035                        p.info.processName);
11036                mProviders.addProvider(p);
11037                p.syncable = p.info.isSyncable;
11038                if (p.info.authority != null) {
11039                    String names[] = p.info.authority.split(";");
11040                    p.info.authority = null;
11041                    for (int j = 0; j < names.length; j++) {
11042                        if (j == 1 && p.syncable) {
11043                            // We only want the first authority for a provider to possibly be
11044                            // syncable, so if we already added this provider using a different
11045                            // authority clear the syncable flag. We copy the provider before
11046                            // changing it because the mProviders object contains a reference
11047                            // to a provider that we don't want to change.
11048                            // Only do this for the second authority since the resulting provider
11049                            // object can be the same for all future authorities for this provider.
11050                            p = new PackageParser.Provider(p);
11051                            p.syncable = false;
11052                        }
11053                        if (!mProvidersByAuthority.containsKey(names[j])) {
11054                            mProvidersByAuthority.put(names[j], p);
11055                            if (p.info.authority == null) {
11056                                p.info.authority = names[j];
11057                            } else {
11058                                p.info.authority = p.info.authority + ";" + names[j];
11059                            }
11060                            if (DEBUG_PACKAGE_SCANNING) {
11061                                if (chatty)
11062                                    Log.d(TAG, "Registered content provider: " + names[j]
11063                                            + ", className = " + p.info.name + ", isSyncable = "
11064                                            + p.info.isSyncable);
11065                            }
11066                        } else {
11067                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11068                            Slog.w(TAG, "Skipping provider name " + names[j] +
11069                                    " (in package " + pkg.applicationInfo.packageName +
11070                                    "): name already used by "
11071                                    + ((other != null && other.getComponentName() != null)
11072                                            ? other.getComponentName().getPackageName() : "?"));
11073                        }
11074                    }
11075                }
11076                if (chatty) {
11077                    if (r == null) {
11078                        r = new StringBuilder(256);
11079                    } else {
11080                        r.append(' ');
11081                    }
11082                    r.append(p.info.name);
11083                }
11084            }
11085            if (r != null) {
11086                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11087            }
11088
11089            N = pkg.services.size();
11090            r = null;
11091            for (i=0; i<N; i++) {
11092                PackageParser.Service s = pkg.services.get(i);
11093                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11094                        s.info.processName);
11095                mServices.addService(s);
11096                if (chatty) {
11097                    if (r == null) {
11098                        r = new StringBuilder(256);
11099                    } else {
11100                        r.append(' ');
11101                    }
11102                    r.append(s.info.name);
11103                }
11104            }
11105            if (r != null) {
11106                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11107            }
11108
11109            N = pkg.receivers.size();
11110            r = null;
11111            for (i=0; i<N; i++) {
11112                PackageParser.Activity a = pkg.receivers.get(i);
11113                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11114                        a.info.processName);
11115                mReceivers.addActivity(a, "receiver");
11116                if (chatty) {
11117                    if (r == null) {
11118                        r = new StringBuilder(256);
11119                    } else {
11120                        r.append(' ');
11121                    }
11122                    r.append(a.info.name);
11123                }
11124            }
11125            if (r != null) {
11126                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11127            }
11128
11129            N = pkg.activities.size();
11130            r = null;
11131            for (i=0; i<N; i++) {
11132                PackageParser.Activity a = pkg.activities.get(i);
11133                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11134                        a.info.processName);
11135                mActivities.addActivity(a, "activity");
11136                if (chatty) {
11137                    if (r == null) {
11138                        r = new StringBuilder(256);
11139                    } else {
11140                        r.append(' ');
11141                    }
11142                    r.append(a.info.name);
11143                }
11144            }
11145            if (r != null) {
11146                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11147            }
11148
11149            N = pkg.permissionGroups.size();
11150            r = null;
11151            for (i=0; i<N; i++) {
11152                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11153                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11154                final String curPackageName = cur == null ? null : cur.info.packageName;
11155                // Dont allow ephemeral apps to define new permission groups.
11156                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11157                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11158                            + pg.info.packageName
11159                            + " ignored: instant apps cannot define new permission groups.");
11160                    continue;
11161                }
11162                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11163                if (cur == null || isPackageUpdate) {
11164                    mPermissionGroups.put(pg.info.name, pg);
11165                    if (chatty) {
11166                        if (r == null) {
11167                            r = new StringBuilder(256);
11168                        } else {
11169                            r.append(' ');
11170                        }
11171                        if (isPackageUpdate) {
11172                            r.append("UPD:");
11173                        }
11174                        r.append(pg.info.name);
11175                    }
11176                } else {
11177                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11178                            + pg.info.packageName + " ignored: original from "
11179                            + cur.info.packageName);
11180                    if (chatty) {
11181                        if (r == null) {
11182                            r = new StringBuilder(256);
11183                        } else {
11184                            r.append(' ');
11185                        }
11186                        r.append("DUP:");
11187                        r.append(pg.info.name);
11188                    }
11189                }
11190            }
11191            if (r != null) {
11192                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11193            }
11194
11195            N = pkg.permissions.size();
11196            r = null;
11197            for (i=0; i<N; i++) {
11198                PackageParser.Permission p = pkg.permissions.get(i);
11199
11200                // Dont allow ephemeral apps to define new permissions.
11201                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11202                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11203                            + p.info.packageName
11204                            + " ignored: instant apps cannot define new permissions.");
11205                    continue;
11206                }
11207
11208                // Assume by default that we did not install this permission into the system.
11209                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11210
11211                // Now that permission groups have a special meaning, we ignore permission
11212                // groups for legacy apps to prevent unexpected behavior. In particular,
11213                // permissions for one app being granted to someone just because they happen
11214                // to be in a group defined by another app (before this had no implications).
11215                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11216                    p.group = mPermissionGroups.get(p.info.group);
11217                    // Warn for a permission in an unknown group.
11218                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11219                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11220                                + p.info.packageName + " in an unknown group " + p.info.group);
11221                    }
11222                }
11223
11224                // TODO Move to PermissionManager once mPermissionTrees moves there.
11225//                        p.tree ? mSettings.mPermissionTrees
11226//                                : mSettings.mPermissions;
11227//                final BasePermission bp = BasePermission.createOrUpdate(
11228//                        permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees, chatty);
11229//                permissionMap.put(p.info.name, bp);
11230                if (p.tree) {
11231                    final ArrayMap<String, BasePermission> permissionMap =
11232                            mSettings.mPermissionTrees;
11233                    final BasePermission bp = BasePermission.createOrUpdate(
11234                            permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees,
11235                            chatty);
11236                    permissionMap.put(p.info.name, bp);
11237                } else {
11238                    final BasePermission bp = BasePermission.createOrUpdate(
11239                            (BasePermission) mPermissionManager.getPermissionTEMP(p.info.name),
11240                            p, pkg, mSettings.mPermissionTrees, chatty);
11241                    mPermissionManager.putPermissionTEMP(p.info.name, bp);
11242                }
11243            }
11244
11245            N = pkg.instrumentation.size();
11246            r = null;
11247            for (i=0; i<N; i++) {
11248                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11249                a.info.packageName = pkg.applicationInfo.packageName;
11250                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11251                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11252                a.info.splitNames = pkg.splitNames;
11253                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11254                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11255                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11256                a.info.dataDir = pkg.applicationInfo.dataDir;
11257                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11258                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11259                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11260                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11261                mInstrumentation.put(a.getComponentName(), a);
11262                if (chatty) {
11263                    if (r == null) {
11264                        r = new StringBuilder(256);
11265                    } else {
11266                        r.append(' ');
11267                    }
11268                    r.append(a.info.name);
11269                }
11270            }
11271            if (r != null) {
11272                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11273            }
11274
11275            if (pkg.protectedBroadcasts != null) {
11276                N = pkg.protectedBroadcasts.size();
11277                synchronized (mProtectedBroadcasts) {
11278                    for (i = 0; i < N; i++) {
11279                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11280                    }
11281                }
11282            }
11283        }
11284
11285        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11286    }
11287
11288    /**
11289     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11290     * is derived purely on the basis of the contents of {@code scanFile} and
11291     * {@code cpuAbiOverride}.
11292     *
11293     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11294     */
11295    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11296                                 String cpuAbiOverride, boolean extractLibs,
11297                                 File appLib32InstallDir)
11298            throws PackageManagerException {
11299        // Give ourselves some initial paths; we'll come back for another
11300        // pass once we've determined ABI below.
11301        setNativeLibraryPaths(pkg, appLib32InstallDir);
11302
11303        // We would never need to extract libs for forward-locked and external packages,
11304        // since the container service will do it for us. We shouldn't attempt to
11305        // extract libs from system app when it was not updated.
11306        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11307                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11308            extractLibs = false;
11309        }
11310
11311        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11312        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11313
11314        NativeLibraryHelper.Handle handle = null;
11315        try {
11316            handle = NativeLibraryHelper.Handle.create(pkg);
11317            // TODO(multiArch): This can be null for apps that didn't go through the
11318            // usual installation process. We can calculate it again, like we
11319            // do during install time.
11320            //
11321            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11322            // unnecessary.
11323            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11324
11325            // Null out the abis so that they can be recalculated.
11326            pkg.applicationInfo.primaryCpuAbi = null;
11327            pkg.applicationInfo.secondaryCpuAbi = null;
11328            if (isMultiArch(pkg.applicationInfo)) {
11329                // Warn if we've set an abiOverride for multi-lib packages..
11330                // By definition, we need to copy both 32 and 64 bit libraries for
11331                // such packages.
11332                if (pkg.cpuAbiOverride != null
11333                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11334                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11335                }
11336
11337                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11338                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11339                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11340                    if (extractLibs) {
11341                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11342                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11343                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11344                                useIsaSpecificSubdirs);
11345                    } else {
11346                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11347                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11348                    }
11349                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11350                }
11351
11352                // Shared library native code should be in the APK zip aligned
11353                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11354                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11355                            "Shared library native lib extraction not supported");
11356                }
11357
11358                maybeThrowExceptionForMultiArchCopy(
11359                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11360
11361                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11362                    if (extractLibs) {
11363                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11364                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11365                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11366                                useIsaSpecificSubdirs);
11367                    } else {
11368                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11369                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11370                    }
11371                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11372                }
11373
11374                maybeThrowExceptionForMultiArchCopy(
11375                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11376
11377                if (abi64 >= 0) {
11378                    // Shared library native libs should be in the APK zip aligned
11379                    if (extractLibs && pkg.isLibrary()) {
11380                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11381                                "Shared library native lib extraction not supported");
11382                    }
11383                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11384                }
11385
11386                if (abi32 >= 0) {
11387                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11388                    if (abi64 >= 0) {
11389                        if (pkg.use32bitAbi) {
11390                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11391                            pkg.applicationInfo.primaryCpuAbi = abi;
11392                        } else {
11393                            pkg.applicationInfo.secondaryCpuAbi = abi;
11394                        }
11395                    } else {
11396                        pkg.applicationInfo.primaryCpuAbi = abi;
11397                    }
11398                }
11399            } else {
11400                String[] abiList = (cpuAbiOverride != null) ?
11401                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11402
11403                // Enable gross and lame hacks for apps that are built with old
11404                // SDK tools. We must scan their APKs for renderscript bitcode and
11405                // not launch them if it's present. Don't bother checking on devices
11406                // that don't have 64 bit support.
11407                boolean needsRenderScriptOverride = false;
11408                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11409                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11410                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11411                    needsRenderScriptOverride = true;
11412                }
11413
11414                final int copyRet;
11415                if (extractLibs) {
11416                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11417                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11418                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11419                } else {
11420                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11421                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11422                }
11423                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11424
11425                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11426                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11427                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11428                }
11429
11430                if (copyRet >= 0) {
11431                    // Shared libraries that have native libs must be multi-architecture
11432                    if (pkg.isLibrary()) {
11433                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11434                                "Shared library with native libs must be multiarch");
11435                    }
11436                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11437                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11438                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11439                } else if (needsRenderScriptOverride) {
11440                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11441                }
11442            }
11443        } catch (IOException ioe) {
11444            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11445        } finally {
11446            IoUtils.closeQuietly(handle);
11447        }
11448
11449        // Now that we've calculated the ABIs and determined if it's an internal app,
11450        // we will go ahead and populate the nativeLibraryPath.
11451        setNativeLibraryPaths(pkg, appLib32InstallDir);
11452    }
11453
11454    /**
11455     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11456     * i.e, so that all packages can be run inside a single process if required.
11457     *
11458     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11459     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11460     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11461     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11462     * updating a package that belongs to a shared user.
11463     *
11464     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11465     * adds unnecessary complexity.
11466     */
11467    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11468            PackageParser.Package scannedPackage) {
11469        String requiredInstructionSet = null;
11470        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11471            requiredInstructionSet = VMRuntime.getInstructionSet(
11472                     scannedPackage.applicationInfo.primaryCpuAbi);
11473        }
11474
11475        PackageSetting requirer = null;
11476        for (PackageSetting ps : packagesForUser) {
11477            // If packagesForUser contains scannedPackage, we skip it. This will happen
11478            // when scannedPackage is an update of an existing package. Without this check,
11479            // we will never be able to change the ABI of any package belonging to a shared
11480            // user, even if it's compatible with other packages.
11481            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11482                if (ps.primaryCpuAbiString == null) {
11483                    continue;
11484                }
11485
11486                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11487                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11488                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11489                    // this but there's not much we can do.
11490                    String errorMessage = "Instruction set mismatch, "
11491                            + ((requirer == null) ? "[caller]" : requirer)
11492                            + " requires " + requiredInstructionSet + " whereas " + ps
11493                            + " requires " + instructionSet;
11494                    Slog.w(TAG, errorMessage);
11495                }
11496
11497                if (requiredInstructionSet == null) {
11498                    requiredInstructionSet = instructionSet;
11499                    requirer = ps;
11500                }
11501            }
11502        }
11503
11504        if (requiredInstructionSet != null) {
11505            String adjustedAbi;
11506            if (requirer != null) {
11507                // requirer != null implies that either scannedPackage was null or that scannedPackage
11508                // did not require an ABI, in which case we have to adjust scannedPackage to match
11509                // the ABI of the set (which is the same as requirer's ABI)
11510                adjustedAbi = requirer.primaryCpuAbiString;
11511                if (scannedPackage != null) {
11512                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11513                }
11514            } else {
11515                // requirer == null implies that we're updating all ABIs in the set to
11516                // match scannedPackage.
11517                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11518            }
11519
11520            for (PackageSetting ps : packagesForUser) {
11521                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11522                    if (ps.primaryCpuAbiString != null) {
11523                        continue;
11524                    }
11525
11526                    ps.primaryCpuAbiString = adjustedAbi;
11527                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11528                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11529                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11530                        if (DEBUG_ABI_SELECTION) {
11531                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11532                                    + " (requirer="
11533                                    + (requirer != null ? requirer.pkg : "null")
11534                                    + ", scannedPackage="
11535                                    + (scannedPackage != null ? scannedPackage : "null")
11536                                    + ")");
11537                        }
11538                        try {
11539                            mInstaller.rmdex(ps.codePathString,
11540                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11541                        } catch (InstallerException ignored) {
11542                        }
11543                    }
11544                }
11545            }
11546        }
11547    }
11548
11549    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11550        synchronized (mPackages) {
11551            mResolverReplaced = true;
11552            // Set up information for custom user intent resolution activity.
11553            mResolveActivity.applicationInfo = pkg.applicationInfo;
11554            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11555            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11556            mResolveActivity.processName = pkg.applicationInfo.packageName;
11557            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11558            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11559                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11560            mResolveActivity.theme = 0;
11561            mResolveActivity.exported = true;
11562            mResolveActivity.enabled = true;
11563            mResolveInfo.activityInfo = mResolveActivity;
11564            mResolveInfo.priority = 0;
11565            mResolveInfo.preferredOrder = 0;
11566            mResolveInfo.match = 0;
11567            mResolveComponentName = mCustomResolverComponentName;
11568            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11569                    mResolveComponentName);
11570        }
11571    }
11572
11573    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11574        if (installerActivity == null) {
11575            if (DEBUG_EPHEMERAL) {
11576                Slog.d(TAG, "Clear ephemeral installer activity");
11577            }
11578            mInstantAppInstallerActivity = null;
11579            return;
11580        }
11581
11582        if (DEBUG_EPHEMERAL) {
11583            Slog.d(TAG, "Set ephemeral installer activity: "
11584                    + installerActivity.getComponentName());
11585        }
11586        // Set up information for ephemeral installer activity
11587        mInstantAppInstallerActivity = installerActivity;
11588        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11589                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11590        mInstantAppInstallerActivity.exported = true;
11591        mInstantAppInstallerActivity.enabled = true;
11592        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11593        mInstantAppInstallerInfo.priority = 0;
11594        mInstantAppInstallerInfo.preferredOrder = 1;
11595        mInstantAppInstallerInfo.isDefault = true;
11596        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11597                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11598    }
11599
11600    private static String calculateBundledApkRoot(final String codePathString) {
11601        final File codePath = new File(codePathString);
11602        final File codeRoot;
11603        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11604            codeRoot = Environment.getRootDirectory();
11605        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11606            codeRoot = Environment.getOemDirectory();
11607        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11608            codeRoot = Environment.getVendorDirectory();
11609        } else {
11610            // Unrecognized code path; take its top real segment as the apk root:
11611            // e.g. /something/app/blah.apk => /something
11612            try {
11613                File f = codePath.getCanonicalFile();
11614                File parent = f.getParentFile();    // non-null because codePath is a file
11615                File tmp;
11616                while ((tmp = parent.getParentFile()) != null) {
11617                    f = parent;
11618                    parent = tmp;
11619                }
11620                codeRoot = f;
11621                Slog.w(TAG, "Unrecognized code path "
11622                        + codePath + " - using " + codeRoot);
11623            } catch (IOException e) {
11624                // Can't canonicalize the code path -- shenanigans?
11625                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11626                return Environment.getRootDirectory().getPath();
11627            }
11628        }
11629        return codeRoot.getPath();
11630    }
11631
11632    /**
11633     * Derive and set the location of native libraries for the given package,
11634     * which varies depending on where and how the package was installed.
11635     */
11636    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11637        final ApplicationInfo info = pkg.applicationInfo;
11638        final String codePath = pkg.codePath;
11639        final File codeFile = new File(codePath);
11640        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11641        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11642
11643        info.nativeLibraryRootDir = null;
11644        info.nativeLibraryRootRequiresIsa = false;
11645        info.nativeLibraryDir = null;
11646        info.secondaryNativeLibraryDir = null;
11647
11648        if (isApkFile(codeFile)) {
11649            // Monolithic install
11650            if (bundledApp) {
11651                // If "/system/lib64/apkname" exists, assume that is the per-package
11652                // native library directory to use; otherwise use "/system/lib/apkname".
11653                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11654                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11655                        getPrimaryInstructionSet(info));
11656
11657                // This is a bundled system app so choose the path based on the ABI.
11658                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11659                // is just the default path.
11660                final String apkName = deriveCodePathName(codePath);
11661                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11662                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11663                        apkName).getAbsolutePath();
11664
11665                if (info.secondaryCpuAbi != null) {
11666                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11667                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11668                            secondaryLibDir, apkName).getAbsolutePath();
11669                }
11670            } else if (asecApp) {
11671                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11672                        .getAbsolutePath();
11673            } else {
11674                final String apkName = deriveCodePathName(codePath);
11675                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11676                        .getAbsolutePath();
11677            }
11678
11679            info.nativeLibraryRootRequiresIsa = false;
11680            info.nativeLibraryDir = info.nativeLibraryRootDir;
11681        } else {
11682            // Cluster install
11683            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11684            info.nativeLibraryRootRequiresIsa = true;
11685
11686            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11687                    getPrimaryInstructionSet(info)).getAbsolutePath();
11688
11689            if (info.secondaryCpuAbi != null) {
11690                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11691                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11692            }
11693        }
11694    }
11695
11696    /**
11697     * Calculate the abis and roots for a bundled app. These can uniquely
11698     * be determined from the contents of the system partition, i.e whether
11699     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11700     * of this information, and instead assume that the system was built
11701     * sensibly.
11702     */
11703    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11704                                           PackageSetting pkgSetting) {
11705        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11706
11707        // If "/system/lib64/apkname" exists, assume that is the per-package
11708        // native library directory to use; otherwise use "/system/lib/apkname".
11709        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11710        setBundledAppAbi(pkg, apkRoot, apkName);
11711        // pkgSetting might be null during rescan following uninstall of updates
11712        // to a bundled app, so accommodate that possibility.  The settings in
11713        // that case will be established later from the parsed package.
11714        //
11715        // If the settings aren't null, sync them up with what we've just derived.
11716        // note that apkRoot isn't stored in the package settings.
11717        if (pkgSetting != null) {
11718            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11719            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11720        }
11721    }
11722
11723    /**
11724     * Deduces the ABI of a bundled app and sets the relevant fields on the
11725     * parsed pkg object.
11726     *
11727     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11728     *        under which system libraries are installed.
11729     * @param apkName the name of the installed package.
11730     */
11731    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11732        final File codeFile = new File(pkg.codePath);
11733
11734        final boolean has64BitLibs;
11735        final boolean has32BitLibs;
11736        if (isApkFile(codeFile)) {
11737            // Monolithic install
11738            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11739            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11740        } else {
11741            // Cluster install
11742            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11743            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11744                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11745                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11746                has64BitLibs = (new File(rootDir, isa)).exists();
11747            } else {
11748                has64BitLibs = false;
11749            }
11750            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11751                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11752                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11753                has32BitLibs = (new File(rootDir, isa)).exists();
11754            } else {
11755                has32BitLibs = false;
11756            }
11757        }
11758
11759        if (has64BitLibs && !has32BitLibs) {
11760            // The package has 64 bit libs, but not 32 bit libs. Its primary
11761            // ABI should be 64 bit. We can safely assume here that the bundled
11762            // native libraries correspond to the most preferred ABI in the list.
11763
11764            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11765            pkg.applicationInfo.secondaryCpuAbi = null;
11766        } else if (has32BitLibs && !has64BitLibs) {
11767            // The package has 32 bit libs but not 64 bit libs. Its primary
11768            // ABI should be 32 bit.
11769
11770            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11771            pkg.applicationInfo.secondaryCpuAbi = null;
11772        } else if (has32BitLibs && has64BitLibs) {
11773            // The application has both 64 and 32 bit bundled libraries. We check
11774            // here that the app declares multiArch support, and warn if it doesn't.
11775            //
11776            // We will be lenient here and record both ABIs. The primary will be the
11777            // ABI that's higher on the list, i.e, a device that's configured to prefer
11778            // 64 bit apps will see a 64 bit primary ABI,
11779
11780            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11781                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11782            }
11783
11784            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11785                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11786                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11787            } else {
11788                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11789                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11790            }
11791        } else {
11792            pkg.applicationInfo.primaryCpuAbi = null;
11793            pkg.applicationInfo.secondaryCpuAbi = null;
11794        }
11795    }
11796
11797    private void killApplication(String pkgName, int appId, String reason) {
11798        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11799    }
11800
11801    private void killApplication(String pkgName, int appId, int userId, String reason) {
11802        // Request the ActivityManager to kill the process(only for existing packages)
11803        // so that we do not end up in a confused state while the user is still using the older
11804        // version of the application while the new one gets installed.
11805        final long token = Binder.clearCallingIdentity();
11806        try {
11807            IActivityManager am = ActivityManager.getService();
11808            if (am != null) {
11809                try {
11810                    am.killApplication(pkgName, appId, userId, reason);
11811                } catch (RemoteException e) {
11812                }
11813            }
11814        } finally {
11815            Binder.restoreCallingIdentity(token);
11816        }
11817    }
11818
11819    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11820        // Remove the parent package setting
11821        PackageSetting ps = (PackageSetting) pkg.mExtras;
11822        if (ps != null) {
11823            removePackageLI(ps, chatty);
11824        }
11825        // Remove the child package setting
11826        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11827        for (int i = 0; i < childCount; i++) {
11828            PackageParser.Package childPkg = pkg.childPackages.get(i);
11829            ps = (PackageSetting) childPkg.mExtras;
11830            if (ps != null) {
11831                removePackageLI(ps, chatty);
11832            }
11833        }
11834    }
11835
11836    void removePackageLI(PackageSetting ps, boolean chatty) {
11837        if (DEBUG_INSTALL) {
11838            if (chatty)
11839                Log.d(TAG, "Removing package " + ps.name);
11840        }
11841
11842        // writer
11843        synchronized (mPackages) {
11844            mPackages.remove(ps.name);
11845            final PackageParser.Package pkg = ps.pkg;
11846            if (pkg != null) {
11847                cleanPackageDataStructuresLILPw(pkg, chatty);
11848            }
11849        }
11850    }
11851
11852    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11853        if (DEBUG_INSTALL) {
11854            if (chatty)
11855                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11856        }
11857
11858        // writer
11859        synchronized (mPackages) {
11860            // Remove the parent package
11861            mPackages.remove(pkg.applicationInfo.packageName);
11862            cleanPackageDataStructuresLILPw(pkg, chatty);
11863
11864            // Remove the child packages
11865            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11866            for (int i = 0; i < childCount; i++) {
11867                PackageParser.Package childPkg = pkg.childPackages.get(i);
11868                mPackages.remove(childPkg.applicationInfo.packageName);
11869                cleanPackageDataStructuresLILPw(childPkg, chatty);
11870            }
11871        }
11872    }
11873
11874    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11875        int N = pkg.providers.size();
11876        StringBuilder r = null;
11877        int i;
11878        for (i=0; i<N; i++) {
11879            PackageParser.Provider p = pkg.providers.get(i);
11880            mProviders.removeProvider(p);
11881            if (p.info.authority == null) {
11882
11883                /* There was another ContentProvider with this authority when
11884                 * this app was installed so this authority is null,
11885                 * Ignore it as we don't have to unregister the provider.
11886                 */
11887                continue;
11888            }
11889            String names[] = p.info.authority.split(";");
11890            for (int j = 0; j < names.length; j++) {
11891                if (mProvidersByAuthority.get(names[j]) == p) {
11892                    mProvidersByAuthority.remove(names[j]);
11893                    if (DEBUG_REMOVE) {
11894                        if (chatty)
11895                            Log.d(TAG, "Unregistered content provider: " + names[j]
11896                                    + ", className = " + p.info.name + ", isSyncable = "
11897                                    + p.info.isSyncable);
11898                    }
11899                }
11900            }
11901            if (DEBUG_REMOVE && chatty) {
11902                if (r == null) {
11903                    r = new StringBuilder(256);
11904                } else {
11905                    r.append(' ');
11906                }
11907                r.append(p.info.name);
11908            }
11909        }
11910        if (r != null) {
11911            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11912        }
11913
11914        N = pkg.services.size();
11915        r = null;
11916        for (i=0; i<N; i++) {
11917            PackageParser.Service s = pkg.services.get(i);
11918            mServices.removeService(s);
11919            if (chatty) {
11920                if (r == null) {
11921                    r = new StringBuilder(256);
11922                } else {
11923                    r.append(' ');
11924                }
11925                r.append(s.info.name);
11926            }
11927        }
11928        if (r != null) {
11929            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11930        }
11931
11932        N = pkg.receivers.size();
11933        r = null;
11934        for (i=0; i<N; i++) {
11935            PackageParser.Activity a = pkg.receivers.get(i);
11936            mReceivers.removeActivity(a, "receiver");
11937            if (DEBUG_REMOVE && chatty) {
11938                if (r == null) {
11939                    r = new StringBuilder(256);
11940                } else {
11941                    r.append(' ');
11942                }
11943                r.append(a.info.name);
11944            }
11945        }
11946        if (r != null) {
11947            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11948        }
11949
11950        N = pkg.activities.size();
11951        r = null;
11952        for (i=0; i<N; i++) {
11953            PackageParser.Activity a = pkg.activities.get(i);
11954            mActivities.removeActivity(a, "activity");
11955            if (DEBUG_REMOVE && chatty) {
11956                if (r == null) {
11957                    r = new StringBuilder(256);
11958                } else {
11959                    r.append(' ');
11960                }
11961                r.append(a.info.name);
11962            }
11963        }
11964        if (r != null) {
11965            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11966        }
11967
11968        N = pkg.permissions.size();
11969        r = null;
11970        for (i=0; i<N; i++) {
11971            PackageParser.Permission p = pkg.permissions.get(i);
11972            BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(p.info.name);
11973            if (bp == null) {
11974                bp = mSettings.mPermissionTrees.get(p.info.name);
11975            }
11976            if (bp != null && bp.isPermission(p)) {
11977                bp.setPermission(null);
11978                if (DEBUG_REMOVE && chatty) {
11979                    if (r == null) {
11980                        r = new StringBuilder(256);
11981                    } else {
11982                        r.append(' ');
11983                    }
11984                    r.append(p.info.name);
11985                }
11986            }
11987            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11988                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11989                if (appOpPkgs != null) {
11990                    appOpPkgs.remove(pkg.packageName);
11991                }
11992            }
11993        }
11994        if (r != null) {
11995            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11996        }
11997
11998        N = pkg.requestedPermissions.size();
11999        r = null;
12000        for (i=0; i<N; i++) {
12001            String perm = pkg.requestedPermissions.get(i);
12002            if (mPermissionManager.isPermissionAppOp(perm)) {
12003                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12004                if (appOpPkgs != null) {
12005                    appOpPkgs.remove(pkg.packageName);
12006                    if (appOpPkgs.isEmpty()) {
12007                        mAppOpPermissionPackages.remove(perm);
12008                    }
12009                }
12010            }
12011        }
12012        if (r != null) {
12013            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12014        }
12015
12016        N = pkg.instrumentation.size();
12017        r = null;
12018        for (i=0; i<N; i++) {
12019            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12020            mInstrumentation.remove(a.getComponentName());
12021            if (DEBUG_REMOVE && chatty) {
12022                if (r == null) {
12023                    r = new StringBuilder(256);
12024                } else {
12025                    r.append(' ');
12026                }
12027                r.append(a.info.name);
12028            }
12029        }
12030        if (r != null) {
12031            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12032        }
12033
12034        r = null;
12035        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12036            // Only system apps can hold shared libraries.
12037            if (pkg.libraryNames != null) {
12038                for (i = 0; i < pkg.libraryNames.size(); i++) {
12039                    String name = pkg.libraryNames.get(i);
12040                    if (removeSharedLibraryLPw(name, 0)) {
12041                        if (DEBUG_REMOVE && chatty) {
12042                            if (r == null) {
12043                                r = new StringBuilder(256);
12044                            } else {
12045                                r.append(' ');
12046                            }
12047                            r.append(name);
12048                        }
12049                    }
12050                }
12051            }
12052        }
12053
12054        r = null;
12055
12056        // Any package can hold static shared libraries.
12057        if (pkg.staticSharedLibName != null) {
12058            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12059                if (DEBUG_REMOVE && chatty) {
12060                    if (r == null) {
12061                        r = new StringBuilder(256);
12062                    } else {
12063                        r.append(' ');
12064                    }
12065                    r.append(pkg.staticSharedLibName);
12066                }
12067            }
12068        }
12069
12070        if (r != null) {
12071            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12072        }
12073    }
12074
12075    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12076        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12077            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12078                return true;
12079            }
12080        }
12081        return false;
12082    }
12083
12084    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12085    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12086    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12087
12088    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12089        // Update the parent permissions
12090        updatePermissionsLPw(pkg.packageName, pkg, flags);
12091        // Update the child permissions
12092        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12093        for (int i = 0; i < childCount; i++) {
12094            PackageParser.Package childPkg = pkg.childPackages.get(i);
12095            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12096        }
12097    }
12098
12099    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12100            int flags) {
12101        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12102        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12103    }
12104
12105    private void updatePermissionsLPw(String changingPkg,
12106            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12107        // TODO: Most of the methods exposing BasePermission internals [source package name,
12108        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12109        // have package settings, we should make note of it elsewhere [map between
12110        // source package name and BasePermission] and cycle through that here. Then we
12111        // define a single method on BasePermission that takes a PackageSetting, changing
12112        // package name and a package.
12113        // NOTE: With this approach, we also don't need to tree trees differently than
12114        // normal permissions. Today, we need two separate loops because these BasePermission
12115        // objects are stored separately.
12116        // Make sure there are no dangling permission trees.
12117        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12118        while (it.hasNext()) {
12119            final BasePermission bp = it.next();
12120            if (bp.getSourcePackageSetting() == null) {
12121                // We may not yet have parsed the package, so just see if
12122                // we still know about its settings.
12123                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12124            }
12125            if (bp.getSourcePackageSetting() == null) {
12126                Slog.w(TAG, "Removing dangling permission tree: " + bp.getName()
12127                        + " from package " + bp.getSourcePackageName());
12128                it.remove();
12129            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12130                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12131                    Slog.i(TAG, "Removing old permission tree: " + bp.getName()
12132                            + " from package " + bp.getSourcePackageName());
12133                    flags |= UPDATE_PERMISSIONS_ALL;
12134                    it.remove();
12135                }
12136            }
12137        }
12138
12139        // Make sure all dynamic permissions have been assigned to a package,
12140        // and make sure there are no dangling permissions.
12141        final Iterator<BasePermission> permissionIter =
12142                mPermissionManager.getPermissionIteratorTEMP();
12143        while (permissionIter.hasNext()) {
12144            final BasePermission bp = permissionIter.next();
12145            if (bp.isDynamic()) {
12146                bp.updateDynamicPermission(mSettings.mPermissionTrees);
12147            }
12148            if (bp.getSourcePackageSetting() == null) {
12149                // We may not yet have parsed the package, so just see if
12150                // we still know about its settings.
12151                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12152            }
12153            if (bp.getSourcePackageSetting() == null) {
12154                Slog.w(TAG, "Removing dangling permission: " + bp.getName()
12155                        + " from package " + bp.getSourcePackageName());
12156                permissionIter.remove();
12157            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12158                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12159                    Slog.i(TAG, "Removing old permission: " + bp.getName()
12160                            + " from package " + bp.getSourcePackageName());
12161                    flags |= UPDATE_PERMISSIONS_ALL;
12162                    permissionIter.remove();
12163                }
12164            }
12165        }
12166
12167        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12168        // Now update the permissions for all packages, in particular
12169        // replace the granted permissions of the system packages.
12170        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12171            for (PackageParser.Package pkg : mPackages.values()) {
12172                if (pkg != pkgInfo) {
12173                    // Only replace for packages on requested volume
12174                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12175                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12176                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12177                    grantPermissionsLPw(pkg, replace, changingPkg);
12178                }
12179            }
12180        }
12181
12182        if (pkgInfo != null) {
12183            // Only replace for packages on requested volume
12184            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12185            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12186                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12187            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12188        }
12189        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12190    }
12191
12192    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12193            String packageOfInterest) {
12194        // IMPORTANT: There are two types of permissions: install and runtime.
12195        // Install time permissions are granted when the app is installed to
12196        // all device users and users added in the future. Runtime permissions
12197        // are granted at runtime explicitly to specific users. Normal and signature
12198        // protected permissions are install time permissions. Dangerous permissions
12199        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12200        // otherwise they are runtime permissions. This function does not manage
12201        // runtime permissions except for the case an app targeting Lollipop MR1
12202        // being upgraded to target a newer SDK, in which case dangerous permissions
12203        // are transformed from install time to runtime ones.
12204
12205        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12206        if (ps == null) {
12207            return;
12208        }
12209
12210        PermissionsState permissionsState = ps.getPermissionsState();
12211        PermissionsState origPermissions = permissionsState;
12212
12213        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12214
12215        boolean runtimePermissionsRevoked = false;
12216        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12217
12218        boolean changedInstallPermission = false;
12219
12220        if (replace) {
12221            ps.installPermissionsFixed = false;
12222            if (!ps.isSharedUser()) {
12223                origPermissions = new PermissionsState(permissionsState);
12224                permissionsState.reset();
12225            } else {
12226                // We need to know only about runtime permission changes since the
12227                // calling code always writes the install permissions state but
12228                // the runtime ones are written only if changed. The only cases of
12229                // changed runtime permissions here are promotion of an install to
12230                // runtime and revocation of a runtime from a shared user.
12231                changedRuntimePermissionUserIds =
12232                        mPermissionManager.revokeUnusedSharedUserPermissions(
12233                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12234                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12235                    runtimePermissionsRevoked = true;
12236                }
12237            }
12238        }
12239
12240        permissionsState.setGlobalGids(mGlobalGids);
12241
12242        final int N = pkg.requestedPermissions.size();
12243        for (int i=0; i<N; i++) {
12244            final String name = pkg.requestedPermissions.get(i);
12245            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12246            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12247                    >= Build.VERSION_CODES.M;
12248
12249            if (DEBUG_INSTALL) {
12250                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12251            }
12252
12253            if (bp == null || bp.getSourcePackageSetting() == null) {
12254                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12255                    if (DEBUG_PERMISSIONS) {
12256                        Slog.i(TAG, "Unknown permission " + name
12257                                + " in package " + pkg.packageName);
12258                    }
12259                }
12260                continue;
12261            }
12262
12263
12264            // Limit ephemeral apps to ephemeral allowed permissions.
12265            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12266                if (DEBUG_PERMISSIONS) {
12267                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12268                            + pkg.packageName);
12269                }
12270                continue;
12271            }
12272
12273            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12274                if (DEBUG_PERMISSIONS) {
12275                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12276                            + pkg.packageName);
12277                }
12278                continue;
12279            }
12280
12281            final String perm = bp.getName();
12282            boolean allowedSig = false;
12283            int grant = GRANT_DENIED;
12284
12285            // Keep track of app op permissions.
12286            if (bp.isAppOp()) {
12287                ArraySet<String> pkgs = mAppOpPermissionPackages.get(perm);
12288                if (pkgs == null) {
12289                    pkgs = new ArraySet<>();
12290                    mAppOpPermissionPackages.put(perm, pkgs);
12291                }
12292                pkgs.add(pkg.packageName);
12293            }
12294
12295            if (bp.isNormal()) {
12296                // For all apps normal permissions are install time ones.
12297                grant = GRANT_INSTALL;
12298            } else if (bp.isRuntime()) {
12299                // If a permission review is required for legacy apps we represent
12300                // their permissions as always granted runtime ones since we need
12301                // to keep the review required permission flag per user while an
12302                // install permission's state is shared across all users.
12303                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12304                    // For legacy apps dangerous permissions are install time ones.
12305                    grant = GRANT_INSTALL;
12306                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12307                    // For legacy apps that became modern, install becomes runtime.
12308                    grant = GRANT_UPGRADE;
12309                } else if (mPromoteSystemApps
12310                        && isSystemApp(ps)
12311                        && mExistingSystemPackages.contains(ps.name)) {
12312                    // For legacy system apps, install becomes runtime.
12313                    // We cannot check hasInstallPermission() for system apps since those
12314                    // permissions were granted implicitly and not persisted pre-M.
12315                    grant = GRANT_UPGRADE;
12316                } else {
12317                    // For modern apps keep runtime permissions unchanged.
12318                    grant = GRANT_RUNTIME;
12319                }
12320            } else if (bp.isSignature()) {
12321                // For all apps signature permissions are install time ones.
12322                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12323                if (allowedSig) {
12324                    grant = GRANT_INSTALL;
12325                }
12326            }
12327
12328            if (DEBUG_PERMISSIONS) {
12329                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12330            }
12331
12332            if (grant != GRANT_DENIED) {
12333                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12334                    // If this is an existing, non-system package, then
12335                    // we can't add any new permissions to it.
12336                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12337                        // Except...  if this is a permission that was added
12338                        // to the platform (note: need to only do this when
12339                        // updating the platform).
12340                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12341                            grant = GRANT_DENIED;
12342                        }
12343                    }
12344                }
12345
12346                switch (grant) {
12347                    case GRANT_INSTALL: {
12348                        // Revoke this as runtime permission to handle the case of
12349                        // a runtime permission being downgraded to an install one.
12350                        // Also in permission review mode we keep dangerous permissions
12351                        // for legacy apps
12352                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12353                            if (origPermissions.getRuntimePermissionState(
12354                                    perm, userId) != null) {
12355                                // Revoke the runtime permission and clear the flags.
12356                                origPermissions.revokeRuntimePermission(bp, userId);
12357                                origPermissions.updatePermissionFlags(bp, userId,
12358                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12359                                // If we revoked a permission permission, we have to write.
12360                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12361                                        changedRuntimePermissionUserIds, userId);
12362                            }
12363                        }
12364                        // Grant an install permission.
12365                        if (permissionsState.grantInstallPermission(bp) !=
12366                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12367                            changedInstallPermission = true;
12368                        }
12369                    } break;
12370
12371                    case GRANT_RUNTIME: {
12372                        // Grant previously granted runtime permissions.
12373                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12374                            PermissionState permissionState = origPermissions
12375                                    .getRuntimePermissionState(perm, userId);
12376                            int flags = permissionState != null
12377                                    ? permissionState.getFlags() : 0;
12378                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12379                                // Don't propagate the permission in a permission review mode if
12380                                // the former was revoked, i.e. marked to not propagate on upgrade.
12381                                // Note that in a permission review mode install permissions are
12382                                // represented as constantly granted runtime ones since we need to
12383                                // keep a per user state associated with the permission. Also the
12384                                // revoke on upgrade flag is no longer applicable and is reset.
12385                                final boolean revokeOnUpgrade = (flags & PackageManager
12386                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12387                                if (revokeOnUpgrade) {
12388                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12389                                    // Since we changed the flags, we have to write.
12390                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12391                                            changedRuntimePermissionUserIds, userId);
12392                                }
12393                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12394                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12395                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12396                                        // If we cannot put the permission as it was,
12397                                        // we have to write.
12398                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12399                                                changedRuntimePermissionUserIds, userId);
12400                                    }
12401                                }
12402
12403                                // If the app supports runtime permissions no need for a review.
12404                                if (mPermissionReviewRequired
12405                                        && appSupportsRuntimePermissions
12406                                        && (flags & PackageManager
12407                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12408                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12409                                    // Since we changed the flags, we have to write.
12410                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12411                                            changedRuntimePermissionUserIds, userId);
12412                                }
12413                            } else if (mPermissionReviewRequired
12414                                    && !appSupportsRuntimePermissions) {
12415                                // For legacy apps that need a permission review, every new
12416                                // runtime permission is granted but it is pending a review.
12417                                // We also need to review only platform defined runtime
12418                                // permissions as these are the only ones the platform knows
12419                                // how to disable the API to simulate revocation as legacy
12420                                // apps don't expect to run with revoked permissions.
12421                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12422                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12423                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12424                                        // We changed the flags, hence have to write.
12425                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12426                                                changedRuntimePermissionUserIds, userId);
12427                                    }
12428                                }
12429                                if (permissionsState.grantRuntimePermission(bp, userId)
12430                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12431                                    // We changed the permission, hence have to write.
12432                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12433                                            changedRuntimePermissionUserIds, userId);
12434                                }
12435                            }
12436                            // Propagate the permission flags.
12437                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12438                        }
12439                    } break;
12440
12441                    case GRANT_UPGRADE: {
12442                        // Grant runtime permissions for a previously held install permission.
12443                        PermissionState permissionState = origPermissions
12444                                .getInstallPermissionState(perm);
12445                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12446
12447                        if (origPermissions.revokeInstallPermission(bp)
12448                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12449                            // We will be transferring the permission flags, so clear them.
12450                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12451                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12452                            changedInstallPermission = true;
12453                        }
12454
12455                        // If the permission is not to be promoted to runtime we ignore it and
12456                        // also its other flags as they are not applicable to install permissions.
12457                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12458                            for (int userId : currentUserIds) {
12459                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12460                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12461                                    // Transfer the permission flags.
12462                                    permissionsState.updatePermissionFlags(bp, userId,
12463                                            flags, flags);
12464                                    // If we granted the permission, we have to write.
12465                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12466                                            changedRuntimePermissionUserIds, userId);
12467                                }
12468                            }
12469                        }
12470                    } break;
12471
12472                    default: {
12473                        if (packageOfInterest == null
12474                                || packageOfInterest.equals(pkg.packageName)) {
12475                            if (DEBUG_PERMISSIONS) {
12476                                Slog.i(TAG, "Not granting permission " + perm
12477                                        + " to package " + pkg.packageName
12478                                        + " because it was previously installed without");
12479                            }
12480                        }
12481                    } break;
12482                }
12483            } else {
12484                if (permissionsState.revokeInstallPermission(bp) !=
12485                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12486                    // Also drop the permission flags.
12487                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12488                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12489                    changedInstallPermission = true;
12490                    Slog.i(TAG, "Un-granting permission " + perm
12491                            + " from package " + pkg.packageName
12492                            + " (protectionLevel=" + bp.getProtectionLevel()
12493                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12494                            + ")");
12495                } else if (bp.isAppOp()) {
12496                    // Don't print warning for app op permissions, since it is fine for them
12497                    // not to be granted, there is a UI for the user to decide.
12498                    if (DEBUG_PERMISSIONS
12499                            && (packageOfInterest == null
12500                                    || packageOfInterest.equals(pkg.packageName))) {
12501                        Slog.i(TAG, "Not granting permission " + perm
12502                                + " to package " + pkg.packageName
12503                                + " (protectionLevel=" + bp.getProtectionLevel()
12504                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12505                                + ")");
12506                    }
12507                }
12508            }
12509        }
12510
12511        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12512                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12513            // This is the first that we have heard about this package, so the
12514            // permissions we have now selected are fixed until explicitly
12515            // changed.
12516            ps.installPermissionsFixed = true;
12517        }
12518
12519        // Persist the runtime permissions state for users with changes. If permissions
12520        // were revoked because no app in the shared user declares them we have to
12521        // write synchronously to avoid losing runtime permissions state.
12522        for (int userId : changedRuntimePermissionUserIds) {
12523            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12524        }
12525    }
12526
12527    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12528        boolean allowed = false;
12529        final int NP = PackageParser.NEW_PERMISSIONS.length;
12530        for (int ip=0; ip<NP; ip++) {
12531            final PackageParser.NewPermissionInfo npi
12532                    = PackageParser.NEW_PERMISSIONS[ip];
12533            if (npi.name.equals(perm)
12534                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12535                allowed = true;
12536                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12537                        + pkg.packageName);
12538                break;
12539            }
12540        }
12541        return allowed;
12542    }
12543
12544    /**
12545     * Determines whether a package is whitelisted for a particular privapp permission.
12546     *
12547     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12548     *
12549     * <p>This handles parent/child apps.
12550     */
12551    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12552        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12553                .getPrivAppPermissions(pkg.packageName);
12554        // Let's check if this package is whitelisted...
12555        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12556        // If it's not, we'll also tail-recurse to the parent.
12557        return whitelisted ||
12558                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12559    }
12560
12561    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12562            BasePermission bp, PermissionsState origPermissions) {
12563        boolean oemPermission = bp.isOEM();
12564        boolean privilegedPermission = bp.isPrivileged();
12565        boolean privappPermissionsDisable =
12566                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12567        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12568        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12569        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12570                && !platformPackage && platformPermission) {
12571            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12572                Slog.w(TAG, "Privileged permission " + perm + " for package "
12573                        + pkg.packageName + " - not in privapp-permissions whitelist");
12574                // Only report violations for apps on system image
12575                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12576                    // it's only a reportable violation if the permission isn't explicitly denied
12577                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12578                            .getPrivAppDenyPermissions(pkg.packageName);
12579                    final boolean permissionViolation =
12580                            deniedPermissions == null || !deniedPermissions.contains(perm);
12581                    if (permissionViolation) {
12582                        if (mPrivappPermissionsViolations == null) {
12583                            mPrivappPermissionsViolations = new ArraySet<>();
12584                        }
12585                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12586                    } else {
12587                        return false;
12588                    }
12589                }
12590                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12591                    return false;
12592                }
12593            }
12594        }
12595        boolean allowed = (compareSignatures(
12596                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12597                        == PackageManager.SIGNATURE_MATCH)
12598                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12599                        == PackageManager.SIGNATURE_MATCH);
12600        if (!allowed && (privilegedPermission || oemPermission)) {
12601            if (isSystemApp(pkg)) {
12602                // For updated system applications, a privileged/oem permission
12603                // is granted only if it had been defined by the original application.
12604                if (pkg.isUpdatedSystemApp()) {
12605                    final PackageSetting sysPs = mSettings
12606                            .getDisabledSystemPkgLPr(pkg.packageName);
12607                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12608                        // If the original was granted this permission, we take
12609                        // that grant decision as read and propagate it to the
12610                        // update.
12611                        if ((privilegedPermission && sysPs.isPrivileged())
12612                                || (oemPermission && sysPs.isOem()
12613                                        && canGrantOemPermission(sysPs, perm))) {
12614                            allowed = true;
12615                        }
12616                    } else {
12617                        // The system apk may have been updated with an older
12618                        // version of the one on the data partition, but which
12619                        // granted a new system permission that it didn't have
12620                        // before.  In this case we do want to allow the app to
12621                        // now get the new permission if the ancestral apk is
12622                        // privileged to get it.
12623                        if (sysPs != null && sysPs.pkg != null
12624                                && isPackageRequestingPermission(sysPs.pkg, perm)
12625                                && ((privilegedPermission && sysPs.isPrivileged())
12626                                        || (oemPermission && sysPs.isOem()
12627                                                && canGrantOemPermission(sysPs, perm)))) {
12628                            allowed = true;
12629                        }
12630                        // Also if a privileged parent package on the system image or any of
12631                        // its children requested a privileged/oem permission, the updated child
12632                        // packages can also get the permission.
12633                        if (pkg.parentPackage != null) {
12634                            final PackageSetting disabledSysParentPs = mSettings
12635                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12636                            final PackageParser.Package disabledSysParentPkg =
12637                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12638                                    ? null : disabledSysParentPs.pkg;
12639                            if (disabledSysParentPkg != null
12640                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12641                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12642                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12643                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12644                                    allowed = true;
12645                                } else if (disabledSysParentPkg.childPackages != null) {
12646                                    final int count = disabledSysParentPkg.childPackages.size();
12647                                    for (int i = 0; i < count; i++) {
12648                                        final PackageParser.Package disabledSysChildPkg =
12649                                                disabledSysParentPkg.childPackages.get(i);
12650                                        final PackageSetting disabledSysChildPs =
12651                                                mSettings.getDisabledSystemPkgLPr(
12652                                                        disabledSysChildPkg.packageName);
12653                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12654                                                && canGrantOemPermission(
12655                                                        disabledSysChildPs, perm)) {
12656                                            allowed = true;
12657                                            break;
12658                                        }
12659                                    }
12660                                }
12661                            }
12662                        }
12663                    }
12664                } else {
12665                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12666                            || (oemPermission && isOemApp(pkg)
12667                                    && canGrantOemPermission(
12668                                            mSettings.getPackageLPr(pkg.packageName), perm));
12669                }
12670            }
12671        }
12672        if (!allowed) {
12673            if (!allowed
12674                    && bp.isPre23()
12675                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12676                // If this was a previously normal/dangerous permission that got moved
12677                // to a system permission as part of the runtime permission redesign, then
12678                // we still want to blindly grant it to old apps.
12679                allowed = true;
12680            }
12681            if (!allowed && bp.isInstaller()
12682                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12683                // If this permission is to be granted to the system installer and
12684                // this app is an installer, then it gets the permission.
12685                allowed = true;
12686            }
12687            if (!allowed && bp.isVerifier()
12688                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12689                // If this permission is to be granted to the system verifier and
12690                // this app is a verifier, then it gets the permission.
12691                allowed = true;
12692            }
12693            if (!allowed && bp.isPreInstalled()
12694                    && isSystemApp(pkg)) {
12695                // Any pre-installed system app is allowed to get this permission.
12696                allowed = true;
12697            }
12698            if (!allowed && bp.isDevelopment()) {
12699                // For development permissions, a development permission
12700                // is granted only if it was already granted.
12701                allowed = origPermissions.hasInstallPermission(perm);
12702            }
12703            if (!allowed && bp.isSetup()
12704                    && pkg.packageName.equals(mSetupWizardPackage)) {
12705                // If this permission is to be granted to the system setup wizard and
12706                // this app is a setup wizard, then it gets the permission.
12707                allowed = true;
12708            }
12709        }
12710        return allowed;
12711    }
12712
12713    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12714        if (!ps.isOem()) {
12715            return false;
12716        }
12717        // all oem permissions must explicitly be granted or denied
12718        final Boolean granted =
12719                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12720        if (granted == null) {
12721            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12722                    + ps.name + " must be explicitly declared granted or not");
12723        }
12724        return Boolean.TRUE == granted;
12725    }
12726
12727    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12728        final int permCount = pkg.requestedPermissions.size();
12729        for (int j = 0; j < permCount; j++) {
12730            String requestedPermission = pkg.requestedPermissions.get(j);
12731            if (permission.equals(requestedPermission)) {
12732                return true;
12733            }
12734        }
12735        return false;
12736    }
12737
12738    final class ActivityIntentResolver
12739            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12740        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12741                boolean defaultOnly, int userId) {
12742            if (!sUserManager.exists(userId)) return null;
12743            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12744            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12745        }
12746
12747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12748                int userId) {
12749            if (!sUserManager.exists(userId)) return null;
12750            mFlags = flags;
12751            return super.queryIntent(intent, resolvedType,
12752                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12753                    userId);
12754        }
12755
12756        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12757                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12758            if (!sUserManager.exists(userId)) return null;
12759            if (packageActivities == null) {
12760                return null;
12761            }
12762            mFlags = flags;
12763            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12764            final int N = packageActivities.size();
12765            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12766                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12767
12768            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12769            for (int i = 0; i < N; ++i) {
12770                intentFilters = packageActivities.get(i).intents;
12771                if (intentFilters != null && intentFilters.size() > 0) {
12772                    PackageParser.ActivityIntentInfo[] array =
12773                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12774                    intentFilters.toArray(array);
12775                    listCut.add(array);
12776                }
12777            }
12778            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12779        }
12780
12781        /**
12782         * Finds a privileged activity that matches the specified activity names.
12783         */
12784        private PackageParser.Activity findMatchingActivity(
12785                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12786            for (PackageParser.Activity sysActivity : activityList) {
12787                if (sysActivity.info.name.equals(activityInfo.name)) {
12788                    return sysActivity;
12789                }
12790                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12791                    return sysActivity;
12792                }
12793                if (sysActivity.info.targetActivity != null) {
12794                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12795                        return sysActivity;
12796                    }
12797                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12798                        return sysActivity;
12799                    }
12800                }
12801            }
12802            return null;
12803        }
12804
12805        public class IterGenerator<E> {
12806            public Iterator<E> generate(ActivityIntentInfo info) {
12807                return null;
12808            }
12809        }
12810
12811        public class ActionIterGenerator extends IterGenerator<String> {
12812            @Override
12813            public Iterator<String> generate(ActivityIntentInfo info) {
12814                return info.actionsIterator();
12815            }
12816        }
12817
12818        public class CategoriesIterGenerator extends IterGenerator<String> {
12819            @Override
12820            public Iterator<String> generate(ActivityIntentInfo info) {
12821                return info.categoriesIterator();
12822            }
12823        }
12824
12825        public class SchemesIterGenerator extends IterGenerator<String> {
12826            @Override
12827            public Iterator<String> generate(ActivityIntentInfo info) {
12828                return info.schemesIterator();
12829            }
12830        }
12831
12832        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12833            @Override
12834            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12835                return info.authoritiesIterator();
12836            }
12837        }
12838
12839        /**
12840         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12841         * MODIFIED. Do not pass in a list that should not be changed.
12842         */
12843        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12844                IterGenerator<T> generator, Iterator<T> searchIterator) {
12845            // loop through the set of actions; every one must be found in the intent filter
12846            while (searchIterator.hasNext()) {
12847                // we must have at least one filter in the list to consider a match
12848                if (intentList.size() == 0) {
12849                    break;
12850                }
12851
12852                final T searchAction = searchIterator.next();
12853
12854                // loop through the set of intent filters
12855                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12856                while (intentIter.hasNext()) {
12857                    final ActivityIntentInfo intentInfo = intentIter.next();
12858                    boolean selectionFound = false;
12859
12860                    // loop through the intent filter's selection criteria; at least one
12861                    // of them must match the searched criteria
12862                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12863                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12864                        final T intentSelection = intentSelectionIter.next();
12865                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12866                            selectionFound = true;
12867                            break;
12868                        }
12869                    }
12870
12871                    // the selection criteria wasn't found in this filter's set; this filter
12872                    // is not a potential match
12873                    if (!selectionFound) {
12874                        intentIter.remove();
12875                    }
12876                }
12877            }
12878        }
12879
12880        private boolean isProtectedAction(ActivityIntentInfo filter) {
12881            final Iterator<String> actionsIter = filter.actionsIterator();
12882            while (actionsIter != null && actionsIter.hasNext()) {
12883                final String filterAction = actionsIter.next();
12884                if (PROTECTED_ACTIONS.contains(filterAction)) {
12885                    return true;
12886                }
12887            }
12888            return false;
12889        }
12890
12891        /**
12892         * Adjusts the priority of the given intent filter according to policy.
12893         * <p>
12894         * <ul>
12895         * <li>The priority for non privileged applications is capped to '0'</li>
12896         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12897         * <li>The priority for unbundled updates to privileged applications is capped to the
12898         *      priority defined on the system partition</li>
12899         * </ul>
12900         * <p>
12901         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12902         * allowed to obtain any priority on any action.
12903         */
12904        private void adjustPriority(
12905                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12906            // nothing to do; priority is fine as-is
12907            if (intent.getPriority() <= 0) {
12908                return;
12909            }
12910
12911            final ActivityInfo activityInfo = intent.activity.info;
12912            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12913
12914            final boolean privilegedApp =
12915                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12916            if (!privilegedApp) {
12917                // non-privileged applications can never define a priority >0
12918                if (DEBUG_FILTERS) {
12919                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12920                            + " package: " + applicationInfo.packageName
12921                            + " activity: " + intent.activity.className
12922                            + " origPrio: " + intent.getPriority());
12923                }
12924                intent.setPriority(0);
12925                return;
12926            }
12927
12928            if (systemActivities == null) {
12929                // the system package is not disabled; we're parsing the system partition
12930                if (isProtectedAction(intent)) {
12931                    if (mDeferProtectedFilters) {
12932                        // We can't deal with these just yet. No component should ever obtain a
12933                        // >0 priority for a protected actions, with ONE exception -- the setup
12934                        // wizard. The setup wizard, however, cannot be known until we're able to
12935                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12936                        // until all intent filters have been processed. Chicken, meet egg.
12937                        // Let the filter temporarily have a high priority and rectify the
12938                        // priorities after all system packages have been scanned.
12939                        mProtectedFilters.add(intent);
12940                        if (DEBUG_FILTERS) {
12941                            Slog.i(TAG, "Protected action; save for later;"
12942                                    + " package: " + applicationInfo.packageName
12943                                    + " activity: " + intent.activity.className
12944                                    + " origPrio: " + intent.getPriority());
12945                        }
12946                        return;
12947                    } else {
12948                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12949                            Slog.i(TAG, "No setup wizard;"
12950                                + " All protected intents capped to priority 0");
12951                        }
12952                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12953                            if (DEBUG_FILTERS) {
12954                                Slog.i(TAG, "Found setup wizard;"
12955                                    + " allow priority " + intent.getPriority() + ";"
12956                                    + " package: " + intent.activity.info.packageName
12957                                    + " activity: " + intent.activity.className
12958                                    + " priority: " + intent.getPriority());
12959                            }
12960                            // setup wizard gets whatever it wants
12961                            return;
12962                        }
12963                        if (DEBUG_FILTERS) {
12964                            Slog.i(TAG, "Protected action; cap priority to 0;"
12965                                    + " package: " + intent.activity.info.packageName
12966                                    + " activity: " + intent.activity.className
12967                                    + " origPrio: " + intent.getPriority());
12968                        }
12969                        intent.setPriority(0);
12970                        return;
12971                    }
12972                }
12973                // privileged apps on the system image get whatever priority they request
12974                return;
12975            }
12976
12977            // privileged app unbundled update ... try to find the same activity
12978            final PackageParser.Activity foundActivity =
12979                    findMatchingActivity(systemActivities, activityInfo);
12980            if (foundActivity == null) {
12981                // this is a new activity; it cannot obtain >0 priority
12982                if (DEBUG_FILTERS) {
12983                    Slog.i(TAG, "New activity; cap priority to 0;"
12984                            + " package: " + applicationInfo.packageName
12985                            + " activity: " + intent.activity.className
12986                            + " origPrio: " + intent.getPriority());
12987                }
12988                intent.setPriority(0);
12989                return;
12990            }
12991
12992            // found activity, now check for filter equivalence
12993
12994            // a shallow copy is enough; we modify the list, not its contents
12995            final List<ActivityIntentInfo> intentListCopy =
12996                    new ArrayList<>(foundActivity.intents);
12997            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12998
12999            // find matching action subsets
13000            final Iterator<String> actionsIterator = intent.actionsIterator();
13001            if (actionsIterator != null) {
13002                getIntentListSubset(
13003                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13004                if (intentListCopy.size() == 0) {
13005                    // no more intents to match; we're not equivalent
13006                    if (DEBUG_FILTERS) {
13007                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13008                                + " package: " + applicationInfo.packageName
13009                                + " activity: " + intent.activity.className
13010                                + " origPrio: " + intent.getPriority());
13011                    }
13012                    intent.setPriority(0);
13013                    return;
13014                }
13015            }
13016
13017            // find matching category subsets
13018            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13019            if (categoriesIterator != null) {
13020                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13021                        categoriesIterator);
13022                if (intentListCopy.size() == 0) {
13023                    // no more intents to match; we're not equivalent
13024                    if (DEBUG_FILTERS) {
13025                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13026                                + " package: " + applicationInfo.packageName
13027                                + " activity: " + intent.activity.className
13028                                + " origPrio: " + intent.getPriority());
13029                    }
13030                    intent.setPriority(0);
13031                    return;
13032                }
13033            }
13034
13035            // find matching schemes subsets
13036            final Iterator<String> schemesIterator = intent.schemesIterator();
13037            if (schemesIterator != null) {
13038                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13039                        schemesIterator);
13040                if (intentListCopy.size() == 0) {
13041                    // no more intents to match; we're not equivalent
13042                    if (DEBUG_FILTERS) {
13043                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13044                                + " package: " + applicationInfo.packageName
13045                                + " activity: " + intent.activity.className
13046                                + " origPrio: " + intent.getPriority());
13047                    }
13048                    intent.setPriority(0);
13049                    return;
13050                }
13051            }
13052
13053            // find matching authorities subsets
13054            final Iterator<IntentFilter.AuthorityEntry>
13055                    authoritiesIterator = intent.authoritiesIterator();
13056            if (authoritiesIterator != null) {
13057                getIntentListSubset(intentListCopy,
13058                        new AuthoritiesIterGenerator(),
13059                        authoritiesIterator);
13060                if (intentListCopy.size() == 0) {
13061                    // no more intents to match; we're not equivalent
13062                    if (DEBUG_FILTERS) {
13063                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13064                                + " package: " + applicationInfo.packageName
13065                                + " activity: " + intent.activity.className
13066                                + " origPrio: " + intent.getPriority());
13067                    }
13068                    intent.setPriority(0);
13069                    return;
13070                }
13071            }
13072
13073            // we found matching filter(s); app gets the max priority of all intents
13074            int cappedPriority = 0;
13075            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13076                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13077            }
13078            if (intent.getPriority() > cappedPriority) {
13079                if (DEBUG_FILTERS) {
13080                    Slog.i(TAG, "Found matching filter(s);"
13081                            + " cap priority to " + cappedPriority + ";"
13082                            + " package: " + applicationInfo.packageName
13083                            + " activity: " + intent.activity.className
13084                            + " origPrio: " + intent.getPriority());
13085                }
13086                intent.setPriority(cappedPriority);
13087                return;
13088            }
13089            // all this for nothing; the requested priority was <= what was on the system
13090        }
13091
13092        public final void addActivity(PackageParser.Activity a, String type) {
13093            mActivities.put(a.getComponentName(), a);
13094            if (DEBUG_SHOW_INFO)
13095                Log.v(
13096                TAG, "  " + type + " " +
13097                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13098            if (DEBUG_SHOW_INFO)
13099                Log.v(TAG, "    Class=" + a.info.name);
13100            final int NI = a.intents.size();
13101            for (int j=0; j<NI; j++) {
13102                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13103                if ("activity".equals(type)) {
13104                    final PackageSetting ps =
13105                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13106                    final List<PackageParser.Activity> systemActivities =
13107                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13108                    adjustPriority(systemActivities, intent);
13109                }
13110                if (DEBUG_SHOW_INFO) {
13111                    Log.v(TAG, "    IntentFilter:");
13112                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13113                }
13114                if (!intent.debugCheck()) {
13115                    Log.w(TAG, "==> For Activity " + a.info.name);
13116                }
13117                addFilter(intent);
13118            }
13119        }
13120
13121        public final void removeActivity(PackageParser.Activity a, String type) {
13122            mActivities.remove(a.getComponentName());
13123            if (DEBUG_SHOW_INFO) {
13124                Log.v(TAG, "  " + type + " "
13125                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13126                                : a.info.name) + ":");
13127                Log.v(TAG, "    Class=" + a.info.name);
13128            }
13129            final int NI = a.intents.size();
13130            for (int j=0; j<NI; j++) {
13131                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13132                if (DEBUG_SHOW_INFO) {
13133                    Log.v(TAG, "    IntentFilter:");
13134                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13135                }
13136                removeFilter(intent);
13137            }
13138        }
13139
13140        @Override
13141        protected boolean allowFilterResult(
13142                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13143            ActivityInfo filterAi = filter.activity.info;
13144            for (int i=dest.size()-1; i>=0; i--) {
13145                ActivityInfo destAi = dest.get(i).activityInfo;
13146                if (destAi.name == filterAi.name
13147                        && destAi.packageName == filterAi.packageName) {
13148                    return false;
13149                }
13150            }
13151            return true;
13152        }
13153
13154        @Override
13155        protected ActivityIntentInfo[] newArray(int size) {
13156            return new ActivityIntentInfo[size];
13157        }
13158
13159        @Override
13160        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13161            if (!sUserManager.exists(userId)) return true;
13162            PackageParser.Package p = filter.activity.owner;
13163            if (p != null) {
13164                PackageSetting ps = (PackageSetting)p.mExtras;
13165                if (ps != null) {
13166                    // System apps are never considered stopped for purposes of
13167                    // filtering, because there may be no way for the user to
13168                    // actually re-launch them.
13169                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13170                            && ps.getStopped(userId);
13171                }
13172            }
13173            return false;
13174        }
13175
13176        @Override
13177        protected boolean isPackageForFilter(String packageName,
13178                PackageParser.ActivityIntentInfo info) {
13179            return packageName.equals(info.activity.owner.packageName);
13180        }
13181
13182        @Override
13183        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13184                int match, int userId) {
13185            if (!sUserManager.exists(userId)) return null;
13186            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13187                return null;
13188            }
13189            final PackageParser.Activity activity = info.activity;
13190            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13191            if (ps == null) {
13192                return null;
13193            }
13194            final PackageUserState userState = ps.readUserState(userId);
13195            ActivityInfo ai =
13196                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13197            if (ai == null) {
13198                return null;
13199            }
13200            final boolean matchExplicitlyVisibleOnly =
13201                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13202            final boolean matchVisibleToInstantApp =
13203                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13204            final boolean componentVisible =
13205                    matchVisibleToInstantApp
13206                    && info.isVisibleToInstantApp()
13207                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13208            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13209            // throw out filters that aren't visible to ephemeral apps
13210            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13211                return null;
13212            }
13213            // throw out instant app filters if we're not explicitly requesting them
13214            if (!matchInstantApp && userState.instantApp) {
13215                return null;
13216            }
13217            // throw out instant app filters if updates are available; will trigger
13218            // instant app resolution
13219            if (userState.instantApp && ps.isUpdateAvailable()) {
13220                return null;
13221            }
13222            final ResolveInfo res = new ResolveInfo();
13223            res.activityInfo = ai;
13224            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13225                res.filter = info;
13226            }
13227            if (info != null) {
13228                res.handleAllWebDataURI = info.handleAllWebDataURI();
13229            }
13230            res.priority = info.getPriority();
13231            res.preferredOrder = activity.owner.mPreferredOrder;
13232            //System.out.println("Result: " + res.activityInfo.className +
13233            //                   " = " + res.priority);
13234            res.match = match;
13235            res.isDefault = info.hasDefault;
13236            res.labelRes = info.labelRes;
13237            res.nonLocalizedLabel = info.nonLocalizedLabel;
13238            if (userNeedsBadging(userId)) {
13239                res.noResourceId = true;
13240            } else {
13241                res.icon = info.icon;
13242            }
13243            res.iconResourceId = info.icon;
13244            res.system = res.activityInfo.applicationInfo.isSystemApp();
13245            res.isInstantAppAvailable = userState.instantApp;
13246            return res;
13247        }
13248
13249        @Override
13250        protected void sortResults(List<ResolveInfo> results) {
13251            Collections.sort(results, mResolvePrioritySorter);
13252        }
13253
13254        @Override
13255        protected void dumpFilter(PrintWriter out, String prefix,
13256                PackageParser.ActivityIntentInfo filter) {
13257            out.print(prefix); out.print(
13258                    Integer.toHexString(System.identityHashCode(filter.activity)));
13259                    out.print(' ');
13260                    filter.activity.printComponentShortName(out);
13261                    out.print(" filter ");
13262                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13263        }
13264
13265        @Override
13266        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13267            return filter.activity;
13268        }
13269
13270        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13271            PackageParser.Activity activity = (PackageParser.Activity)label;
13272            out.print(prefix); out.print(
13273                    Integer.toHexString(System.identityHashCode(activity)));
13274                    out.print(' ');
13275                    activity.printComponentShortName(out);
13276            if (count > 1) {
13277                out.print(" ("); out.print(count); out.print(" filters)");
13278            }
13279            out.println();
13280        }
13281
13282        // Keys are String (activity class name), values are Activity.
13283        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13284                = new ArrayMap<ComponentName, PackageParser.Activity>();
13285        private int mFlags;
13286    }
13287
13288    private final class ServiceIntentResolver
13289            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13290        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13291                boolean defaultOnly, int userId) {
13292            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13293            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13294        }
13295
13296        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13297                int userId) {
13298            if (!sUserManager.exists(userId)) return null;
13299            mFlags = flags;
13300            return super.queryIntent(intent, resolvedType,
13301                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13302                    userId);
13303        }
13304
13305        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13306                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13307            if (!sUserManager.exists(userId)) return null;
13308            if (packageServices == null) {
13309                return null;
13310            }
13311            mFlags = flags;
13312            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13313            final int N = packageServices.size();
13314            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13315                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13316
13317            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13318            for (int i = 0; i < N; ++i) {
13319                intentFilters = packageServices.get(i).intents;
13320                if (intentFilters != null && intentFilters.size() > 0) {
13321                    PackageParser.ServiceIntentInfo[] array =
13322                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13323                    intentFilters.toArray(array);
13324                    listCut.add(array);
13325                }
13326            }
13327            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13328        }
13329
13330        public final void addService(PackageParser.Service s) {
13331            mServices.put(s.getComponentName(), s);
13332            if (DEBUG_SHOW_INFO) {
13333                Log.v(TAG, "  "
13334                        + (s.info.nonLocalizedLabel != null
13335                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13336                Log.v(TAG, "    Class=" + s.info.name);
13337            }
13338            final int NI = s.intents.size();
13339            int j;
13340            for (j=0; j<NI; j++) {
13341                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13342                if (DEBUG_SHOW_INFO) {
13343                    Log.v(TAG, "    IntentFilter:");
13344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13345                }
13346                if (!intent.debugCheck()) {
13347                    Log.w(TAG, "==> For Service " + s.info.name);
13348                }
13349                addFilter(intent);
13350            }
13351        }
13352
13353        public final void removeService(PackageParser.Service s) {
13354            mServices.remove(s.getComponentName());
13355            if (DEBUG_SHOW_INFO) {
13356                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13357                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13358                Log.v(TAG, "    Class=" + s.info.name);
13359            }
13360            final int NI = s.intents.size();
13361            int j;
13362            for (j=0; j<NI; j++) {
13363                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13364                if (DEBUG_SHOW_INFO) {
13365                    Log.v(TAG, "    IntentFilter:");
13366                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13367                }
13368                removeFilter(intent);
13369            }
13370        }
13371
13372        @Override
13373        protected boolean allowFilterResult(
13374                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13375            ServiceInfo filterSi = filter.service.info;
13376            for (int i=dest.size()-1; i>=0; i--) {
13377                ServiceInfo destAi = dest.get(i).serviceInfo;
13378                if (destAi.name == filterSi.name
13379                        && destAi.packageName == filterSi.packageName) {
13380                    return false;
13381                }
13382            }
13383            return true;
13384        }
13385
13386        @Override
13387        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13388            return new PackageParser.ServiceIntentInfo[size];
13389        }
13390
13391        @Override
13392        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13393            if (!sUserManager.exists(userId)) return true;
13394            PackageParser.Package p = filter.service.owner;
13395            if (p != null) {
13396                PackageSetting ps = (PackageSetting)p.mExtras;
13397                if (ps != null) {
13398                    // System apps are never considered stopped for purposes of
13399                    // filtering, because there may be no way for the user to
13400                    // actually re-launch them.
13401                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13402                            && ps.getStopped(userId);
13403                }
13404            }
13405            return false;
13406        }
13407
13408        @Override
13409        protected boolean isPackageForFilter(String packageName,
13410                PackageParser.ServiceIntentInfo info) {
13411            return packageName.equals(info.service.owner.packageName);
13412        }
13413
13414        @Override
13415        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13416                int match, int userId) {
13417            if (!sUserManager.exists(userId)) return null;
13418            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13419            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13420                return null;
13421            }
13422            final PackageParser.Service service = info.service;
13423            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13424            if (ps == null) {
13425                return null;
13426            }
13427            final PackageUserState userState = ps.readUserState(userId);
13428            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13429                    userState, userId);
13430            if (si == null) {
13431                return null;
13432            }
13433            final boolean matchVisibleToInstantApp =
13434                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13435            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13436            // throw out filters that aren't visible to ephemeral apps
13437            if (matchVisibleToInstantApp
13438                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13439                return null;
13440            }
13441            // throw out ephemeral filters if we're not explicitly requesting them
13442            if (!isInstantApp && userState.instantApp) {
13443                return null;
13444            }
13445            // throw out instant app filters if updates are available; will trigger
13446            // instant app resolution
13447            if (userState.instantApp && ps.isUpdateAvailable()) {
13448                return null;
13449            }
13450            final ResolveInfo res = new ResolveInfo();
13451            res.serviceInfo = si;
13452            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13453                res.filter = filter;
13454            }
13455            res.priority = info.getPriority();
13456            res.preferredOrder = service.owner.mPreferredOrder;
13457            res.match = match;
13458            res.isDefault = info.hasDefault;
13459            res.labelRes = info.labelRes;
13460            res.nonLocalizedLabel = info.nonLocalizedLabel;
13461            res.icon = info.icon;
13462            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13463            return res;
13464        }
13465
13466        @Override
13467        protected void sortResults(List<ResolveInfo> results) {
13468            Collections.sort(results, mResolvePrioritySorter);
13469        }
13470
13471        @Override
13472        protected void dumpFilter(PrintWriter out, String prefix,
13473                PackageParser.ServiceIntentInfo filter) {
13474            out.print(prefix); out.print(
13475                    Integer.toHexString(System.identityHashCode(filter.service)));
13476                    out.print(' ');
13477                    filter.service.printComponentShortName(out);
13478                    out.print(" filter ");
13479                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13480        }
13481
13482        @Override
13483        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13484            return filter.service;
13485        }
13486
13487        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13488            PackageParser.Service service = (PackageParser.Service)label;
13489            out.print(prefix); out.print(
13490                    Integer.toHexString(System.identityHashCode(service)));
13491                    out.print(' ');
13492                    service.printComponentShortName(out);
13493            if (count > 1) {
13494                out.print(" ("); out.print(count); out.print(" filters)");
13495            }
13496            out.println();
13497        }
13498
13499//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13500//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13501//            final List<ResolveInfo> retList = Lists.newArrayList();
13502//            while (i.hasNext()) {
13503//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13504//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13505//                    retList.add(resolveInfo);
13506//                }
13507//            }
13508//            return retList;
13509//        }
13510
13511        // Keys are String (activity class name), values are Activity.
13512        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13513                = new ArrayMap<ComponentName, PackageParser.Service>();
13514        private int mFlags;
13515    }
13516
13517    private final class ProviderIntentResolver
13518            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13519        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13520                boolean defaultOnly, int userId) {
13521            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13522            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13523        }
13524
13525        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13526                int userId) {
13527            if (!sUserManager.exists(userId))
13528                return null;
13529            mFlags = flags;
13530            return super.queryIntent(intent, resolvedType,
13531                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13532                    userId);
13533        }
13534
13535        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13536                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13537            if (!sUserManager.exists(userId))
13538                return null;
13539            if (packageProviders == null) {
13540                return null;
13541            }
13542            mFlags = flags;
13543            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13544            final int N = packageProviders.size();
13545            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13546                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13547
13548            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13549            for (int i = 0; i < N; ++i) {
13550                intentFilters = packageProviders.get(i).intents;
13551                if (intentFilters != null && intentFilters.size() > 0) {
13552                    PackageParser.ProviderIntentInfo[] array =
13553                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13554                    intentFilters.toArray(array);
13555                    listCut.add(array);
13556                }
13557            }
13558            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13559        }
13560
13561        public final void addProvider(PackageParser.Provider p) {
13562            if (mProviders.containsKey(p.getComponentName())) {
13563                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13564                return;
13565            }
13566
13567            mProviders.put(p.getComponentName(), p);
13568            if (DEBUG_SHOW_INFO) {
13569                Log.v(TAG, "  "
13570                        + (p.info.nonLocalizedLabel != null
13571                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13572                Log.v(TAG, "    Class=" + p.info.name);
13573            }
13574            final int NI = p.intents.size();
13575            int j;
13576            for (j = 0; j < NI; j++) {
13577                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13578                if (DEBUG_SHOW_INFO) {
13579                    Log.v(TAG, "    IntentFilter:");
13580                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13581                }
13582                if (!intent.debugCheck()) {
13583                    Log.w(TAG, "==> For Provider " + p.info.name);
13584                }
13585                addFilter(intent);
13586            }
13587        }
13588
13589        public final void removeProvider(PackageParser.Provider p) {
13590            mProviders.remove(p.getComponentName());
13591            if (DEBUG_SHOW_INFO) {
13592                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13593                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13594                Log.v(TAG, "    Class=" + p.info.name);
13595            }
13596            final int NI = p.intents.size();
13597            int j;
13598            for (j = 0; j < NI; j++) {
13599                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13600                if (DEBUG_SHOW_INFO) {
13601                    Log.v(TAG, "    IntentFilter:");
13602                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13603                }
13604                removeFilter(intent);
13605            }
13606        }
13607
13608        @Override
13609        protected boolean allowFilterResult(
13610                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13611            ProviderInfo filterPi = filter.provider.info;
13612            for (int i = dest.size() - 1; i >= 0; i--) {
13613                ProviderInfo destPi = dest.get(i).providerInfo;
13614                if (destPi.name == filterPi.name
13615                        && destPi.packageName == filterPi.packageName) {
13616                    return false;
13617                }
13618            }
13619            return true;
13620        }
13621
13622        @Override
13623        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13624            return new PackageParser.ProviderIntentInfo[size];
13625        }
13626
13627        @Override
13628        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13629            if (!sUserManager.exists(userId))
13630                return true;
13631            PackageParser.Package p = filter.provider.owner;
13632            if (p != null) {
13633                PackageSetting ps = (PackageSetting) p.mExtras;
13634                if (ps != null) {
13635                    // System apps are never considered stopped for purposes of
13636                    // filtering, because there may be no way for the user to
13637                    // actually re-launch them.
13638                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13639                            && ps.getStopped(userId);
13640                }
13641            }
13642            return false;
13643        }
13644
13645        @Override
13646        protected boolean isPackageForFilter(String packageName,
13647                PackageParser.ProviderIntentInfo info) {
13648            return packageName.equals(info.provider.owner.packageName);
13649        }
13650
13651        @Override
13652        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13653                int match, int userId) {
13654            if (!sUserManager.exists(userId))
13655                return null;
13656            final PackageParser.ProviderIntentInfo info = filter;
13657            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13658                return null;
13659            }
13660            final PackageParser.Provider provider = info.provider;
13661            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13662            if (ps == null) {
13663                return null;
13664            }
13665            final PackageUserState userState = ps.readUserState(userId);
13666            final boolean matchVisibleToInstantApp =
13667                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13668            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13669            // throw out filters that aren't visible to instant applications
13670            if (matchVisibleToInstantApp
13671                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13672                return null;
13673            }
13674            // throw out instant application filters if we're not explicitly requesting them
13675            if (!isInstantApp && userState.instantApp) {
13676                return null;
13677            }
13678            // throw out instant application filters if updates are available; will trigger
13679            // instant application resolution
13680            if (userState.instantApp && ps.isUpdateAvailable()) {
13681                return null;
13682            }
13683            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13684                    userState, userId);
13685            if (pi == null) {
13686                return null;
13687            }
13688            final ResolveInfo res = new ResolveInfo();
13689            res.providerInfo = pi;
13690            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13691                res.filter = filter;
13692            }
13693            res.priority = info.getPriority();
13694            res.preferredOrder = provider.owner.mPreferredOrder;
13695            res.match = match;
13696            res.isDefault = info.hasDefault;
13697            res.labelRes = info.labelRes;
13698            res.nonLocalizedLabel = info.nonLocalizedLabel;
13699            res.icon = info.icon;
13700            res.system = res.providerInfo.applicationInfo.isSystemApp();
13701            return res;
13702        }
13703
13704        @Override
13705        protected void sortResults(List<ResolveInfo> results) {
13706            Collections.sort(results, mResolvePrioritySorter);
13707        }
13708
13709        @Override
13710        protected void dumpFilter(PrintWriter out, String prefix,
13711                PackageParser.ProviderIntentInfo filter) {
13712            out.print(prefix);
13713            out.print(
13714                    Integer.toHexString(System.identityHashCode(filter.provider)));
13715            out.print(' ');
13716            filter.provider.printComponentShortName(out);
13717            out.print(" filter ");
13718            out.println(Integer.toHexString(System.identityHashCode(filter)));
13719        }
13720
13721        @Override
13722        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13723            return filter.provider;
13724        }
13725
13726        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13727            PackageParser.Provider provider = (PackageParser.Provider)label;
13728            out.print(prefix); out.print(
13729                    Integer.toHexString(System.identityHashCode(provider)));
13730                    out.print(' ');
13731                    provider.printComponentShortName(out);
13732            if (count > 1) {
13733                out.print(" ("); out.print(count); out.print(" filters)");
13734            }
13735            out.println();
13736        }
13737
13738        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13739                = new ArrayMap<ComponentName, PackageParser.Provider>();
13740        private int mFlags;
13741    }
13742
13743    static final class EphemeralIntentResolver
13744            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13745        /**
13746         * The result that has the highest defined order. Ordering applies on a
13747         * per-package basis. Mapping is from package name to Pair of order and
13748         * EphemeralResolveInfo.
13749         * <p>
13750         * NOTE: This is implemented as a field variable for convenience and efficiency.
13751         * By having a field variable, we're able to track filter ordering as soon as
13752         * a non-zero order is defined. Otherwise, multiple loops across the result set
13753         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13754         * this needs to be contained entirely within {@link #filterResults}.
13755         */
13756        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13757
13758        @Override
13759        protected AuxiliaryResolveInfo[] newArray(int size) {
13760            return new AuxiliaryResolveInfo[size];
13761        }
13762
13763        @Override
13764        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13765            return true;
13766        }
13767
13768        @Override
13769        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13770                int userId) {
13771            if (!sUserManager.exists(userId)) {
13772                return null;
13773            }
13774            final String packageName = responseObj.resolveInfo.getPackageName();
13775            final Integer order = responseObj.getOrder();
13776            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13777                    mOrderResult.get(packageName);
13778            // ordering is enabled and this item's order isn't high enough
13779            if (lastOrderResult != null && lastOrderResult.first >= order) {
13780                return null;
13781            }
13782            final InstantAppResolveInfo res = responseObj.resolveInfo;
13783            if (order > 0) {
13784                // non-zero order, enable ordering
13785                mOrderResult.put(packageName, new Pair<>(order, res));
13786            }
13787            return responseObj;
13788        }
13789
13790        @Override
13791        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13792            // only do work if ordering is enabled [most of the time it won't be]
13793            if (mOrderResult.size() == 0) {
13794                return;
13795            }
13796            int resultSize = results.size();
13797            for (int i = 0; i < resultSize; i++) {
13798                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13799                final String packageName = info.getPackageName();
13800                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13801                if (savedInfo == null) {
13802                    // package doesn't having ordering
13803                    continue;
13804                }
13805                if (savedInfo.second == info) {
13806                    // circled back to the highest ordered item; remove from order list
13807                    mOrderResult.remove(packageName);
13808                    if (mOrderResult.size() == 0) {
13809                        // no more ordered items
13810                        break;
13811                    }
13812                    continue;
13813                }
13814                // item has a worse order, remove it from the result list
13815                results.remove(i);
13816                resultSize--;
13817                i--;
13818            }
13819        }
13820    }
13821
13822    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13823            new Comparator<ResolveInfo>() {
13824        public int compare(ResolveInfo r1, ResolveInfo r2) {
13825            int v1 = r1.priority;
13826            int v2 = r2.priority;
13827            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13828            if (v1 != v2) {
13829                return (v1 > v2) ? -1 : 1;
13830            }
13831            v1 = r1.preferredOrder;
13832            v2 = r2.preferredOrder;
13833            if (v1 != v2) {
13834                return (v1 > v2) ? -1 : 1;
13835            }
13836            if (r1.isDefault != r2.isDefault) {
13837                return r1.isDefault ? -1 : 1;
13838            }
13839            v1 = r1.match;
13840            v2 = r2.match;
13841            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13842            if (v1 != v2) {
13843                return (v1 > v2) ? -1 : 1;
13844            }
13845            if (r1.system != r2.system) {
13846                return r1.system ? -1 : 1;
13847            }
13848            if (r1.activityInfo != null) {
13849                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13850            }
13851            if (r1.serviceInfo != null) {
13852                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13853            }
13854            if (r1.providerInfo != null) {
13855                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13856            }
13857            return 0;
13858        }
13859    };
13860
13861    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13862            new Comparator<ProviderInfo>() {
13863        public int compare(ProviderInfo p1, ProviderInfo p2) {
13864            final int v1 = p1.initOrder;
13865            final int v2 = p2.initOrder;
13866            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13867        }
13868    };
13869
13870    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13871            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13872            final int[] userIds) {
13873        mHandler.post(new Runnable() {
13874            @Override
13875            public void run() {
13876                try {
13877                    final IActivityManager am = ActivityManager.getService();
13878                    if (am == null) return;
13879                    final int[] resolvedUserIds;
13880                    if (userIds == null) {
13881                        resolvedUserIds = am.getRunningUserIds();
13882                    } else {
13883                        resolvedUserIds = userIds;
13884                    }
13885                    for (int id : resolvedUserIds) {
13886                        final Intent intent = new Intent(action,
13887                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13888                        if (extras != null) {
13889                            intent.putExtras(extras);
13890                        }
13891                        if (targetPkg != null) {
13892                            intent.setPackage(targetPkg);
13893                        }
13894                        // Modify the UID when posting to other users
13895                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13896                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13897                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13898                            intent.putExtra(Intent.EXTRA_UID, uid);
13899                        }
13900                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13901                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13902                        if (DEBUG_BROADCASTS) {
13903                            RuntimeException here = new RuntimeException("here");
13904                            here.fillInStackTrace();
13905                            Slog.d(TAG, "Sending to user " + id + ": "
13906                                    + intent.toShortString(false, true, false, false)
13907                                    + " " + intent.getExtras(), here);
13908                        }
13909                        am.broadcastIntent(null, intent, null, finishedReceiver,
13910                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13911                                null, finishedReceiver != null, false, id);
13912                    }
13913                } catch (RemoteException ex) {
13914                }
13915            }
13916        });
13917    }
13918
13919    /**
13920     * Check if the external storage media is available. This is true if there
13921     * is a mounted external storage medium or if the external storage is
13922     * emulated.
13923     */
13924    private boolean isExternalMediaAvailable() {
13925        return mMediaMounted || Environment.isExternalStorageEmulated();
13926    }
13927
13928    @Override
13929    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13930        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13931            return null;
13932        }
13933        // writer
13934        synchronized (mPackages) {
13935            if (!isExternalMediaAvailable()) {
13936                // If the external storage is no longer mounted at this point,
13937                // the caller may not have been able to delete all of this
13938                // packages files and can not delete any more.  Bail.
13939                return null;
13940            }
13941            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13942            if (lastPackage != null) {
13943                pkgs.remove(lastPackage);
13944            }
13945            if (pkgs.size() > 0) {
13946                return pkgs.get(0);
13947            }
13948        }
13949        return null;
13950    }
13951
13952    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13953        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13954                userId, andCode ? 1 : 0, packageName);
13955        if (mSystemReady) {
13956            msg.sendToTarget();
13957        } else {
13958            if (mPostSystemReadyMessages == null) {
13959                mPostSystemReadyMessages = new ArrayList<>();
13960            }
13961            mPostSystemReadyMessages.add(msg);
13962        }
13963    }
13964
13965    void startCleaningPackages() {
13966        // reader
13967        if (!isExternalMediaAvailable()) {
13968            return;
13969        }
13970        synchronized (mPackages) {
13971            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13972                return;
13973            }
13974        }
13975        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13976        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13977        IActivityManager am = ActivityManager.getService();
13978        if (am != null) {
13979            int dcsUid = -1;
13980            synchronized (mPackages) {
13981                if (!mDefaultContainerWhitelisted) {
13982                    mDefaultContainerWhitelisted = true;
13983                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13984                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13985                }
13986            }
13987            try {
13988                if (dcsUid > 0) {
13989                    am.backgroundWhitelistUid(dcsUid);
13990                }
13991                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13992                        UserHandle.USER_SYSTEM);
13993            } catch (RemoteException e) {
13994            }
13995        }
13996    }
13997
13998    @Override
13999    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14000            int installFlags, String installerPackageName, int userId) {
14001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14002
14003        final int callingUid = Binder.getCallingUid();
14004        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14005                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14006
14007        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14008            try {
14009                if (observer != null) {
14010                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14011                }
14012            } catch (RemoteException re) {
14013            }
14014            return;
14015        }
14016
14017        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14018            installFlags |= PackageManager.INSTALL_FROM_ADB;
14019
14020        } else {
14021            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14022            // about installerPackageName.
14023
14024            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14025            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14026        }
14027
14028        UserHandle user;
14029        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14030            user = UserHandle.ALL;
14031        } else {
14032            user = new UserHandle(userId);
14033        }
14034
14035        // Only system components can circumvent runtime permissions when installing.
14036        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14037                && mContext.checkCallingOrSelfPermission(Manifest.permission
14038                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14039            throw new SecurityException("You need the "
14040                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14041                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14042        }
14043
14044        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14045                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14046            throw new IllegalArgumentException(
14047                    "New installs into ASEC containers no longer supported");
14048        }
14049
14050        final File originFile = new File(originPath);
14051        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14052
14053        final Message msg = mHandler.obtainMessage(INIT_COPY);
14054        final VerificationInfo verificationInfo = new VerificationInfo(
14055                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14056        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14057                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14058                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14059                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14060        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14061        msg.obj = params;
14062
14063        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14064                System.identityHashCode(msg.obj));
14065        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14066                System.identityHashCode(msg.obj));
14067
14068        mHandler.sendMessage(msg);
14069    }
14070
14071
14072    /**
14073     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14074     * it is acting on behalf on an enterprise or the user).
14075     *
14076     * Note that the ordering of the conditionals in this method is important. The checks we perform
14077     * are as follows, in this order:
14078     *
14079     * 1) If the install is being performed by a system app, we can trust the app to have set the
14080     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14081     *    what it is.
14082     * 2) If the install is being performed by a device or profile owner app, the install reason
14083     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14084     *    set the install reason correctly. If the app targets an older SDK version where install
14085     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14086     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14087     * 3) In all other cases, the install is being performed by a regular app that is neither part
14088     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14089     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14090     *    set to enterprise policy and if so, change it to unknown instead.
14091     */
14092    private int fixUpInstallReason(String installerPackageName, int installerUid,
14093            int installReason) {
14094        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14095                == PERMISSION_GRANTED) {
14096            // If the install is being performed by a system app, we trust that app to have set the
14097            // install reason correctly.
14098            return installReason;
14099        }
14100
14101        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14102            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14103        if (dpm != null) {
14104            ComponentName owner = null;
14105            try {
14106                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14107                if (owner == null) {
14108                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14109                }
14110            } catch (RemoteException e) {
14111            }
14112            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14113                // If the install is being performed by a device or profile owner, the install
14114                // reason should be enterprise policy.
14115                return PackageManager.INSTALL_REASON_POLICY;
14116            }
14117        }
14118
14119        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14120            // If the install is being performed by a regular app (i.e. neither system app nor
14121            // device or profile owner), we have no reason to believe that the app is acting on
14122            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14123            // change it to unknown instead.
14124            return PackageManager.INSTALL_REASON_UNKNOWN;
14125        }
14126
14127        // If the install is being performed by a regular app and the install reason was set to any
14128        // value but enterprise policy, leave the install reason unchanged.
14129        return installReason;
14130    }
14131
14132    void installStage(String packageName, File stagedDir, String stagedCid,
14133            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14134            String installerPackageName, int installerUid, UserHandle user,
14135            Certificate[][] certificates) {
14136        if (DEBUG_EPHEMERAL) {
14137            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14138                Slog.d(TAG, "Ephemeral install of " + packageName);
14139            }
14140        }
14141        final VerificationInfo verificationInfo = new VerificationInfo(
14142                sessionParams.originatingUri, sessionParams.referrerUri,
14143                sessionParams.originatingUid, installerUid);
14144
14145        final OriginInfo origin;
14146        if (stagedDir != null) {
14147            origin = OriginInfo.fromStagedFile(stagedDir);
14148        } else {
14149            origin = OriginInfo.fromStagedContainer(stagedCid);
14150        }
14151
14152        final Message msg = mHandler.obtainMessage(INIT_COPY);
14153        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14154                sessionParams.installReason);
14155        final InstallParams params = new InstallParams(origin, null, observer,
14156                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14157                verificationInfo, user, sessionParams.abiOverride,
14158                sessionParams.grantedRuntimePermissions, certificates, installReason);
14159        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14160        msg.obj = params;
14161
14162        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14163                System.identityHashCode(msg.obj));
14164        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14165                System.identityHashCode(msg.obj));
14166
14167        mHandler.sendMessage(msg);
14168    }
14169
14170    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14171            int userId) {
14172        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14173        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14174                false /*startReceiver*/, pkgSetting.appId, userId);
14175
14176        // Send a session commit broadcast
14177        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14178        info.installReason = pkgSetting.getInstallReason(userId);
14179        info.appPackageName = packageName;
14180        sendSessionCommitBroadcast(info, userId);
14181    }
14182
14183    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14184            boolean includeStopped, int appId, int... userIds) {
14185        if (ArrayUtils.isEmpty(userIds)) {
14186            return;
14187        }
14188        Bundle extras = new Bundle(1);
14189        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14190        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14191
14192        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14193                packageName, extras, 0, null, null, userIds);
14194        if (sendBootCompleted) {
14195            mHandler.post(() -> {
14196                        for (int userId : userIds) {
14197                            sendBootCompletedBroadcastToSystemApp(
14198                                    packageName, includeStopped, userId);
14199                        }
14200                    }
14201            );
14202        }
14203    }
14204
14205    /**
14206     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14207     * automatically without needing an explicit launch.
14208     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14209     */
14210    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14211            int userId) {
14212        // If user is not running, the app didn't miss any broadcast
14213        if (!mUserManagerInternal.isUserRunning(userId)) {
14214            return;
14215        }
14216        final IActivityManager am = ActivityManager.getService();
14217        try {
14218            // Deliver LOCKED_BOOT_COMPLETED first
14219            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14220                    .setPackage(packageName);
14221            if (includeStopped) {
14222                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14223            }
14224            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14225            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14226                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14227
14228            // Deliver BOOT_COMPLETED only if user is unlocked
14229            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14230                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14231                if (includeStopped) {
14232                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14233                }
14234                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14235                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14236            }
14237        } catch (RemoteException e) {
14238            throw e.rethrowFromSystemServer();
14239        }
14240    }
14241
14242    @Override
14243    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14244            int userId) {
14245        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14246        PackageSetting pkgSetting;
14247        final int callingUid = Binder.getCallingUid();
14248        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14249                true /* requireFullPermission */, true /* checkShell */,
14250                "setApplicationHiddenSetting for user " + userId);
14251
14252        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14253            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14254            return false;
14255        }
14256
14257        long callingId = Binder.clearCallingIdentity();
14258        try {
14259            boolean sendAdded = false;
14260            boolean sendRemoved = false;
14261            // writer
14262            synchronized (mPackages) {
14263                pkgSetting = mSettings.mPackages.get(packageName);
14264                if (pkgSetting == null) {
14265                    return false;
14266                }
14267                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14268                    return false;
14269                }
14270                // Do not allow "android" is being disabled
14271                if ("android".equals(packageName)) {
14272                    Slog.w(TAG, "Cannot hide package: android");
14273                    return false;
14274                }
14275                // Cannot hide static shared libs as they are considered
14276                // a part of the using app (emulating static linking). Also
14277                // static libs are installed always on internal storage.
14278                PackageParser.Package pkg = mPackages.get(packageName);
14279                if (pkg != null && pkg.staticSharedLibName != null) {
14280                    Slog.w(TAG, "Cannot hide package: " + packageName
14281                            + " providing static shared library: "
14282                            + pkg.staticSharedLibName);
14283                    return false;
14284                }
14285                // Only allow protected packages to hide themselves.
14286                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14287                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14288                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14289                    return false;
14290                }
14291
14292                if (pkgSetting.getHidden(userId) != hidden) {
14293                    pkgSetting.setHidden(hidden, userId);
14294                    mSettings.writePackageRestrictionsLPr(userId);
14295                    if (hidden) {
14296                        sendRemoved = true;
14297                    } else {
14298                        sendAdded = true;
14299                    }
14300                }
14301            }
14302            if (sendAdded) {
14303                sendPackageAddedForUser(packageName, pkgSetting, userId);
14304                return true;
14305            }
14306            if (sendRemoved) {
14307                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14308                        "hiding pkg");
14309                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14310                return true;
14311            }
14312        } finally {
14313            Binder.restoreCallingIdentity(callingId);
14314        }
14315        return false;
14316    }
14317
14318    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14319            int userId) {
14320        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14321        info.removedPackage = packageName;
14322        info.installerPackageName = pkgSetting.installerPackageName;
14323        info.removedUsers = new int[] {userId};
14324        info.broadcastUsers = new int[] {userId};
14325        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14326        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14327    }
14328
14329    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14330        if (pkgList.length > 0) {
14331            Bundle extras = new Bundle(1);
14332            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14333
14334            sendPackageBroadcast(
14335                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14336                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14337                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14338                    new int[] {userId});
14339        }
14340    }
14341
14342    /**
14343     * Returns true if application is not found or there was an error. Otherwise it returns
14344     * the hidden state of the package for the given user.
14345     */
14346    @Override
14347    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14349        final int callingUid = Binder.getCallingUid();
14350        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14351                true /* requireFullPermission */, false /* checkShell */,
14352                "getApplicationHidden for user " + userId);
14353        PackageSetting ps;
14354        long callingId = Binder.clearCallingIdentity();
14355        try {
14356            // writer
14357            synchronized (mPackages) {
14358                ps = mSettings.mPackages.get(packageName);
14359                if (ps == null) {
14360                    return true;
14361                }
14362                if (filterAppAccessLPr(ps, callingUid, userId)) {
14363                    return true;
14364                }
14365                return ps.getHidden(userId);
14366            }
14367        } finally {
14368            Binder.restoreCallingIdentity(callingId);
14369        }
14370    }
14371
14372    /**
14373     * @hide
14374     */
14375    @Override
14376    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14377            int installReason) {
14378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14379                null);
14380        PackageSetting pkgSetting;
14381        final int callingUid = Binder.getCallingUid();
14382        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14383                true /* requireFullPermission */, true /* checkShell */,
14384                "installExistingPackage for user " + userId);
14385        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14386            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14387        }
14388
14389        long callingId = Binder.clearCallingIdentity();
14390        try {
14391            boolean installed = false;
14392            final boolean instantApp =
14393                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14394            final boolean fullApp =
14395                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14396
14397            // writer
14398            synchronized (mPackages) {
14399                pkgSetting = mSettings.mPackages.get(packageName);
14400                if (pkgSetting == null) {
14401                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14402                }
14403                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14404                    // only allow the existing package to be used if it's installed as a full
14405                    // application for at least one user
14406                    boolean installAllowed = false;
14407                    for (int checkUserId : sUserManager.getUserIds()) {
14408                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14409                        if (installAllowed) {
14410                            break;
14411                        }
14412                    }
14413                    if (!installAllowed) {
14414                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14415                    }
14416                }
14417                if (!pkgSetting.getInstalled(userId)) {
14418                    pkgSetting.setInstalled(true, userId);
14419                    pkgSetting.setHidden(false, userId);
14420                    pkgSetting.setInstallReason(installReason, userId);
14421                    mSettings.writePackageRestrictionsLPr(userId);
14422                    mSettings.writeKernelMappingLPr(pkgSetting);
14423                    installed = true;
14424                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14425                    // upgrade app from instant to full; we don't allow app downgrade
14426                    installed = true;
14427                }
14428                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14429            }
14430
14431            if (installed) {
14432                if (pkgSetting.pkg != null) {
14433                    synchronized (mInstallLock) {
14434                        // We don't need to freeze for a brand new install
14435                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14436                    }
14437                }
14438                sendPackageAddedForUser(packageName, pkgSetting, userId);
14439                synchronized (mPackages) {
14440                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14441                }
14442            }
14443        } finally {
14444            Binder.restoreCallingIdentity(callingId);
14445        }
14446
14447        return PackageManager.INSTALL_SUCCEEDED;
14448    }
14449
14450    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14451            boolean instantApp, boolean fullApp) {
14452        // no state specified; do nothing
14453        if (!instantApp && !fullApp) {
14454            return;
14455        }
14456        if (userId != UserHandle.USER_ALL) {
14457            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14458                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14459            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14460                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14461            }
14462        } else {
14463            for (int currentUserId : sUserManager.getUserIds()) {
14464                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14465                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14466                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14467                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14468                }
14469            }
14470        }
14471    }
14472
14473    boolean isUserRestricted(int userId, String restrictionKey) {
14474        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14475        if (restrictions.getBoolean(restrictionKey, false)) {
14476            Log.w(TAG, "User is restricted: " + restrictionKey);
14477            return true;
14478        }
14479        return false;
14480    }
14481
14482    @Override
14483    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14484            int userId) {
14485        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14486        final int callingUid = Binder.getCallingUid();
14487        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14488                true /* requireFullPermission */, true /* checkShell */,
14489                "setPackagesSuspended for user " + userId);
14490
14491        if (ArrayUtils.isEmpty(packageNames)) {
14492            return packageNames;
14493        }
14494
14495        // List of package names for whom the suspended state has changed.
14496        List<String> changedPackages = new ArrayList<>(packageNames.length);
14497        // List of package names for whom the suspended state is not set as requested in this
14498        // method.
14499        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14500        long callingId = Binder.clearCallingIdentity();
14501        try {
14502            for (int i = 0; i < packageNames.length; i++) {
14503                String packageName = packageNames[i];
14504                boolean changed = false;
14505                final int appId;
14506                synchronized (mPackages) {
14507                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14508                    if (pkgSetting == null
14509                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14510                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14511                                + "\". Skipping suspending/un-suspending.");
14512                        unactionedPackages.add(packageName);
14513                        continue;
14514                    }
14515                    appId = pkgSetting.appId;
14516                    if (pkgSetting.getSuspended(userId) != suspended) {
14517                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14518                            unactionedPackages.add(packageName);
14519                            continue;
14520                        }
14521                        pkgSetting.setSuspended(suspended, userId);
14522                        mSettings.writePackageRestrictionsLPr(userId);
14523                        changed = true;
14524                        changedPackages.add(packageName);
14525                    }
14526                }
14527
14528                if (changed && suspended) {
14529                    killApplication(packageName, UserHandle.getUid(userId, appId),
14530                            "suspending package");
14531                }
14532            }
14533        } finally {
14534            Binder.restoreCallingIdentity(callingId);
14535        }
14536
14537        if (!changedPackages.isEmpty()) {
14538            sendPackagesSuspendedForUser(changedPackages.toArray(
14539                    new String[changedPackages.size()]), userId, suspended);
14540        }
14541
14542        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14543    }
14544
14545    @Override
14546    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14547        final int callingUid = Binder.getCallingUid();
14548        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14549                true /* requireFullPermission */, false /* checkShell */,
14550                "isPackageSuspendedForUser for user " + userId);
14551        synchronized (mPackages) {
14552            final PackageSetting ps = mSettings.mPackages.get(packageName);
14553            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14554                throw new IllegalArgumentException("Unknown target package: " + packageName);
14555            }
14556            return ps.getSuspended(userId);
14557        }
14558    }
14559
14560    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14561        if (isPackageDeviceAdmin(packageName, userId)) {
14562            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14563                    + "\": has an active device admin");
14564            return false;
14565        }
14566
14567        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14568        if (packageName.equals(activeLauncherPackageName)) {
14569            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14570                    + "\": contains the active launcher");
14571            return false;
14572        }
14573
14574        if (packageName.equals(mRequiredInstallerPackage)) {
14575            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14576                    + "\": required for package installation");
14577            return false;
14578        }
14579
14580        if (packageName.equals(mRequiredUninstallerPackage)) {
14581            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14582                    + "\": required for package uninstallation");
14583            return false;
14584        }
14585
14586        if (packageName.equals(mRequiredVerifierPackage)) {
14587            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14588                    + "\": required for package verification");
14589            return false;
14590        }
14591
14592        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14593            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14594                    + "\": is the default dialer");
14595            return false;
14596        }
14597
14598        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14599            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14600                    + "\": protected package");
14601            return false;
14602        }
14603
14604        // Cannot suspend static shared libs as they are considered
14605        // a part of the using app (emulating static linking). Also
14606        // static libs are installed always on internal storage.
14607        PackageParser.Package pkg = mPackages.get(packageName);
14608        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14609            Slog.w(TAG, "Cannot suspend package: " + packageName
14610                    + " providing static shared library: "
14611                    + pkg.staticSharedLibName);
14612            return false;
14613        }
14614
14615        return true;
14616    }
14617
14618    private String getActiveLauncherPackageName(int userId) {
14619        Intent intent = new Intent(Intent.ACTION_MAIN);
14620        intent.addCategory(Intent.CATEGORY_HOME);
14621        ResolveInfo resolveInfo = resolveIntent(
14622                intent,
14623                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14624                PackageManager.MATCH_DEFAULT_ONLY,
14625                userId);
14626
14627        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14628    }
14629
14630    private String getDefaultDialerPackageName(int userId) {
14631        synchronized (mPackages) {
14632            return mSettings.getDefaultDialerPackageNameLPw(userId);
14633        }
14634    }
14635
14636    @Override
14637    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14638        mContext.enforceCallingOrSelfPermission(
14639                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14640                "Only package verification agents can verify applications");
14641
14642        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14643        final PackageVerificationResponse response = new PackageVerificationResponse(
14644                verificationCode, Binder.getCallingUid());
14645        msg.arg1 = id;
14646        msg.obj = response;
14647        mHandler.sendMessage(msg);
14648    }
14649
14650    @Override
14651    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14652            long millisecondsToDelay) {
14653        mContext.enforceCallingOrSelfPermission(
14654                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14655                "Only package verification agents can extend verification timeouts");
14656
14657        final PackageVerificationState state = mPendingVerification.get(id);
14658        final PackageVerificationResponse response = new PackageVerificationResponse(
14659                verificationCodeAtTimeout, Binder.getCallingUid());
14660
14661        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14662            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14663        }
14664        if (millisecondsToDelay < 0) {
14665            millisecondsToDelay = 0;
14666        }
14667        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14668                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14669            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14670        }
14671
14672        if ((state != null) && !state.timeoutExtended()) {
14673            state.extendTimeout();
14674
14675            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14676            msg.arg1 = id;
14677            msg.obj = response;
14678            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14679        }
14680    }
14681
14682    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14683            int verificationCode, UserHandle user) {
14684        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14685        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14686        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14687        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14688        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14689
14690        mContext.sendBroadcastAsUser(intent, user,
14691                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14692    }
14693
14694    private ComponentName matchComponentForVerifier(String packageName,
14695            List<ResolveInfo> receivers) {
14696        ActivityInfo targetReceiver = null;
14697
14698        final int NR = receivers.size();
14699        for (int i = 0; i < NR; i++) {
14700            final ResolveInfo info = receivers.get(i);
14701            if (info.activityInfo == null) {
14702                continue;
14703            }
14704
14705            if (packageName.equals(info.activityInfo.packageName)) {
14706                targetReceiver = info.activityInfo;
14707                break;
14708            }
14709        }
14710
14711        if (targetReceiver == null) {
14712            return null;
14713        }
14714
14715        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14716    }
14717
14718    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14719            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14720        if (pkgInfo.verifiers.length == 0) {
14721            return null;
14722        }
14723
14724        final int N = pkgInfo.verifiers.length;
14725        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14726        for (int i = 0; i < N; i++) {
14727            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14728
14729            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14730                    receivers);
14731            if (comp == null) {
14732                continue;
14733            }
14734
14735            final int verifierUid = getUidForVerifier(verifierInfo);
14736            if (verifierUid == -1) {
14737                continue;
14738            }
14739
14740            if (DEBUG_VERIFY) {
14741                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14742                        + " with the correct signature");
14743            }
14744            sufficientVerifiers.add(comp);
14745            verificationState.addSufficientVerifier(verifierUid);
14746        }
14747
14748        return sufficientVerifiers;
14749    }
14750
14751    private int getUidForVerifier(VerifierInfo verifierInfo) {
14752        synchronized (mPackages) {
14753            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14754            if (pkg == null) {
14755                return -1;
14756            } else if (pkg.mSignatures.length != 1) {
14757                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14758                        + " has more than one signature; ignoring");
14759                return -1;
14760            }
14761
14762            /*
14763             * If the public key of the package's signature does not match
14764             * our expected public key, then this is a different package and
14765             * we should skip.
14766             */
14767
14768            final byte[] expectedPublicKey;
14769            try {
14770                final Signature verifierSig = pkg.mSignatures[0];
14771                final PublicKey publicKey = verifierSig.getPublicKey();
14772                expectedPublicKey = publicKey.getEncoded();
14773            } catch (CertificateException e) {
14774                return -1;
14775            }
14776
14777            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14778
14779            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14780                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14781                        + " does not have the expected public key; ignoring");
14782                return -1;
14783            }
14784
14785            return pkg.applicationInfo.uid;
14786        }
14787    }
14788
14789    @Override
14790    public void finishPackageInstall(int token, boolean didLaunch) {
14791        enforceSystemOrRoot("Only the system is allowed to finish installs");
14792
14793        if (DEBUG_INSTALL) {
14794            Slog.v(TAG, "BM finishing package install for " + token);
14795        }
14796        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14797
14798        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14799        mHandler.sendMessage(msg);
14800    }
14801
14802    /**
14803     * Get the verification agent timeout.  Used for both the APK verifier and the
14804     * intent filter verifier.
14805     *
14806     * @return verification timeout in milliseconds
14807     */
14808    private long getVerificationTimeout() {
14809        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14810                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14811                DEFAULT_VERIFICATION_TIMEOUT);
14812    }
14813
14814    /**
14815     * Get the default verification agent response code.
14816     *
14817     * @return default verification response code
14818     */
14819    private int getDefaultVerificationResponse(UserHandle user) {
14820        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14821            return PackageManager.VERIFICATION_REJECT;
14822        }
14823        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14824                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14825                DEFAULT_VERIFICATION_RESPONSE);
14826    }
14827
14828    /**
14829     * Check whether or not package verification has been enabled.
14830     *
14831     * @return true if verification should be performed
14832     */
14833    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14834        if (!DEFAULT_VERIFY_ENABLE) {
14835            return false;
14836        }
14837
14838        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14839
14840        // Check if installing from ADB
14841        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14842            // Do not run verification in a test harness environment
14843            if (ActivityManager.isRunningInTestHarness()) {
14844                return false;
14845            }
14846            if (ensureVerifyAppsEnabled) {
14847                return true;
14848            }
14849            // Check if the developer does not want package verification for ADB installs
14850            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14851                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14852                return false;
14853            }
14854        } else {
14855            // only when not installed from ADB, skip verification for instant apps when
14856            // the installer and verifier are the same.
14857            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14858                if (mInstantAppInstallerActivity != null
14859                        && mInstantAppInstallerActivity.packageName.equals(
14860                                mRequiredVerifierPackage)) {
14861                    try {
14862                        mContext.getSystemService(AppOpsManager.class)
14863                                .checkPackage(installerUid, mRequiredVerifierPackage);
14864                        if (DEBUG_VERIFY) {
14865                            Slog.i(TAG, "disable verification for instant app");
14866                        }
14867                        return false;
14868                    } catch (SecurityException ignore) { }
14869                }
14870            }
14871        }
14872
14873        if (ensureVerifyAppsEnabled) {
14874            return true;
14875        }
14876
14877        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14878                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14879    }
14880
14881    @Override
14882    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14883            throws RemoteException {
14884        mContext.enforceCallingOrSelfPermission(
14885                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14886                "Only intentfilter verification agents can verify applications");
14887
14888        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14889        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14890                Binder.getCallingUid(), verificationCode, failedDomains);
14891        msg.arg1 = id;
14892        msg.obj = response;
14893        mHandler.sendMessage(msg);
14894    }
14895
14896    @Override
14897    public int getIntentVerificationStatus(String packageName, int userId) {
14898        final int callingUid = Binder.getCallingUid();
14899        if (UserHandle.getUserId(callingUid) != userId) {
14900            mContext.enforceCallingOrSelfPermission(
14901                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14902                    "getIntentVerificationStatus" + userId);
14903        }
14904        if (getInstantAppPackageName(callingUid) != null) {
14905            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14906        }
14907        synchronized (mPackages) {
14908            final PackageSetting ps = mSettings.mPackages.get(packageName);
14909            if (ps == null
14910                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14911                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14912            }
14913            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14914        }
14915    }
14916
14917    @Override
14918    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14919        mContext.enforceCallingOrSelfPermission(
14920                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14921
14922        boolean result = false;
14923        synchronized (mPackages) {
14924            final PackageSetting ps = mSettings.mPackages.get(packageName);
14925            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14926                return false;
14927            }
14928            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14929        }
14930        if (result) {
14931            scheduleWritePackageRestrictionsLocked(userId);
14932        }
14933        return result;
14934    }
14935
14936    @Override
14937    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14938            String packageName) {
14939        final int callingUid = Binder.getCallingUid();
14940        if (getInstantAppPackageName(callingUid) != null) {
14941            return ParceledListSlice.emptyList();
14942        }
14943        synchronized (mPackages) {
14944            final PackageSetting ps = mSettings.mPackages.get(packageName);
14945            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14946                return ParceledListSlice.emptyList();
14947            }
14948            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14949        }
14950    }
14951
14952    @Override
14953    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14954        if (TextUtils.isEmpty(packageName)) {
14955            return ParceledListSlice.emptyList();
14956        }
14957        final int callingUid = Binder.getCallingUid();
14958        final int callingUserId = UserHandle.getUserId(callingUid);
14959        synchronized (mPackages) {
14960            PackageParser.Package pkg = mPackages.get(packageName);
14961            if (pkg == null || pkg.activities == null) {
14962                return ParceledListSlice.emptyList();
14963            }
14964            if (pkg.mExtras == null) {
14965                return ParceledListSlice.emptyList();
14966            }
14967            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14968            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14969                return ParceledListSlice.emptyList();
14970            }
14971            final int count = pkg.activities.size();
14972            ArrayList<IntentFilter> result = new ArrayList<>();
14973            for (int n=0; n<count; n++) {
14974                PackageParser.Activity activity = pkg.activities.get(n);
14975                if (activity.intents != null && activity.intents.size() > 0) {
14976                    result.addAll(activity.intents);
14977                }
14978            }
14979            return new ParceledListSlice<>(result);
14980        }
14981    }
14982
14983    @Override
14984    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14985        mContext.enforceCallingOrSelfPermission(
14986                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14987        if (UserHandle.getCallingUserId() != userId) {
14988            mContext.enforceCallingOrSelfPermission(
14989                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14990        }
14991
14992        synchronized (mPackages) {
14993            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14994            if (packageName != null) {
14995                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14996                        packageName, userId);
14997            }
14998            return result;
14999        }
15000    }
15001
15002    @Override
15003    public String getDefaultBrowserPackageName(int userId) {
15004        if (UserHandle.getCallingUserId() != userId) {
15005            mContext.enforceCallingOrSelfPermission(
15006                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15007        }
15008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15009            return null;
15010        }
15011        synchronized (mPackages) {
15012            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15013        }
15014    }
15015
15016    /**
15017     * Get the "allow unknown sources" setting.
15018     *
15019     * @return the current "allow unknown sources" setting
15020     */
15021    private int getUnknownSourcesSettings() {
15022        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15023                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15024                -1);
15025    }
15026
15027    @Override
15028    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15029        final int callingUid = Binder.getCallingUid();
15030        if (getInstantAppPackageName(callingUid) != null) {
15031            return;
15032        }
15033        // writer
15034        synchronized (mPackages) {
15035            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15036            if (targetPackageSetting == null
15037                    || filterAppAccessLPr(
15038                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15039                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15040            }
15041
15042            PackageSetting installerPackageSetting;
15043            if (installerPackageName != null) {
15044                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15045                if (installerPackageSetting == null) {
15046                    throw new IllegalArgumentException("Unknown installer package: "
15047                            + installerPackageName);
15048                }
15049            } else {
15050                installerPackageSetting = null;
15051            }
15052
15053            Signature[] callerSignature;
15054            Object obj = mSettings.getUserIdLPr(callingUid);
15055            if (obj != null) {
15056                if (obj instanceof SharedUserSetting) {
15057                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15058                } else if (obj instanceof PackageSetting) {
15059                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15060                } else {
15061                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15062                }
15063            } else {
15064                throw new SecurityException("Unknown calling UID: " + callingUid);
15065            }
15066
15067            // Verify: can't set installerPackageName to a package that is
15068            // not signed with the same cert as the caller.
15069            if (installerPackageSetting != null) {
15070                if (compareSignatures(callerSignature,
15071                        installerPackageSetting.signatures.mSignatures)
15072                        != PackageManager.SIGNATURE_MATCH) {
15073                    throw new SecurityException(
15074                            "Caller does not have same cert as new installer package "
15075                            + installerPackageName);
15076                }
15077            }
15078
15079            // Verify: if target already has an installer package, it must
15080            // be signed with the same cert as the caller.
15081            if (targetPackageSetting.installerPackageName != null) {
15082                PackageSetting setting = mSettings.mPackages.get(
15083                        targetPackageSetting.installerPackageName);
15084                // If the currently set package isn't valid, then it's always
15085                // okay to change it.
15086                if (setting != null) {
15087                    if (compareSignatures(callerSignature,
15088                            setting.signatures.mSignatures)
15089                            != PackageManager.SIGNATURE_MATCH) {
15090                        throw new SecurityException(
15091                                "Caller does not have same cert as old installer package "
15092                                + targetPackageSetting.installerPackageName);
15093                    }
15094                }
15095            }
15096
15097            // Okay!
15098            targetPackageSetting.installerPackageName = installerPackageName;
15099            if (installerPackageName != null) {
15100                mSettings.mInstallerPackages.add(installerPackageName);
15101            }
15102            scheduleWriteSettingsLocked();
15103        }
15104    }
15105
15106    @Override
15107    public void setApplicationCategoryHint(String packageName, int categoryHint,
15108            String callerPackageName) {
15109        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15110            throw new SecurityException("Instant applications don't have access to this method");
15111        }
15112        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15113                callerPackageName);
15114        synchronized (mPackages) {
15115            PackageSetting ps = mSettings.mPackages.get(packageName);
15116            if (ps == null) {
15117                throw new IllegalArgumentException("Unknown target package " + packageName);
15118            }
15119            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15120                throw new IllegalArgumentException("Unknown target package " + packageName);
15121            }
15122            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15123                throw new IllegalArgumentException("Calling package " + callerPackageName
15124                        + " is not installer for " + packageName);
15125            }
15126
15127            if (ps.categoryHint != categoryHint) {
15128                ps.categoryHint = categoryHint;
15129                scheduleWriteSettingsLocked();
15130            }
15131        }
15132    }
15133
15134    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15135        // Queue up an async operation since the package installation may take a little while.
15136        mHandler.post(new Runnable() {
15137            public void run() {
15138                mHandler.removeCallbacks(this);
15139                 // Result object to be returned
15140                PackageInstalledInfo res = new PackageInstalledInfo();
15141                res.setReturnCode(currentStatus);
15142                res.uid = -1;
15143                res.pkg = null;
15144                res.removedInfo = null;
15145                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15146                    args.doPreInstall(res.returnCode);
15147                    synchronized (mInstallLock) {
15148                        installPackageTracedLI(args, res);
15149                    }
15150                    args.doPostInstall(res.returnCode, res.uid);
15151                }
15152
15153                // A restore should be performed at this point if (a) the install
15154                // succeeded, (b) the operation is not an update, and (c) the new
15155                // package has not opted out of backup participation.
15156                final boolean update = res.removedInfo != null
15157                        && res.removedInfo.removedPackage != null;
15158                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15159                boolean doRestore = !update
15160                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15161
15162                // Set up the post-install work request bookkeeping.  This will be used
15163                // and cleaned up by the post-install event handling regardless of whether
15164                // there's a restore pass performed.  Token values are >= 1.
15165                int token;
15166                if (mNextInstallToken < 0) mNextInstallToken = 1;
15167                token = mNextInstallToken++;
15168
15169                PostInstallData data = new PostInstallData(args, res);
15170                mRunningInstalls.put(token, data);
15171                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15172
15173                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15174                    // Pass responsibility to the Backup Manager.  It will perform a
15175                    // restore if appropriate, then pass responsibility back to the
15176                    // Package Manager to run the post-install observer callbacks
15177                    // and broadcasts.
15178                    IBackupManager bm = IBackupManager.Stub.asInterface(
15179                            ServiceManager.getService(Context.BACKUP_SERVICE));
15180                    if (bm != null) {
15181                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15182                                + " to BM for possible restore");
15183                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15184                        try {
15185                            // TODO: http://b/22388012
15186                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15187                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15188                            } else {
15189                                doRestore = false;
15190                            }
15191                        } catch (RemoteException e) {
15192                            // can't happen; the backup manager is local
15193                        } catch (Exception e) {
15194                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15195                            doRestore = false;
15196                        }
15197                    } else {
15198                        Slog.e(TAG, "Backup Manager not found!");
15199                        doRestore = false;
15200                    }
15201                }
15202
15203                if (!doRestore) {
15204                    // No restore possible, or the Backup Manager was mysteriously not
15205                    // available -- just fire the post-install work request directly.
15206                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15207
15208                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15209
15210                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15211                    mHandler.sendMessage(msg);
15212                }
15213            }
15214        });
15215    }
15216
15217    /**
15218     * Callback from PackageSettings whenever an app is first transitioned out of the
15219     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15220     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15221     * here whether the app is the target of an ongoing install, and only send the
15222     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15223     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15224     * handling.
15225     */
15226    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15227        // Serialize this with the rest of the install-process message chain.  In the
15228        // restore-at-install case, this Runnable will necessarily run before the
15229        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15230        // are coherent.  In the non-restore case, the app has already completed install
15231        // and been launched through some other means, so it is not in a problematic
15232        // state for observers to see the FIRST_LAUNCH signal.
15233        mHandler.post(new Runnable() {
15234            @Override
15235            public void run() {
15236                for (int i = 0; i < mRunningInstalls.size(); i++) {
15237                    final PostInstallData data = mRunningInstalls.valueAt(i);
15238                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15239                        continue;
15240                    }
15241                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15242                        // right package; but is it for the right user?
15243                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15244                            if (userId == data.res.newUsers[uIndex]) {
15245                                if (DEBUG_BACKUP) {
15246                                    Slog.i(TAG, "Package " + pkgName
15247                                            + " being restored so deferring FIRST_LAUNCH");
15248                                }
15249                                return;
15250                            }
15251                        }
15252                    }
15253                }
15254                // didn't find it, so not being restored
15255                if (DEBUG_BACKUP) {
15256                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15257                }
15258                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15259            }
15260        });
15261    }
15262
15263    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15264        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15265                installerPkg, null, userIds);
15266    }
15267
15268    private abstract class HandlerParams {
15269        private static final int MAX_RETRIES = 4;
15270
15271        /**
15272         * Number of times startCopy() has been attempted and had a non-fatal
15273         * error.
15274         */
15275        private int mRetries = 0;
15276
15277        /** User handle for the user requesting the information or installation. */
15278        private final UserHandle mUser;
15279        String traceMethod;
15280        int traceCookie;
15281
15282        HandlerParams(UserHandle user) {
15283            mUser = user;
15284        }
15285
15286        UserHandle getUser() {
15287            return mUser;
15288        }
15289
15290        HandlerParams setTraceMethod(String traceMethod) {
15291            this.traceMethod = traceMethod;
15292            return this;
15293        }
15294
15295        HandlerParams setTraceCookie(int traceCookie) {
15296            this.traceCookie = traceCookie;
15297            return this;
15298        }
15299
15300        final boolean startCopy() {
15301            boolean res;
15302            try {
15303                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15304
15305                if (++mRetries > MAX_RETRIES) {
15306                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15307                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15308                    handleServiceError();
15309                    return false;
15310                } else {
15311                    handleStartCopy();
15312                    res = true;
15313                }
15314            } catch (RemoteException e) {
15315                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15316                mHandler.sendEmptyMessage(MCS_RECONNECT);
15317                res = false;
15318            }
15319            handleReturnCode();
15320            return res;
15321        }
15322
15323        final void serviceError() {
15324            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15325            handleServiceError();
15326            handleReturnCode();
15327        }
15328
15329        abstract void handleStartCopy() throws RemoteException;
15330        abstract void handleServiceError();
15331        abstract void handleReturnCode();
15332    }
15333
15334    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15335        for (File path : paths) {
15336            try {
15337                mcs.clearDirectory(path.getAbsolutePath());
15338            } catch (RemoteException e) {
15339            }
15340        }
15341    }
15342
15343    static class OriginInfo {
15344        /**
15345         * Location where install is coming from, before it has been
15346         * copied/renamed into place. This could be a single monolithic APK
15347         * file, or a cluster directory. This location may be untrusted.
15348         */
15349        final File file;
15350        final String cid;
15351
15352        /**
15353         * Flag indicating that {@link #file} or {@link #cid} has already been
15354         * staged, meaning downstream users don't need to defensively copy the
15355         * contents.
15356         */
15357        final boolean staged;
15358
15359        /**
15360         * Flag indicating that {@link #file} or {@link #cid} is an already
15361         * installed app that is being moved.
15362         */
15363        final boolean existing;
15364
15365        final String resolvedPath;
15366        final File resolvedFile;
15367
15368        static OriginInfo fromNothing() {
15369            return new OriginInfo(null, null, false, false);
15370        }
15371
15372        static OriginInfo fromUntrustedFile(File file) {
15373            return new OriginInfo(file, null, false, false);
15374        }
15375
15376        static OriginInfo fromExistingFile(File file) {
15377            return new OriginInfo(file, null, false, true);
15378        }
15379
15380        static OriginInfo fromStagedFile(File file) {
15381            return new OriginInfo(file, null, true, false);
15382        }
15383
15384        static OriginInfo fromStagedContainer(String cid) {
15385            return new OriginInfo(null, cid, true, false);
15386        }
15387
15388        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15389            this.file = file;
15390            this.cid = cid;
15391            this.staged = staged;
15392            this.existing = existing;
15393
15394            if (cid != null) {
15395                resolvedPath = PackageHelper.getSdDir(cid);
15396                resolvedFile = new File(resolvedPath);
15397            } else if (file != null) {
15398                resolvedPath = file.getAbsolutePath();
15399                resolvedFile = file;
15400            } else {
15401                resolvedPath = null;
15402                resolvedFile = null;
15403            }
15404        }
15405    }
15406
15407    static class MoveInfo {
15408        final int moveId;
15409        final String fromUuid;
15410        final String toUuid;
15411        final String packageName;
15412        final String dataAppName;
15413        final int appId;
15414        final String seinfo;
15415        final int targetSdkVersion;
15416
15417        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15418                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15419            this.moveId = moveId;
15420            this.fromUuid = fromUuid;
15421            this.toUuid = toUuid;
15422            this.packageName = packageName;
15423            this.dataAppName = dataAppName;
15424            this.appId = appId;
15425            this.seinfo = seinfo;
15426            this.targetSdkVersion = targetSdkVersion;
15427        }
15428    }
15429
15430    static class VerificationInfo {
15431        /** A constant used to indicate that a uid value is not present. */
15432        public static final int NO_UID = -1;
15433
15434        /** URI referencing where the package was downloaded from. */
15435        final Uri originatingUri;
15436
15437        /** HTTP referrer URI associated with the originatingURI. */
15438        final Uri referrer;
15439
15440        /** UID of the application that the install request originated from. */
15441        final int originatingUid;
15442
15443        /** UID of application requesting the install */
15444        final int installerUid;
15445
15446        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15447            this.originatingUri = originatingUri;
15448            this.referrer = referrer;
15449            this.originatingUid = originatingUid;
15450            this.installerUid = installerUid;
15451        }
15452    }
15453
15454    class InstallParams extends HandlerParams {
15455        final OriginInfo origin;
15456        final MoveInfo move;
15457        final IPackageInstallObserver2 observer;
15458        int installFlags;
15459        final String installerPackageName;
15460        final String volumeUuid;
15461        private InstallArgs mArgs;
15462        private int mRet;
15463        final String packageAbiOverride;
15464        final String[] grantedRuntimePermissions;
15465        final VerificationInfo verificationInfo;
15466        final Certificate[][] certificates;
15467        final int installReason;
15468
15469        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15470                int installFlags, String installerPackageName, String volumeUuid,
15471                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15472                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15473            super(user);
15474            this.origin = origin;
15475            this.move = move;
15476            this.observer = observer;
15477            this.installFlags = installFlags;
15478            this.installerPackageName = installerPackageName;
15479            this.volumeUuid = volumeUuid;
15480            this.verificationInfo = verificationInfo;
15481            this.packageAbiOverride = packageAbiOverride;
15482            this.grantedRuntimePermissions = grantedPermissions;
15483            this.certificates = certificates;
15484            this.installReason = installReason;
15485        }
15486
15487        @Override
15488        public String toString() {
15489            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15490                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15491        }
15492
15493        private int installLocationPolicy(PackageInfoLite pkgLite) {
15494            String packageName = pkgLite.packageName;
15495            int installLocation = pkgLite.installLocation;
15496            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15497            // reader
15498            synchronized (mPackages) {
15499                // Currently installed package which the new package is attempting to replace or
15500                // null if no such package is installed.
15501                PackageParser.Package installedPkg = mPackages.get(packageName);
15502                // Package which currently owns the data which the new package will own if installed.
15503                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15504                // will be null whereas dataOwnerPkg will contain information about the package
15505                // which was uninstalled while keeping its data.
15506                PackageParser.Package dataOwnerPkg = installedPkg;
15507                if (dataOwnerPkg  == null) {
15508                    PackageSetting ps = mSettings.mPackages.get(packageName);
15509                    if (ps != null) {
15510                        dataOwnerPkg = ps.pkg;
15511                    }
15512                }
15513
15514                if (dataOwnerPkg != null) {
15515                    // If installed, the package will get access to data left on the device by its
15516                    // predecessor. As a security measure, this is permited only if this is not a
15517                    // version downgrade or if the predecessor package is marked as debuggable and
15518                    // a downgrade is explicitly requested.
15519                    //
15520                    // On debuggable platform builds, downgrades are permitted even for
15521                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15522                    // not offer security guarantees and thus it's OK to disable some security
15523                    // mechanisms to make debugging/testing easier on those builds. However, even on
15524                    // debuggable builds downgrades of packages are permitted only if requested via
15525                    // installFlags. This is because we aim to keep the behavior of debuggable
15526                    // platform builds as close as possible to the behavior of non-debuggable
15527                    // platform builds.
15528                    final boolean downgradeRequested =
15529                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15530                    final boolean packageDebuggable =
15531                                (dataOwnerPkg.applicationInfo.flags
15532                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15533                    final boolean downgradePermitted =
15534                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15535                    if (!downgradePermitted) {
15536                        try {
15537                            checkDowngrade(dataOwnerPkg, pkgLite);
15538                        } catch (PackageManagerException e) {
15539                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15540                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15541                        }
15542                    }
15543                }
15544
15545                if (installedPkg != null) {
15546                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15547                        // Check for updated system application.
15548                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15549                            if (onSd) {
15550                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15551                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15552                            }
15553                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15554                        } else {
15555                            if (onSd) {
15556                                // Install flag overrides everything.
15557                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15558                            }
15559                            // If current upgrade specifies particular preference
15560                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15561                                // Application explicitly specified internal.
15562                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15563                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15564                                // App explictly prefers external. Let policy decide
15565                            } else {
15566                                // Prefer previous location
15567                                if (isExternal(installedPkg)) {
15568                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15569                                }
15570                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15571                            }
15572                        }
15573                    } else {
15574                        // Invalid install. Return error code
15575                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15576                    }
15577                }
15578            }
15579            // All the special cases have been taken care of.
15580            // Return result based on recommended install location.
15581            if (onSd) {
15582                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15583            }
15584            return pkgLite.recommendedInstallLocation;
15585        }
15586
15587        /*
15588         * Invoke remote method to get package information and install
15589         * location values. Override install location based on default
15590         * policy if needed and then create install arguments based
15591         * on the install location.
15592         */
15593        public void handleStartCopy() throws RemoteException {
15594            int ret = PackageManager.INSTALL_SUCCEEDED;
15595
15596            // If we're already staged, we've firmly committed to an install location
15597            if (origin.staged) {
15598                if (origin.file != null) {
15599                    installFlags |= PackageManager.INSTALL_INTERNAL;
15600                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15601                } else if (origin.cid != null) {
15602                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15603                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15604                } else {
15605                    throw new IllegalStateException("Invalid stage location");
15606                }
15607            }
15608
15609            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15610            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15611            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15612            PackageInfoLite pkgLite = null;
15613
15614            if (onInt && onSd) {
15615                // Check if both bits are set.
15616                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15617                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15618            } else if (onSd && ephemeral) {
15619                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15620                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15621            } else {
15622                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15623                        packageAbiOverride);
15624
15625                if (DEBUG_EPHEMERAL && ephemeral) {
15626                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15627                }
15628
15629                /*
15630                 * If we have too little free space, try to free cache
15631                 * before giving up.
15632                 */
15633                if (!origin.staged && pkgLite.recommendedInstallLocation
15634                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15635                    // TODO: focus freeing disk space on the target device
15636                    final StorageManager storage = StorageManager.from(mContext);
15637                    final long lowThreshold = storage.getStorageLowBytes(
15638                            Environment.getDataDirectory());
15639
15640                    final long sizeBytes = mContainerService.calculateInstalledSize(
15641                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15642
15643                    try {
15644                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15645                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15646                                installFlags, packageAbiOverride);
15647                    } catch (InstallerException e) {
15648                        Slog.w(TAG, "Failed to free cache", e);
15649                    }
15650
15651                    /*
15652                     * The cache free must have deleted the file we
15653                     * downloaded to install.
15654                     *
15655                     * TODO: fix the "freeCache" call to not delete
15656                     *       the file we care about.
15657                     */
15658                    if (pkgLite.recommendedInstallLocation
15659                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15660                        pkgLite.recommendedInstallLocation
15661                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15662                    }
15663                }
15664            }
15665
15666            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15667                int loc = pkgLite.recommendedInstallLocation;
15668                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15669                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15670                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15671                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15672                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15673                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15674                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15675                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15676                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15677                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15678                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15679                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15680                } else {
15681                    // Override with defaults if needed.
15682                    loc = installLocationPolicy(pkgLite);
15683                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15684                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15685                    } else if (!onSd && !onInt) {
15686                        // Override install location with flags
15687                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15688                            // Set the flag to install on external media.
15689                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15690                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15691                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15692                            if (DEBUG_EPHEMERAL) {
15693                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15694                            }
15695                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15696                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15697                                    |PackageManager.INSTALL_INTERNAL);
15698                        } else {
15699                            // Make sure the flag for installing on external
15700                            // media is unset
15701                            installFlags |= PackageManager.INSTALL_INTERNAL;
15702                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15703                        }
15704                    }
15705                }
15706            }
15707
15708            final InstallArgs args = createInstallArgs(this);
15709            mArgs = args;
15710
15711            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15712                // TODO: http://b/22976637
15713                // Apps installed for "all" users use the device owner to verify the app
15714                UserHandle verifierUser = getUser();
15715                if (verifierUser == UserHandle.ALL) {
15716                    verifierUser = UserHandle.SYSTEM;
15717                }
15718
15719                /*
15720                 * Determine if we have any installed package verifiers. If we
15721                 * do, then we'll defer to them to verify the packages.
15722                 */
15723                final int requiredUid = mRequiredVerifierPackage == null ? -1
15724                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15725                                verifierUser.getIdentifier());
15726                final int installerUid =
15727                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15728                if (!origin.existing && requiredUid != -1
15729                        && isVerificationEnabled(
15730                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15731                    final Intent verification = new Intent(
15732                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15733                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15734                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15735                            PACKAGE_MIME_TYPE);
15736                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15737
15738                    // Query all live verifiers based on current user state
15739                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15740                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15741                            false /*allowDynamicSplits*/);
15742
15743                    if (DEBUG_VERIFY) {
15744                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15745                                + verification.toString() + " with " + pkgLite.verifiers.length
15746                                + " optional verifiers");
15747                    }
15748
15749                    final int verificationId = mPendingVerificationToken++;
15750
15751                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15752
15753                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15754                            installerPackageName);
15755
15756                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15757                            installFlags);
15758
15759                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15760                            pkgLite.packageName);
15761
15762                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15763                            pkgLite.versionCode);
15764
15765                    if (verificationInfo != null) {
15766                        if (verificationInfo.originatingUri != null) {
15767                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15768                                    verificationInfo.originatingUri);
15769                        }
15770                        if (verificationInfo.referrer != null) {
15771                            verification.putExtra(Intent.EXTRA_REFERRER,
15772                                    verificationInfo.referrer);
15773                        }
15774                        if (verificationInfo.originatingUid >= 0) {
15775                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15776                                    verificationInfo.originatingUid);
15777                        }
15778                        if (verificationInfo.installerUid >= 0) {
15779                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15780                                    verificationInfo.installerUid);
15781                        }
15782                    }
15783
15784                    final PackageVerificationState verificationState = new PackageVerificationState(
15785                            requiredUid, args);
15786
15787                    mPendingVerification.append(verificationId, verificationState);
15788
15789                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15790                            receivers, verificationState);
15791
15792                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15793                    final long idleDuration = getVerificationTimeout();
15794
15795                    /*
15796                     * If any sufficient verifiers were listed in the package
15797                     * manifest, attempt to ask them.
15798                     */
15799                    if (sufficientVerifiers != null) {
15800                        final int N = sufficientVerifiers.size();
15801                        if (N == 0) {
15802                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15803                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15804                        } else {
15805                            for (int i = 0; i < N; i++) {
15806                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15807                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15808                                        verifierComponent.getPackageName(), idleDuration,
15809                                        verifierUser.getIdentifier(), false, "package verifier");
15810
15811                                final Intent sufficientIntent = new Intent(verification);
15812                                sufficientIntent.setComponent(verifierComponent);
15813                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15814                            }
15815                        }
15816                    }
15817
15818                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15819                            mRequiredVerifierPackage, receivers);
15820                    if (ret == PackageManager.INSTALL_SUCCEEDED
15821                            && mRequiredVerifierPackage != null) {
15822                        Trace.asyncTraceBegin(
15823                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15824                        /*
15825                         * Send the intent to the required verification agent,
15826                         * but only start the verification timeout after the
15827                         * target BroadcastReceivers have run.
15828                         */
15829                        verification.setComponent(requiredVerifierComponent);
15830                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15831                                mRequiredVerifierPackage, idleDuration,
15832                                verifierUser.getIdentifier(), false, "package verifier");
15833                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15834                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15835                                new BroadcastReceiver() {
15836                                    @Override
15837                                    public void onReceive(Context context, Intent intent) {
15838                                        final Message msg = mHandler
15839                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15840                                        msg.arg1 = verificationId;
15841                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15842                                    }
15843                                }, null, 0, null, null);
15844
15845                        /*
15846                         * We don't want the copy to proceed until verification
15847                         * succeeds, so null out this field.
15848                         */
15849                        mArgs = null;
15850                    }
15851                } else {
15852                    /*
15853                     * No package verification is enabled, so immediately start
15854                     * the remote call to initiate copy using temporary file.
15855                     */
15856                    ret = args.copyApk(mContainerService, true);
15857                }
15858            }
15859
15860            mRet = ret;
15861        }
15862
15863        @Override
15864        void handleReturnCode() {
15865            // If mArgs is null, then MCS couldn't be reached. When it
15866            // reconnects, it will try again to install. At that point, this
15867            // will succeed.
15868            if (mArgs != null) {
15869                processPendingInstall(mArgs, mRet);
15870            }
15871        }
15872
15873        @Override
15874        void handleServiceError() {
15875            mArgs = createInstallArgs(this);
15876            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15877        }
15878
15879        public boolean isForwardLocked() {
15880            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15881        }
15882    }
15883
15884    /**
15885     * Used during creation of InstallArgs
15886     *
15887     * @param installFlags package installation flags
15888     * @return true if should be installed on external storage
15889     */
15890    private static boolean installOnExternalAsec(int installFlags) {
15891        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15892            return false;
15893        }
15894        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15895            return true;
15896        }
15897        return false;
15898    }
15899
15900    /**
15901     * Used during creation of InstallArgs
15902     *
15903     * @param installFlags package installation flags
15904     * @return true if should be installed as forward locked
15905     */
15906    private static boolean installForwardLocked(int installFlags) {
15907        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15908    }
15909
15910    private InstallArgs createInstallArgs(InstallParams params) {
15911        if (params.move != null) {
15912            return new MoveInstallArgs(params);
15913        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15914            return new AsecInstallArgs(params);
15915        } else {
15916            return new FileInstallArgs(params);
15917        }
15918    }
15919
15920    /**
15921     * Create args that describe an existing installed package. Typically used
15922     * when cleaning up old installs, or used as a move source.
15923     */
15924    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15925            String resourcePath, String[] instructionSets) {
15926        final boolean isInAsec;
15927        if (installOnExternalAsec(installFlags)) {
15928            /* Apps on SD card are always in ASEC containers. */
15929            isInAsec = true;
15930        } else if (installForwardLocked(installFlags)
15931                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15932            /*
15933             * Forward-locked apps are only in ASEC containers if they're the
15934             * new style
15935             */
15936            isInAsec = true;
15937        } else {
15938            isInAsec = false;
15939        }
15940
15941        if (isInAsec) {
15942            return new AsecInstallArgs(codePath, instructionSets,
15943                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15944        } else {
15945            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15946        }
15947    }
15948
15949    static abstract class InstallArgs {
15950        /** @see InstallParams#origin */
15951        final OriginInfo origin;
15952        /** @see InstallParams#move */
15953        final MoveInfo move;
15954
15955        final IPackageInstallObserver2 observer;
15956        // Always refers to PackageManager flags only
15957        final int installFlags;
15958        final String installerPackageName;
15959        final String volumeUuid;
15960        final UserHandle user;
15961        final String abiOverride;
15962        final String[] installGrantPermissions;
15963        /** If non-null, drop an async trace when the install completes */
15964        final String traceMethod;
15965        final int traceCookie;
15966        final Certificate[][] certificates;
15967        final int installReason;
15968
15969        // The list of instruction sets supported by this app. This is currently
15970        // only used during the rmdex() phase to clean up resources. We can get rid of this
15971        // if we move dex files under the common app path.
15972        /* nullable */ String[] instructionSets;
15973
15974        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15975                int installFlags, String installerPackageName, String volumeUuid,
15976                UserHandle user, String[] instructionSets,
15977                String abiOverride, String[] installGrantPermissions,
15978                String traceMethod, int traceCookie, Certificate[][] certificates,
15979                int installReason) {
15980            this.origin = origin;
15981            this.move = move;
15982            this.installFlags = installFlags;
15983            this.observer = observer;
15984            this.installerPackageName = installerPackageName;
15985            this.volumeUuid = volumeUuid;
15986            this.user = user;
15987            this.instructionSets = instructionSets;
15988            this.abiOverride = abiOverride;
15989            this.installGrantPermissions = installGrantPermissions;
15990            this.traceMethod = traceMethod;
15991            this.traceCookie = traceCookie;
15992            this.certificates = certificates;
15993            this.installReason = installReason;
15994        }
15995
15996        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15997        abstract int doPreInstall(int status);
15998
15999        /**
16000         * Rename package into final resting place. All paths on the given
16001         * scanned package should be updated to reflect the rename.
16002         */
16003        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16004        abstract int doPostInstall(int status, int uid);
16005
16006        /** @see PackageSettingBase#codePathString */
16007        abstract String getCodePath();
16008        /** @see PackageSettingBase#resourcePathString */
16009        abstract String getResourcePath();
16010
16011        // Need installer lock especially for dex file removal.
16012        abstract void cleanUpResourcesLI();
16013        abstract boolean doPostDeleteLI(boolean delete);
16014
16015        /**
16016         * Called before the source arguments are copied. This is used mostly
16017         * for MoveParams when it needs to read the source file to put it in the
16018         * destination.
16019         */
16020        int doPreCopy() {
16021            return PackageManager.INSTALL_SUCCEEDED;
16022        }
16023
16024        /**
16025         * Called after the source arguments are copied. This is used mostly for
16026         * MoveParams when it needs to read the source file to put it in the
16027         * destination.
16028         */
16029        int doPostCopy(int uid) {
16030            return PackageManager.INSTALL_SUCCEEDED;
16031        }
16032
16033        protected boolean isFwdLocked() {
16034            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16035        }
16036
16037        protected boolean isExternalAsec() {
16038            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16039        }
16040
16041        protected boolean isEphemeral() {
16042            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16043        }
16044
16045        UserHandle getUser() {
16046            return user;
16047        }
16048    }
16049
16050    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16051        if (!allCodePaths.isEmpty()) {
16052            if (instructionSets == null) {
16053                throw new IllegalStateException("instructionSet == null");
16054            }
16055            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16056            for (String codePath : allCodePaths) {
16057                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16058                    try {
16059                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16060                    } catch (InstallerException ignored) {
16061                    }
16062                }
16063            }
16064        }
16065    }
16066
16067    /**
16068     * Logic to handle installation of non-ASEC applications, including copying
16069     * and renaming logic.
16070     */
16071    class FileInstallArgs extends InstallArgs {
16072        private File codeFile;
16073        private File resourceFile;
16074
16075        // Example topology:
16076        // /data/app/com.example/base.apk
16077        // /data/app/com.example/split_foo.apk
16078        // /data/app/com.example/lib/arm/libfoo.so
16079        // /data/app/com.example/lib/arm64/libfoo.so
16080        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16081
16082        /** New install */
16083        FileInstallArgs(InstallParams params) {
16084            super(params.origin, params.move, params.observer, params.installFlags,
16085                    params.installerPackageName, params.volumeUuid,
16086                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16087                    params.grantedRuntimePermissions,
16088                    params.traceMethod, params.traceCookie, params.certificates,
16089                    params.installReason);
16090            if (isFwdLocked()) {
16091                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16092            }
16093        }
16094
16095        /** Existing install */
16096        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16097            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16098                    null, null, null, 0, null /*certificates*/,
16099                    PackageManager.INSTALL_REASON_UNKNOWN);
16100            this.codeFile = (codePath != null) ? new File(codePath) : null;
16101            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16102        }
16103
16104        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16106            try {
16107                return doCopyApk(imcs, temp);
16108            } finally {
16109                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16110            }
16111        }
16112
16113        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16114            if (origin.staged) {
16115                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16116                codeFile = origin.file;
16117                resourceFile = origin.file;
16118                return PackageManager.INSTALL_SUCCEEDED;
16119            }
16120
16121            try {
16122                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16123                final File tempDir =
16124                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16125                codeFile = tempDir;
16126                resourceFile = tempDir;
16127            } catch (IOException e) {
16128                Slog.w(TAG, "Failed to create copy file: " + e);
16129                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16130            }
16131
16132            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16133                @Override
16134                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16135                    if (!FileUtils.isValidExtFilename(name)) {
16136                        throw new IllegalArgumentException("Invalid filename: " + name);
16137                    }
16138                    try {
16139                        final File file = new File(codeFile, name);
16140                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16141                                O_RDWR | O_CREAT, 0644);
16142                        Os.chmod(file.getAbsolutePath(), 0644);
16143                        return new ParcelFileDescriptor(fd);
16144                    } catch (ErrnoException e) {
16145                        throw new RemoteException("Failed to open: " + e.getMessage());
16146                    }
16147                }
16148            };
16149
16150            int ret = PackageManager.INSTALL_SUCCEEDED;
16151            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16152            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16153                Slog.e(TAG, "Failed to copy package");
16154                return ret;
16155            }
16156
16157            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16158            NativeLibraryHelper.Handle handle = null;
16159            try {
16160                handle = NativeLibraryHelper.Handle.create(codeFile);
16161                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16162                        abiOverride);
16163            } catch (IOException e) {
16164                Slog.e(TAG, "Copying native libraries failed", e);
16165                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16166            } finally {
16167                IoUtils.closeQuietly(handle);
16168            }
16169
16170            return ret;
16171        }
16172
16173        int doPreInstall(int status) {
16174            if (status != PackageManager.INSTALL_SUCCEEDED) {
16175                cleanUp();
16176            }
16177            return status;
16178        }
16179
16180        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16181            if (status != PackageManager.INSTALL_SUCCEEDED) {
16182                cleanUp();
16183                return false;
16184            }
16185
16186            final File targetDir = codeFile.getParentFile();
16187            final File beforeCodeFile = codeFile;
16188            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16189
16190            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16191            try {
16192                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16193            } catch (ErrnoException e) {
16194                Slog.w(TAG, "Failed to rename", e);
16195                return false;
16196            }
16197
16198            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16199                Slog.w(TAG, "Failed to restorecon");
16200                return false;
16201            }
16202
16203            // Reflect the rename internally
16204            codeFile = afterCodeFile;
16205            resourceFile = afterCodeFile;
16206
16207            // Reflect the rename in scanned details
16208            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16209            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16210                    afterCodeFile, pkg.baseCodePath));
16211            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16212                    afterCodeFile, pkg.splitCodePaths));
16213
16214            // Reflect the rename in app info
16215            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16216            pkg.setApplicationInfoCodePath(pkg.codePath);
16217            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16218            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16219            pkg.setApplicationInfoResourcePath(pkg.codePath);
16220            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16221            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16222
16223            return true;
16224        }
16225
16226        int doPostInstall(int status, int uid) {
16227            if (status != PackageManager.INSTALL_SUCCEEDED) {
16228                cleanUp();
16229            }
16230            return status;
16231        }
16232
16233        @Override
16234        String getCodePath() {
16235            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16236        }
16237
16238        @Override
16239        String getResourcePath() {
16240            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16241        }
16242
16243        private boolean cleanUp() {
16244            if (codeFile == null || !codeFile.exists()) {
16245                return false;
16246            }
16247
16248            removeCodePathLI(codeFile);
16249
16250            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16251                resourceFile.delete();
16252            }
16253
16254            return true;
16255        }
16256
16257        void cleanUpResourcesLI() {
16258            // Try enumerating all code paths before deleting
16259            List<String> allCodePaths = Collections.EMPTY_LIST;
16260            if (codeFile != null && codeFile.exists()) {
16261                try {
16262                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16263                    allCodePaths = pkg.getAllCodePaths();
16264                } catch (PackageParserException e) {
16265                    // Ignored; we tried our best
16266                }
16267            }
16268
16269            cleanUp();
16270            removeDexFiles(allCodePaths, instructionSets);
16271        }
16272
16273        boolean doPostDeleteLI(boolean delete) {
16274            // XXX err, shouldn't we respect the delete flag?
16275            cleanUpResourcesLI();
16276            return true;
16277        }
16278    }
16279
16280    private boolean isAsecExternal(String cid) {
16281        final String asecPath = PackageHelper.getSdFilesystem(cid);
16282        return !asecPath.startsWith(mAsecInternalPath);
16283    }
16284
16285    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16286            PackageManagerException {
16287        if (copyRet < 0) {
16288            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16289                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16290                throw new PackageManagerException(copyRet, message);
16291            }
16292        }
16293    }
16294
16295    /**
16296     * Extract the StorageManagerService "container ID" from the full code path of an
16297     * .apk.
16298     */
16299    static String cidFromCodePath(String fullCodePath) {
16300        int eidx = fullCodePath.lastIndexOf("/");
16301        String subStr1 = fullCodePath.substring(0, eidx);
16302        int sidx = subStr1.lastIndexOf("/");
16303        return subStr1.substring(sidx+1, eidx);
16304    }
16305
16306    /**
16307     * Logic to handle installation of ASEC applications, including copying and
16308     * renaming logic.
16309     */
16310    class AsecInstallArgs extends InstallArgs {
16311        static final String RES_FILE_NAME = "pkg.apk";
16312        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16313
16314        String cid;
16315        String packagePath;
16316        String resourcePath;
16317
16318        /** New install */
16319        AsecInstallArgs(InstallParams params) {
16320            super(params.origin, params.move, params.observer, params.installFlags,
16321                    params.installerPackageName, params.volumeUuid,
16322                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16323                    params.grantedRuntimePermissions,
16324                    params.traceMethod, params.traceCookie, params.certificates,
16325                    params.installReason);
16326        }
16327
16328        /** Existing install */
16329        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16330                        boolean isExternal, boolean isForwardLocked) {
16331            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16332                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16333                    instructionSets, null, null, null, 0, null /*certificates*/,
16334                    PackageManager.INSTALL_REASON_UNKNOWN);
16335            // Hackily pretend we're still looking at a full code path
16336            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16337                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16338            }
16339
16340            // Extract cid from fullCodePath
16341            int eidx = fullCodePath.lastIndexOf("/");
16342            String subStr1 = fullCodePath.substring(0, eidx);
16343            int sidx = subStr1.lastIndexOf("/");
16344            cid = subStr1.substring(sidx+1, eidx);
16345            setMountPath(subStr1);
16346        }
16347
16348        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16349            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16350                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16351                    instructionSets, null, null, null, 0, null /*certificates*/,
16352                    PackageManager.INSTALL_REASON_UNKNOWN);
16353            this.cid = cid;
16354            setMountPath(PackageHelper.getSdDir(cid));
16355        }
16356
16357        void createCopyFile() {
16358            cid = mInstallerService.allocateExternalStageCidLegacy();
16359        }
16360
16361        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16362            if (origin.staged && origin.cid != null) {
16363                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16364                cid = origin.cid;
16365                setMountPath(PackageHelper.getSdDir(cid));
16366                return PackageManager.INSTALL_SUCCEEDED;
16367            }
16368
16369            if (temp) {
16370                createCopyFile();
16371            } else {
16372                /*
16373                 * Pre-emptively destroy the container since it's destroyed if
16374                 * copying fails due to it existing anyway.
16375                 */
16376                PackageHelper.destroySdDir(cid);
16377            }
16378
16379            final String newMountPath = imcs.copyPackageToContainer(
16380                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16381                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16382
16383            if (newMountPath != null) {
16384                setMountPath(newMountPath);
16385                return PackageManager.INSTALL_SUCCEEDED;
16386            } else {
16387                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16388            }
16389        }
16390
16391        @Override
16392        String getCodePath() {
16393            return packagePath;
16394        }
16395
16396        @Override
16397        String getResourcePath() {
16398            return resourcePath;
16399        }
16400
16401        int doPreInstall(int status) {
16402            if (status != PackageManager.INSTALL_SUCCEEDED) {
16403                // Destroy container
16404                PackageHelper.destroySdDir(cid);
16405            } else {
16406                boolean mounted = PackageHelper.isContainerMounted(cid);
16407                if (!mounted) {
16408                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16409                            Process.SYSTEM_UID);
16410                    if (newMountPath != null) {
16411                        setMountPath(newMountPath);
16412                    } else {
16413                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16414                    }
16415                }
16416            }
16417            return status;
16418        }
16419
16420        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16421            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16422            String newMountPath = null;
16423            if (PackageHelper.isContainerMounted(cid)) {
16424                // Unmount the container
16425                if (!PackageHelper.unMountSdDir(cid)) {
16426                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16427                    return false;
16428                }
16429            }
16430            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16431                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16432                        " which might be stale. Will try to clean up.");
16433                // Clean up the stale container and proceed to recreate.
16434                if (!PackageHelper.destroySdDir(newCacheId)) {
16435                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16436                    return false;
16437                }
16438                // Successfully cleaned up stale container. Try to rename again.
16439                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16440                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16441                            + " inspite of cleaning it up.");
16442                    return false;
16443                }
16444            }
16445            if (!PackageHelper.isContainerMounted(newCacheId)) {
16446                Slog.w(TAG, "Mounting container " + newCacheId);
16447                newMountPath = PackageHelper.mountSdDir(newCacheId,
16448                        getEncryptKey(), Process.SYSTEM_UID);
16449            } else {
16450                newMountPath = PackageHelper.getSdDir(newCacheId);
16451            }
16452            if (newMountPath == null) {
16453                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16454                return false;
16455            }
16456            Log.i(TAG, "Succesfully renamed " + cid +
16457                    " to " + newCacheId +
16458                    " at new path: " + newMountPath);
16459            cid = newCacheId;
16460
16461            final File beforeCodeFile = new File(packagePath);
16462            setMountPath(newMountPath);
16463            final File afterCodeFile = new File(packagePath);
16464
16465            // Reflect the rename in scanned details
16466            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16467            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16468                    afterCodeFile, pkg.baseCodePath));
16469            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16470                    afterCodeFile, pkg.splitCodePaths));
16471
16472            // Reflect the rename in app info
16473            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16474            pkg.setApplicationInfoCodePath(pkg.codePath);
16475            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16476            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16477            pkg.setApplicationInfoResourcePath(pkg.codePath);
16478            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16479            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16480
16481            return true;
16482        }
16483
16484        private void setMountPath(String mountPath) {
16485            final File mountFile = new File(mountPath);
16486
16487            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16488            if (monolithicFile.exists()) {
16489                packagePath = monolithicFile.getAbsolutePath();
16490                if (isFwdLocked()) {
16491                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16492                } else {
16493                    resourcePath = packagePath;
16494                }
16495            } else {
16496                packagePath = mountFile.getAbsolutePath();
16497                resourcePath = packagePath;
16498            }
16499        }
16500
16501        int doPostInstall(int status, int uid) {
16502            if (status != PackageManager.INSTALL_SUCCEEDED) {
16503                cleanUp();
16504            } else {
16505                final int groupOwner;
16506                final String protectedFile;
16507                if (isFwdLocked()) {
16508                    groupOwner = UserHandle.getSharedAppGid(uid);
16509                    protectedFile = RES_FILE_NAME;
16510                } else {
16511                    groupOwner = -1;
16512                    protectedFile = null;
16513                }
16514
16515                if (uid < Process.FIRST_APPLICATION_UID
16516                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16517                    Slog.e(TAG, "Failed to finalize " + cid);
16518                    PackageHelper.destroySdDir(cid);
16519                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16520                }
16521
16522                boolean mounted = PackageHelper.isContainerMounted(cid);
16523                if (!mounted) {
16524                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16525                }
16526            }
16527            return status;
16528        }
16529
16530        private void cleanUp() {
16531            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16532
16533            // Destroy secure container
16534            PackageHelper.destroySdDir(cid);
16535        }
16536
16537        private List<String> getAllCodePaths() {
16538            final File codeFile = new File(getCodePath());
16539            if (codeFile != null && codeFile.exists()) {
16540                try {
16541                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16542                    return pkg.getAllCodePaths();
16543                } catch (PackageParserException e) {
16544                    // Ignored; we tried our best
16545                }
16546            }
16547            return Collections.EMPTY_LIST;
16548        }
16549
16550        void cleanUpResourcesLI() {
16551            // Enumerate all code paths before deleting
16552            cleanUpResourcesLI(getAllCodePaths());
16553        }
16554
16555        private void cleanUpResourcesLI(List<String> allCodePaths) {
16556            cleanUp();
16557            removeDexFiles(allCodePaths, instructionSets);
16558        }
16559
16560        String getPackageName() {
16561            return getAsecPackageName(cid);
16562        }
16563
16564        boolean doPostDeleteLI(boolean delete) {
16565            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16566            final List<String> allCodePaths = getAllCodePaths();
16567            boolean mounted = PackageHelper.isContainerMounted(cid);
16568            if (mounted) {
16569                // Unmount first
16570                if (PackageHelper.unMountSdDir(cid)) {
16571                    mounted = false;
16572                }
16573            }
16574            if (!mounted && delete) {
16575                cleanUpResourcesLI(allCodePaths);
16576            }
16577            return !mounted;
16578        }
16579
16580        @Override
16581        int doPreCopy() {
16582            if (isFwdLocked()) {
16583                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16584                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16585                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16586                }
16587            }
16588
16589            return PackageManager.INSTALL_SUCCEEDED;
16590        }
16591
16592        @Override
16593        int doPostCopy(int uid) {
16594            if (isFwdLocked()) {
16595                if (uid < Process.FIRST_APPLICATION_UID
16596                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16597                                RES_FILE_NAME)) {
16598                    Slog.e(TAG, "Failed to finalize " + cid);
16599                    PackageHelper.destroySdDir(cid);
16600                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16601                }
16602            }
16603
16604            return PackageManager.INSTALL_SUCCEEDED;
16605        }
16606    }
16607
16608    /**
16609     * Logic to handle movement of existing installed applications.
16610     */
16611    class MoveInstallArgs extends InstallArgs {
16612        private File codeFile;
16613        private File resourceFile;
16614
16615        /** New install */
16616        MoveInstallArgs(InstallParams params) {
16617            super(params.origin, params.move, params.observer, params.installFlags,
16618                    params.installerPackageName, params.volumeUuid,
16619                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16620                    params.grantedRuntimePermissions,
16621                    params.traceMethod, params.traceCookie, params.certificates,
16622                    params.installReason);
16623        }
16624
16625        int copyApk(IMediaContainerService imcs, boolean temp) {
16626            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16627                    + move.fromUuid + " to " + move.toUuid);
16628            synchronized (mInstaller) {
16629                try {
16630                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16631                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16632                } catch (InstallerException e) {
16633                    Slog.w(TAG, "Failed to move app", e);
16634                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16635                }
16636            }
16637
16638            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16639            resourceFile = codeFile;
16640            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16641
16642            return PackageManager.INSTALL_SUCCEEDED;
16643        }
16644
16645        int doPreInstall(int status) {
16646            if (status != PackageManager.INSTALL_SUCCEEDED) {
16647                cleanUp(move.toUuid);
16648            }
16649            return status;
16650        }
16651
16652        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16653            if (status != PackageManager.INSTALL_SUCCEEDED) {
16654                cleanUp(move.toUuid);
16655                return false;
16656            }
16657
16658            // Reflect the move in app info
16659            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16660            pkg.setApplicationInfoCodePath(pkg.codePath);
16661            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16662            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16663            pkg.setApplicationInfoResourcePath(pkg.codePath);
16664            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16665            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16666
16667            return true;
16668        }
16669
16670        int doPostInstall(int status, int uid) {
16671            if (status == PackageManager.INSTALL_SUCCEEDED) {
16672                cleanUp(move.fromUuid);
16673            } else {
16674                cleanUp(move.toUuid);
16675            }
16676            return status;
16677        }
16678
16679        @Override
16680        String getCodePath() {
16681            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16682        }
16683
16684        @Override
16685        String getResourcePath() {
16686            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16687        }
16688
16689        private boolean cleanUp(String volumeUuid) {
16690            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16691                    move.dataAppName);
16692            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16693            final int[] userIds = sUserManager.getUserIds();
16694            synchronized (mInstallLock) {
16695                // Clean up both app data and code
16696                // All package moves are frozen until finished
16697                for (int userId : userIds) {
16698                    try {
16699                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16700                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16701                    } catch (InstallerException e) {
16702                        Slog.w(TAG, String.valueOf(e));
16703                    }
16704                }
16705                removeCodePathLI(codeFile);
16706            }
16707            return true;
16708        }
16709
16710        void cleanUpResourcesLI() {
16711            throw new UnsupportedOperationException();
16712        }
16713
16714        boolean doPostDeleteLI(boolean delete) {
16715            throw new UnsupportedOperationException();
16716        }
16717    }
16718
16719    static String getAsecPackageName(String packageCid) {
16720        int idx = packageCid.lastIndexOf("-");
16721        if (idx == -1) {
16722            return packageCid;
16723        }
16724        return packageCid.substring(0, idx);
16725    }
16726
16727    // Utility method used to create code paths based on package name and available index.
16728    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16729        String idxStr = "";
16730        int idx = 1;
16731        // Fall back to default value of idx=1 if prefix is not
16732        // part of oldCodePath
16733        if (oldCodePath != null) {
16734            String subStr = oldCodePath;
16735            // Drop the suffix right away
16736            if (suffix != null && subStr.endsWith(suffix)) {
16737                subStr = subStr.substring(0, subStr.length() - suffix.length());
16738            }
16739            // If oldCodePath already contains prefix find out the
16740            // ending index to either increment or decrement.
16741            int sidx = subStr.lastIndexOf(prefix);
16742            if (sidx != -1) {
16743                subStr = subStr.substring(sidx + prefix.length());
16744                if (subStr != null) {
16745                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16746                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16747                    }
16748                    try {
16749                        idx = Integer.parseInt(subStr);
16750                        if (idx <= 1) {
16751                            idx++;
16752                        } else {
16753                            idx--;
16754                        }
16755                    } catch(NumberFormatException e) {
16756                    }
16757                }
16758            }
16759        }
16760        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16761        return prefix + idxStr;
16762    }
16763
16764    private File getNextCodePath(File targetDir, String packageName) {
16765        File result;
16766        SecureRandom random = new SecureRandom();
16767        byte[] bytes = new byte[16];
16768        do {
16769            random.nextBytes(bytes);
16770            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16771            result = new File(targetDir, packageName + "-" + suffix);
16772        } while (result.exists());
16773        return result;
16774    }
16775
16776    // Utility method that returns the relative package path with respect
16777    // to the installation directory. Like say for /data/data/com.test-1.apk
16778    // string com.test-1 is returned.
16779    static String deriveCodePathName(String codePath) {
16780        if (codePath == null) {
16781            return null;
16782        }
16783        final File codeFile = new File(codePath);
16784        final String name = codeFile.getName();
16785        if (codeFile.isDirectory()) {
16786            return name;
16787        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16788            final int lastDot = name.lastIndexOf('.');
16789            return name.substring(0, lastDot);
16790        } else {
16791            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16792            return null;
16793        }
16794    }
16795
16796    static class PackageInstalledInfo {
16797        String name;
16798        int uid;
16799        // The set of users that originally had this package installed.
16800        int[] origUsers;
16801        // The set of users that now have this package installed.
16802        int[] newUsers;
16803        PackageParser.Package pkg;
16804        int returnCode;
16805        String returnMsg;
16806        String installerPackageName;
16807        PackageRemovedInfo removedInfo;
16808        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16809
16810        public void setError(int code, String msg) {
16811            setReturnCode(code);
16812            setReturnMessage(msg);
16813            Slog.w(TAG, msg);
16814        }
16815
16816        public void setError(String msg, PackageParserException e) {
16817            setReturnCode(e.error);
16818            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16819            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16820            for (int i = 0; i < childCount; i++) {
16821                addedChildPackages.valueAt(i).setError(msg, e);
16822            }
16823            Slog.w(TAG, msg, e);
16824        }
16825
16826        public void setError(String msg, PackageManagerException e) {
16827            returnCode = e.error;
16828            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16829            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16830            for (int i = 0; i < childCount; i++) {
16831                addedChildPackages.valueAt(i).setError(msg, e);
16832            }
16833            Slog.w(TAG, msg, e);
16834        }
16835
16836        public void setReturnCode(int returnCode) {
16837            this.returnCode = returnCode;
16838            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16839            for (int i = 0; i < childCount; i++) {
16840                addedChildPackages.valueAt(i).returnCode = returnCode;
16841            }
16842        }
16843
16844        private void setReturnMessage(String returnMsg) {
16845            this.returnMsg = returnMsg;
16846            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16847            for (int i = 0; i < childCount; i++) {
16848                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16849            }
16850        }
16851
16852        // In some error cases we want to convey more info back to the observer
16853        String origPackage;
16854        String origPermission;
16855    }
16856
16857    /*
16858     * Install a non-existing package.
16859     */
16860    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16861            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16862            PackageInstalledInfo res, int installReason) {
16863        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16864
16865        // Remember this for later, in case we need to rollback this install
16866        String pkgName = pkg.packageName;
16867
16868        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16869
16870        synchronized(mPackages) {
16871            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16872            if (renamedPackage != null) {
16873                // A package with the same name is already installed, though
16874                // it has been renamed to an older name.  The package we
16875                // are trying to install should be installed as an update to
16876                // the existing one, but that has not been requested, so bail.
16877                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16878                        + " without first uninstalling package running as "
16879                        + renamedPackage);
16880                return;
16881            }
16882            if (mPackages.containsKey(pkgName)) {
16883                // Don't allow installation over an existing package with the same name.
16884                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16885                        + " without first uninstalling.");
16886                return;
16887            }
16888        }
16889
16890        try {
16891            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16892                    System.currentTimeMillis(), user);
16893
16894            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16895
16896            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16897                prepareAppDataAfterInstallLIF(newPackage);
16898
16899            } else {
16900                // Remove package from internal structures, but keep around any
16901                // data that might have already existed
16902                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16903                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16904            }
16905        } catch (PackageManagerException e) {
16906            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16907        }
16908
16909        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16910    }
16911
16912    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16913        // Can't rotate keys during boot or if sharedUser.
16914        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16915                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16916            return false;
16917        }
16918        // app is using upgradeKeySets; make sure all are valid
16919        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16920        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16921        for (int i = 0; i < upgradeKeySets.length; i++) {
16922            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16923                Slog.wtf(TAG, "Package "
16924                         + (oldPs.name != null ? oldPs.name : "<null>")
16925                         + " contains upgrade-key-set reference to unknown key-set: "
16926                         + upgradeKeySets[i]
16927                         + " reverting to signatures check.");
16928                return false;
16929            }
16930        }
16931        return true;
16932    }
16933
16934    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16935        // Upgrade keysets are being used.  Determine if new package has a superset of the
16936        // required keys.
16937        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16938        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16939        for (int i = 0; i < upgradeKeySets.length; i++) {
16940            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16941            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16942                return true;
16943            }
16944        }
16945        return false;
16946    }
16947
16948    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16949        try (DigestInputStream digestStream =
16950                new DigestInputStream(new FileInputStream(file), digest)) {
16951            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16952        }
16953    }
16954
16955    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16956            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16957            int installReason) {
16958        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16959
16960        final PackageParser.Package oldPackage;
16961        final PackageSetting ps;
16962        final String pkgName = pkg.packageName;
16963        final int[] allUsers;
16964        final int[] installedUsers;
16965
16966        synchronized(mPackages) {
16967            oldPackage = mPackages.get(pkgName);
16968            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16969
16970            // don't allow upgrade to target a release SDK from a pre-release SDK
16971            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16972                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16973            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16974                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16975            if (oldTargetsPreRelease
16976                    && !newTargetsPreRelease
16977                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16978                Slog.w(TAG, "Can't install package targeting released sdk");
16979                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16980                return;
16981            }
16982
16983            ps = mSettings.mPackages.get(pkgName);
16984
16985            // verify signatures are valid
16986            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16987                if (!checkUpgradeKeySetLP(ps, pkg)) {
16988                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16989                            "New package not signed by keys specified by upgrade-keysets: "
16990                                    + pkgName);
16991                    return;
16992                }
16993            } else {
16994                // default to original signature matching
16995                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16996                        != PackageManager.SIGNATURE_MATCH) {
16997                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16998                            "New package has a different signature: " + pkgName);
16999                    return;
17000                }
17001            }
17002
17003            // don't allow a system upgrade unless the upgrade hash matches
17004            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17005                byte[] digestBytes = null;
17006                try {
17007                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17008                    updateDigest(digest, new File(pkg.baseCodePath));
17009                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17010                        for (String path : pkg.splitCodePaths) {
17011                            updateDigest(digest, new File(path));
17012                        }
17013                    }
17014                    digestBytes = digest.digest();
17015                } catch (NoSuchAlgorithmException | IOException e) {
17016                    res.setError(INSTALL_FAILED_INVALID_APK,
17017                            "Could not compute hash: " + pkgName);
17018                    return;
17019                }
17020                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17021                    res.setError(INSTALL_FAILED_INVALID_APK,
17022                            "New package fails restrict-update check: " + pkgName);
17023                    return;
17024                }
17025                // retain upgrade restriction
17026                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17027            }
17028
17029            // Check for shared user id changes
17030            String invalidPackageName =
17031                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17032            if (invalidPackageName != null) {
17033                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17034                        "Package " + invalidPackageName + " tried to change user "
17035                                + oldPackage.mSharedUserId);
17036                return;
17037            }
17038
17039            // In case of rollback, remember per-user/profile install state
17040            allUsers = sUserManager.getUserIds();
17041            installedUsers = ps.queryInstalledUsers(allUsers, true);
17042
17043            // don't allow an upgrade from full to ephemeral
17044            if (isInstantApp) {
17045                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17046                    for (int currentUser : allUsers) {
17047                        if (!ps.getInstantApp(currentUser)) {
17048                            // can't downgrade from full to instant
17049                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17050                                    + " for user: " + currentUser);
17051                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17052                            return;
17053                        }
17054                    }
17055                } else if (!ps.getInstantApp(user.getIdentifier())) {
17056                    // can't downgrade from full to instant
17057                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17058                            + " for user: " + user.getIdentifier());
17059                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17060                    return;
17061                }
17062            }
17063        }
17064
17065        // Update what is removed
17066        res.removedInfo = new PackageRemovedInfo(this);
17067        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17068        res.removedInfo.removedPackage = oldPackage.packageName;
17069        res.removedInfo.installerPackageName = ps.installerPackageName;
17070        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17071        res.removedInfo.isUpdate = true;
17072        res.removedInfo.origUsers = installedUsers;
17073        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17074        for (int i = 0; i < installedUsers.length; i++) {
17075            final int userId = installedUsers[i];
17076            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17077        }
17078
17079        final int childCount = (oldPackage.childPackages != null)
17080                ? oldPackage.childPackages.size() : 0;
17081        for (int i = 0; i < childCount; i++) {
17082            boolean childPackageUpdated = false;
17083            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17084            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17085            if (res.addedChildPackages != null) {
17086                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17087                if (childRes != null) {
17088                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17089                    childRes.removedInfo.removedPackage = childPkg.packageName;
17090                    if (childPs != null) {
17091                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17092                    }
17093                    childRes.removedInfo.isUpdate = true;
17094                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17095                    childPackageUpdated = true;
17096                }
17097            }
17098            if (!childPackageUpdated) {
17099                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17100                childRemovedRes.removedPackage = childPkg.packageName;
17101                if (childPs != null) {
17102                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17103                }
17104                childRemovedRes.isUpdate = false;
17105                childRemovedRes.dataRemoved = true;
17106                synchronized (mPackages) {
17107                    if (childPs != null) {
17108                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17109                    }
17110                }
17111                if (res.removedInfo.removedChildPackages == null) {
17112                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17113                }
17114                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17115            }
17116        }
17117
17118        boolean sysPkg = (isSystemApp(oldPackage));
17119        if (sysPkg) {
17120            // Set the system/privileged/oem flags as needed
17121            final boolean privileged =
17122                    (oldPackage.applicationInfo.privateFlags
17123                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17124            final boolean oem =
17125                    (oldPackage.applicationInfo.privateFlags
17126                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17127            final int systemPolicyFlags = policyFlags
17128                    | PackageParser.PARSE_IS_SYSTEM
17129                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17130                    | (oem ? PARSE_IS_OEM : 0);
17131
17132            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17133                    user, allUsers, installerPackageName, res, installReason);
17134        } else {
17135            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17136                    user, allUsers, installerPackageName, res, installReason);
17137        }
17138    }
17139
17140    @Override
17141    public List<String> getPreviousCodePaths(String packageName) {
17142        final int callingUid = Binder.getCallingUid();
17143        final List<String> result = new ArrayList<>();
17144        if (getInstantAppPackageName(callingUid) != null) {
17145            return result;
17146        }
17147        final PackageSetting ps = mSettings.mPackages.get(packageName);
17148        if (ps != null
17149                && ps.oldCodePaths != null
17150                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17151            result.addAll(ps.oldCodePaths);
17152        }
17153        return result;
17154    }
17155
17156    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17157            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17158            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17159            int installReason) {
17160        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17161                + deletedPackage);
17162
17163        String pkgName = deletedPackage.packageName;
17164        boolean deletedPkg = true;
17165        boolean addedPkg = false;
17166        boolean updatedSettings = false;
17167        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17168        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17169                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17170
17171        final long origUpdateTime = (pkg.mExtras != null)
17172                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17173
17174        // First delete the existing package while retaining the data directory
17175        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17176                res.removedInfo, true, pkg)) {
17177            // If the existing package wasn't successfully deleted
17178            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17179            deletedPkg = false;
17180        } else {
17181            // Successfully deleted the old package; proceed with replace.
17182
17183            // If deleted package lived in a container, give users a chance to
17184            // relinquish resources before killing.
17185            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17186                if (DEBUG_INSTALL) {
17187                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17188                }
17189                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17190                final ArrayList<String> pkgList = new ArrayList<String>(1);
17191                pkgList.add(deletedPackage.applicationInfo.packageName);
17192                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17193            }
17194
17195            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17196                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17197            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17198
17199            try {
17200                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17201                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17202                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17203                        installReason);
17204
17205                // Update the in-memory copy of the previous code paths.
17206                PackageSetting ps = mSettings.mPackages.get(pkgName);
17207                if (!killApp) {
17208                    if (ps.oldCodePaths == null) {
17209                        ps.oldCodePaths = new ArraySet<>();
17210                    }
17211                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17212                    if (deletedPackage.splitCodePaths != null) {
17213                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17214                    }
17215                } else {
17216                    ps.oldCodePaths = null;
17217                }
17218                if (ps.childPackageNames != null) {
17219                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17220                        final String childPkgName = ps.childPackageNames.get(i);
17221                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17222                        childPs.oldCodePaths = ps.oldCodePaths;
17223                    }
17224                }
17225                // set instant app status, but, only if it's explicitly specified
17226                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17227                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17228                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17229                prepareAppDataAfterInstallLIF(newPackage);
17230                addedPkg = true;
17231                mDexManager.notifyPackageUpdated(newPackage.packageName,
17232                        newPackage.baseCodePath, newPackage.splitCodePaths);
17233            } catch (PackageManagerException e) {
17234                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17235            }
17236        }
17237
17238        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17239            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17240
17241            // Revert all internal state mutations and added folders for the failed install
17242            if (addedPkg) {
17243                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17244                        res.removedInfo, true, null);
17245            }
17246
17247            // Restore the old package
17248            if (deletedPkg) {
17249                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17250                File restoreFile = new File(deletedPackage.codePath);
17251                // Parse old package
17252                boolean oldExternal = isExternal(deletedPackage);
17253                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17254                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17255                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17256                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17257                try {
17258                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17259                            null);
17260                } catch (PackageManagerException e) {
17261                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17262                            + e.getMessage());
17263                    return;
17264                }
17265
17266                synchronized (mPackages) {
17267                    // Ensure the installer package name up to date
17268                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17269
17270                    // Update permissions for restored package
17271                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17272
17273                    mSettings.writeLPr();
17274                }
17275
17276                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17277            }
17278        } else {
17279            synchronized (mPackages) {
17280                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17281                if (ps != null) {
17282                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17283                    if (res.removedInfo.removedChildPackages != null) {
17284                        final int childCount = res.removedInfo.removedChildPackages.size();
17285                        // Iterate in reverse as we may modify the collection
17286                        for (int i = childCount - 1; i >= 0; i--) {
17287                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17288                            if (res.addedChildPackages.containsKey(childPackageName)) {
17289                                res.removedInfo.removedChildPackages.removeAt(i);
17290                            } else {
17291                                PackageRemovedInfo childInfo = res.removedInfo
17292                                        .removedChildPackages.valueAt(i);
17293                                childInfo.removedForAllUsers = mPackages.get(
17294                                        childInfo.removedPackage) == null;
17295                            }
17296                        }
17297                    }
17298                }
17299            }
17300        }
17301    }
17302
17303    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17304            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17305            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17306            int installReason) {
17307        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17308                + ", old=" + deletedPackage);
17309
17310        final boolean disabledSystem;
17311
17312        // Remove existing system package
17313        removePackageLI(deletedPackage, true);
17314
17315        synchronized (mPackages) {
17316            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17317        }
17318        if (!disabledSystem) {
17319            // We didn't need to disable the .apk as a current system package,
17320            // which means we are replacing another update that is already
17321            // installed.  We need to make sure to delete the older one's .apk.
17322            res.removedInfo.args = createInstallArgsForExisting(0,
17323                    deletedPackage.applicationInfo.getCodePath(),
17324                    deletedPackage.applicationInfo.getResourcePath(),
17325                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17326        } else {
17327            res.removedInfo.args = null;
17328        }
17329
17330        // Successfully disabled the old package. Now proceed with re-installation
17331        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17332                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17333        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17334
17335        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17336        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17337                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17338
17339        PackageParser.Package newPackage = null;
17340        try {
17341            // Add the package to the internal data structures
17342            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17343
17344            // Set the update and install times
17345            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17346            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17347                    System.currentTimeMillis());
17348
17349            // Update the package dynamic state if succeeded
17350            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17351                // Now that the install succeeded make sure we remove data
17352                // directories for any child package the update removed.
17353                final int deletedChildCount = (deletedPackage.childPackages != null)
17354                        ? deletedPackage.childPackages.size() : 0;
17355                final int newChildCount = (newPackage.childPackages != null)
17356                        ? newPackage.childPackages.size() : 0;
17357                for (int i = 0; i < deletedChildCount; i++) {
17358                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17359                    boolean childPackageDeleted = true;
17360                    for (int j = 0; j < newChildCount; j++) {
17361                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17362                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17363                            childPackageDeleted = false;
17364                            break;
17365                        }
17366                    }
17367                    if (childPackageDeleted) {
17368                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17369                                deletedChildPkg.packageName);
17370                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17371                            PackageRemovedInfo removedChildRes = res.removedInfo
17372                                    .removedChildPackages.get(deletedChildPkg.packageName);
17373                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17374                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17375                        }
17376                    }
17377                }
17378
17379                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17380                        installReason);
17381                prepareAppDataAfterInstallLIF(newPackage);
17382
17383                mDexManager.notifyPackageUpdated(newPackage.packageName,
17384                            newPackage.baseCodePath, newPackage.splitCodePaths);
17385            }
17386        } catch (PackageManagerException e) {
17387            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17388            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17389        }
17390
17391        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17392            // Re installation failed. Restore old information
17393            // Remove new pkg information
17394            if (newPackage != null) {
17395                removeInstalledPackageLI(newPackage, true);
17396            }
17397            // Add back the old system package
17398            try {
17399                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17400            } catch (PackageManagerException e) {
17401                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17402            }
17403
17404            synchronized (mPackages) {
17405                if (disabledSystem) {
17406                    enableSystemPackageLPw(deletedPackage);
17407                }
17408
17409                // Ensure the installer package name up to date
17410                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17411
17412                // Update permissions for restored package
17413                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17414
17415                mSettings.writeLPr();
17416            }
17417
17418            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17419                    + " after failed upgrade");
17420        }
17421    }
17422
17423    /**
17424     * Checks whether the parent or any of the child packages have a change shared
17425     * user. For a package to be a valid update the shred users of the parent and
17426     * the children should match. We may later support changing child shared users.
17427     * @param oldPkg The updated package.
17428     * @param newPkg The update package.
17429     * @return The shared user that change between the versions.
17430     */
17431    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17432            PackageParser.Package newPkg) {
17433        // Check parent shared user
17434        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17435            return newPkg.packageName;
17436        }
17437        // Check child shared users
17438        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17439        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17440        for (int i = 0; i < newChildCount; i++) {
17441            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17442            // If this child was present, did it have the same shared user?
17443            for (int j = 0; j < oldChildCount; j++) {
17444                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17445                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17446                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17447                    return newChildPkg.packageName;
17448                }
17449            }
17450        }
17451        return null;
17452    }
17453
17454    private void removeNativeBinariesLI(PackageSetting ps) {
17455        // Remove the lib path for the parent package
17456        if (ps != null) {
17457            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17458            // Remove the lib path for the child packages
17459            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17460            for (int i = 0; i < childCount; i++) {
17461                PackageSetting childPs = null;
17462                synchronized (mPackages) {
17463                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17464                }
17465                if (childPs != null) {
17466                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17467                            .legacyNativeLibraryPathString);
17468                }
17469            }
17470        }
17471    }
17472
17473    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17474        // Enable the parent package
17475        mSettings.enableSystemPackageLPw(pkg.packageName);
17476        // Enable the child packages
17477        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17478        for (int i = 0; i < childCount; i++) {
17479            PackageParser.Package childPkg = pkg.childPackages.get(i);
17480            mSettings.enableSystemPackageLPw(childPkg.packageName);
17481        }
17482    }
17483
17484    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17485            PackageParser.Package newPkg) {
17486        // Disable the parent package (parent always replaced)
17487        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17488        // Disable the child packages
17489        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17490        for (int i = 0; i < childCount; i++) {
17491            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17492            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17493            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17494        }
17495        return disabled;
17496    }
17497
17498    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17499            String installerPackageName) {
17500        // Enable the parent package
17501        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17502        // Enable the child packages
17503        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17504        for (int i = 0; i < childCount; i++) {
17505            PackageParser.Package childPkg = pkg.childPackages.get(i);
17506            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17507        }
17508    }
17509
17510    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17511            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17512        // Update the parent package setting
17513        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17514                res, user, installReason);
17515        // Update the child packages setting
17516        final int childCount = (newPackage.childPackages != null)
17517                ? newPackage.childPackages.size() : 0;
17518        for (int i = 0; i < childCount; i++) {
17519            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17520            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17521            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17522                    childRes.origUsers, childRes, user, installReason);
17523        }
17524    }
17525
17526    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17527            String installerPackageName, int[] allUsers, int[] installedForUsers,
17528            PackageInstalledInfo res, UserHandle user, int installReason) {
17529        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17530
17531        String pkgName = newPackage.packageName;
17532        synchronized (mPackages) {
17533            //write settings. the installStatus will be incomplete at this stage.
17534            //note that the new package setting would have already been
17535            //added to mPackages. It hasn't been persisted yet.
17536            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17537            // TODO: Remove this write? It's also written at the end of this method
17538            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17539            mSettings.writeLPr();
17540            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17541        }
17542
17543        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17544        synchronized (mPackages) {
17545            updatePermissionsLPw(newPackage.packageName, newPackage,
17546                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17547                            ? UPDATE_PERMISSIONS_ALL : 0));
17548            // For system-bundled packages, we assume that installing an upgraded version
17549            // of the package implies that the user actually wants to run that new code,
17550            // so we enable the package.
17551            PackageSetting ps = mSettings.mPackages.get(pkgName);
17552            final int userId = user.getIdentifier();
17553            if (ps != null) {
17554                if (isSystemApp(newPackage)) {
17555                    if (DEBUG_INSTALL) {
17556                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17557                    }
17558                    // Enable system package for requested users
17559                    if (res.origUsers != null) {
17560                        for (int origUserId : res.origUsers) {
17561                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17562                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17563                                        origUserId, installerPackageName);
17564                            }
17565                        }
17566                    }
17567                    // Also convey the prior install/uninstall state
17568                    if (allUsers != null && installedForUsers != null) {
17569                        for (int currentUserId : allUsers) {
17570                            final boolean installed = ArrayUtils.contains(
17571                                    installedForUsers, currentUserId);
17572                            if (DEBUG_INSTALL) {
17573                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17574                            }
17575                            ps.setInstalled(installed, currentUserId);
17576                        }
17577                        // these install state changes will be persisted in the
17578                        // upcoming call to mSettings.writeLPr().
17579                    }
17580                }
17581                // It's implied that when a user requests installation, they want the app to be
17582                // installed and enabled.
17583                if (userId != UserHandle.USER_ALL) {
17584                    ps.setInstalled(true, userId);
17585                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17586                }
17587
17588                // When replacing an existing package, preserve the original install reason for all
17589                // users that had the package installed before.
17590                final Set<Integer> previousUserIds = new ArraySet<>();
17591                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17592                    final int installReasonCount = res.removedInfo.installReasons.size();
17593                    for (int i = 0; i < installReasonCount; i++) {
17594                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17595                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17596                        ps.setInstallReason(previousInstallReason, previousUserId);
17597                        previousUserIds.add(previousUserId);
17598                    }
17599                }
17600
17601                // Set install reason for users that are having the package newly installed.
17602                if (userId == UserHandle.USER_ALL) {
17603                    for (int currentUserId : sUserManager.getUserIds()) {
17604                        if (!previousUserIds.contains(currentUserId)) {
17605                            ps.setInstallReason(installReason, currentUserId);
17606                        }
17607                    }
17608                } else if (!previousUserIds.contains(userId)) {
17609                    ps.setInstallReason(installReason, userId);
17610                }
17611                mSettings.writeKernelMappingLPr(ps);
17612            }
17613            res.name = pkgName;
17614            res.uid = newPackage.applicationInfo.uid;
17615            res.pkg = newPackage;
17616            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17617            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17618            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17619            //to update install status
17620            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17621            mSettings.writeLPr();
17622            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17623        }
17624
17625        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17626    }
17627
17628    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17629        try {
17630            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17631            installPackageLI(args, res);
17632        } finally {
17633            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17634        }
17635    }
17636
17637    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17638        final int installFlags = args.installFlags;
17639        final String installerPackageName = args.installerPackageName;
17640        final String volumeUuid = args.volumeUuid;
17641        final File tmpPackageFile = new File(args.getCodePath());
17642        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17643        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17644                || (args.volumeUuid != null));
17645        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17646        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17647        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17648        final boolean virtualPreload =
17649                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17650        boolean replace = false;
17651        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17652        if (args.move != null) {
17653            // moving a complete application; perform an initial scan on the new install location
17654            scanFlags |= SCAN_INITIAL;
17655        }
17656        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17657            scanFlags |= SCAN_DONT_KILL_APP;
17658        }
17659        if (instantApp) {
17660            scanFlags |= SCAN_AS_INSTANT_APP;
17661        }
17662        if (fullApp) {
17663            scanFlags |= SCAN_AS_FULL_APP;
17664        }
17665        if (virtualPreload) {
17666            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17667        }
17668
17669        // Result object to be returned
17670        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17671        res.installerPackageName = installerPackageName;
17672
17673        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17674
17675        // Sanity check
17676        if (instantApp && (forwardLocked || onExternal)) {
17677            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17678                    + " external=" + onExternal);
17679            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17680            return;
17681        }
17682
17683        // Retrieve PackageSettings and parse package
17684        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17685                | PackageParser.PARSE_ENFORCE_CODE
17686                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17687                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17688                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17689                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17690        PackageParser pp = new PackageParser();
17691        pp.setSeparateProcesses(mSeparateProcesses);
17692        pp.setDisplayMetrics(mMetrics);
17693        pp.setCallback(mPackageParserCallback);
17694
17695        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17696        final PackageParser.Package pkg;
17697        try {
17698            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17699        } catch (PackageParserException e) {
17700            res.setError("Failed parse during installPackageLI", e);
17701            return;
17702        } finally {
17703            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17704        }
17705
17706        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17707        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17708            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17709            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17710                    "Instant app package must target O");
17711            return;
17712        }
17713        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17714            Slog.w(TAG, "Instant app package " + pkg.packageName
17715                    + " does not target targetSandboxVersion 2");
17716            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17717                    "Instant app package must use targetSanboxVersion 2");
17718            return;
17719        }
17720
17721        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17722            // Static shared libraries have synthetic package names
17723            renameStaticSharedLibraryPackage(pkg);
17724
17725            // No static shared libs on external storage
17726            if (onExternal) {
17727                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17728                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17729                        "Packages declaring static-shared libs cannot be updated");
17730                return;
17731            }
17732        }
17733
17734        // If we are installing a clustered package add results for the children
17735        if (pkg.childPackages != null) {
17736            synchronized (mPackages) {
17737                final int childCount = pkg.childPackages.size();
17738                for (int i = 0; i < childCount; i++) {
17739                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17740                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17741                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17742                    childRes.pkg = childPkg;
17743                    childRes.name = childPkg.packageName;
17744                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17745                    if (childPs != null) {
17746                        childRes.origUsers = childPs.queryInstalledUsers(
17747                                sUserManager.getUserIds(), true);
17748                    }
17749                    if ((mPackages.containsKey(childPkg.packageName))) {
17750                        childRes.removedInfo = new PackageRemovedInfo(this);
17751                        childRes.removedInfo.removedPackage = childPkg.packageName;
17752                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17753                    }
17754                    if (res.addedChildPackages == null) {
17755                        res.addedChildPackages = new ArrayMap<>();
17756                    }
17757                    res.addedChildPackages.put(childPkg.packageName, childRes);
17758                }
17759            }
17760        }
17761
17762        // If package doesn't declare API override, mark that we have an install
17763        // time CPU ABI override.
17764        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17765            pkg.cpuAbiOverride = args.abiOverride;
17766        }
17767
17768        String pkgName = res.name = pkg.packageName;
17769        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17770            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17771                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17772                return;
17773            }
17774        }
17775
17776        try {
17777            // either use what we've been given or parse directly from the APK
17778            if (args.certificates != null) {
17779                try {
17780                    PackageParser.populateCertificates(pkg, args.certificates);
17781                } catch (PackageParserException e) {
17782                    // there was something wrong with the certificates we were given;
17783                    // try to pull them from the APK
17784                    PackageParser.collectCertificates(pkg, parseFlags);
17785                }
17786            } else {
17787                PackageParser.collectCertificates(pkg, parseFlags);
17788            }
17789        } catch (PackageParserException e) {
17790            res.setError("Failed collect during installPackageLI", e);
17791            return;
17792        }
17793
17794        // Get rid of all references to package scan path via parser.
17795        pp = null;
17796        String oldCodePath = null;
17797        boolean systemApp = false;
17798        synchronized (mPackages) {
17799            // Check if installing already existing package
17800            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17801                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17802                if (pkg.mOriginalPackages != null
17803                        && pkg.mOriginalPackages.contains(oldName)
17804                        && mPackages.containsKey(oldName)) {
17805                    // This package is derived from an original package,
17806                    // and this device has been updating from that original
17807                    // name.  We must continue using the original name, so
17808                    // rename the new package here.
17809                    pkg.setPackageName(oldName);
17810                    pkgName = pkg.packageName;
17811                    replace = true;
17812                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17813                            + oldName + " pkgName=" + pkgName);
17814                } else if (mPackages.containsKey(pkgName)) {
17815                    // This package, under its official name, already exists
17816                    // on the device; we should replace it.
17817                    replace = true;
17818                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17819                }
17820
17821                // Child packages are installed through the parent package
17822                if (pkg.parentPackage != null) {
17823                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17824                            "Package " + pkg.packageName + " is child of package "
17825                                    + pkg.parentPackage.parentPackage + ". Child packages "
17826                                    + "can be updated only through the parent package.");
17827                    return;
17828                }
17829
17830                if (replace) {
17831                    // Prevent apps opting out from runtime permissions
17832                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17833                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17834                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17835                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17836                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17837                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17838                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17839                                        + " doesn't support runtime permissions but the old"
17840                                        + " target SDK " + oldTargetSdk + " does.");
17841                        return;
17842                    }
17843                    // Prevent apps from downgrading their targetSandbox.
17844                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17845                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17846                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17847                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17848                                "Package " + pkg.packageName + " new target sandbox "
17849                                + newTargetSandbox + " is incompatible with the previous value of"
17850                                + oldTargetSandbox + ".");
17851                        return;
17852                    }
17853
17854                    // Prevent installing of child packages
17855                    if (oldPackage.parentPackage != null) {
17856                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17857                                "Package " + pkg.packageName + " is child of package "
17858                                        + oldPackage.parentPackage + ". Child packages "
17859                                        + "can be updated only through the parent package.");
17860                        return;
17861                    }
17862                }
17863            }
17864
17865            PackageSetting ps = mSettings.mPackages.get(pkgName);
17866            if (ps != null) {
17867                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17868
17869                // Static shared libs have same package with different versions where
17870                // we internally use a synthetic package name to allow multiple versions
17871                // of the same package, therefore we need to compare signatures against
17872                // the package setting for the latest library version.
17873                PackageSetting signatureCheckPs = ps;
17874                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17875                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17876                    if (libraryEntry != null) {
17877                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17878                    }
17879                }
17880
17881                // Quick sanity check that we're signed correctly if updating;
17882                // we'll check this again later when scanning, but we want to
17883                // bail early here before tripping over redefined permissions.
17884                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17885                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17886                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17887                                + pkg.packageName + " upgrade keys do not match the "
17888                                + "previously installed version");
17889                        return;
17890                    }
17891                } else {
17892                    try {
17893                        verifySignaturesLP(signatureCheckPs, pkg);
17894                    } catch (PackageManagerException e) {
17895                        res.setError(e.error, e.getMessage());
17896                        return;
17897                    }
17898                }
17899
17900                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17901                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17902                    systemApp = (ps.pkg.applicationInfo.flags &
17903                            ApplicationInfo.FLAG_SYSTEM) != 0;
17904                }
17905                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17906            }
17907
17908            int N = pkg.permissions.size();
17909            for (int i = N-1; i >= 0; i--) {
17910                final PackageParser.Permission perm = pkg.permissions.get(i);
17911                final BasePermission bp =
17912                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17913
17914                // Don't allow anyone but the system to define ephemeral permissions.
17915                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17916                        && !systemApp) {
17917                    Slog.w(TAG, "Non-System package " + pkg.packageName
17918                            + " attempting to delcare ephemeral permission "
17919                            + perm.info.name + "; Removing ephemeral.");
17920                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17921                }
17922
17923                // Check whether the newly-scanned package wants to define an already-defined perm
17924                if (bp != null) {
17925                    // If the defining package is signed with our cert, it's okay.  This
17926                    // also includes the "updating the same package" case, of course.
17927                    // "updating same package" could also involve key-rotation.
17928                    final boolean sigsOk;
17929                    final String sourcePackageName = bp.getSourcePackageName();
17930                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17931                    if (sourcePackageName.equals(pkg.packageName)
17932                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17933                                    scanFlags))) {
17934                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17935                    } else {
17936                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17937                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17938                    }
17939                    if (!sigsOk) {
17940                        // If the owning package is the system itself, we log but allow
17941                        // install to proceed; we fail the install on all other permission
17942                        // redefinitions.
17943                        if (!sourcePackageName.equals("android")) {
17944                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17945                                    + pkg.packageName + " attempting to redeclare permission "
17946                                    + perm.info.name + " already owned by " + sourcePackageName);
17947                            res.origPermission = perm.info.name;
17948                            res.origPackage = sourcePackageName;
17949                            return;
17950                        } else {
17951                            Slog.w(TAG, "Package " + pkg.packageName
17952                                    + " attempting to redeclare system permission "
17953                                    + perm.info.name + "; ignoring new declaration");
17954                            pkg.permissions.remove(i);
17955                        }
17956                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17957                        // Prevent apps to change protection level to dangerous from any other
17958                        // type as this would allow a privilege escalation where an app adds a
17959                        // normal/signature permission in other app's group and later redefines
17960                        // it as dangerous leading to the group auto-grant.
17961                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17962                                == PermissionInfo.PROTECTION_DANGEROUS) {
17963                            if (bp != null && !bp.isRuntime()) {
17964                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17965                                        + "non-runtime permission " + perm.info.name
17966                                        + " to runtime; keeping old protection level");
17967                                perm.info.protectionLevel = bp.getProtectionLevel();
17968                            }
17969                        }
17970                    }
17971                }
17972            }
17973        }
17974
17975        if (systemApp) {
17976            if (onExternal) {
17977                // Abort update; system app can't be replaced with app on sdcard
17978                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17979                        "Cannot install updates to system apps on sdcard");
17980                return;
17981            } else if (instantApp) {
17982                // Abort update; system app can't be replaced with an instant app
17983                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17984                        "Cannot update a system app with an instant app");
17985                return;
17986            }
17987        }
17988
17989        if (args.move != null) {
17990            // We did an in-place move, so dex is ready to roll
17991            scanFlags |= SCAN_NO_DEX;
17992            scanFlags |= SCAN_MOVE;
17993
17994            synchronized (mPackages) {
17995                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17996                if (ps == null) {
17997                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17998                            "Missing settings for moved package " + pkgName);
17999                }
18000
18001                // We moved the entire application as-is, so bring over the
18002                // previously derived ABI information.
18003                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18004                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18005            }
18006
18007        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18008            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18009            scanFlags |= SCAN_NO_DEX;
18010
18011            try {
18012                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18013                    args.abiOverride : pkg.cpuAbiOverride);
18014                final boolean extractNativeLibs = !pkg.isLibrary();
18015                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18016                        extractNativeLibs, mAppLib32InstallDir);
18017            } catch (PackageManagerException pme) {
18018                Slog.e(TAG, "Error deriving application ABI", pme);
18019                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18020                return;
18021            }
18022
18023            // Shared libraries for the package need to be updated.
18024            synchronized (mPackages) {
18025                try {
18026                    updateSharedLibrariesLPr(pkg, null);
18027                } catch (PackageManagerException e) {
18028                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18029                }
18030            }
18031        }
18032
18033        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18034            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18035            return;
18036        }
18037
18038        // Verify if we need to dexopt the app.
18039        //
18040        // NOTE: it is *important* to call dexopt after doRename which will sync the
18041        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18042        //
18043        // We only need to dexopt if the package meets ALL of the following conditions:
18044        //   1) it is not forward locked.
18045        //   2) it is not on on an external ASEC container.
18046        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18047        //
18048        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18049        // complete, so we skip this step during installation. Instead, we'll take extra time
18050        // the first time the instant app starts. It's preferred to do it this way to provide
18051        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18052        // middle of running an instant app. The default behaviour can be overridden
18053        // via gservices.
18054        final boolean performDexopt = !forwardLocked
18055            && !pkg.applicationInfo.isExternalAsec()
18056            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18057                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18058
18059        if (performDexopt) {
18060            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18061            // Do not run PackageDexOptimizer through the local performDexOpt
18062            // method because `pkg` may not be in `mPackages` yet.
18063            //
18064            // Also, don't fail application installs if the dexopt step fails.
18065            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18066                REASON_INSTALL,
18067                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18068            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18069                null /* instructionSets */,
18070                getOrCreateCompilerPackageStats(pkg),
18071                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18072                dexoptOptions);
18073            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18074        }
18075
18076        // Notify BackgroundDexOptService that the package has been changed.
18077        // If this is an update of a package which used to fail to compile,
18078        // BackgroundDexOptService will remove it from its blacklist.
18079        // TODO: Layering violation
18080        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18081
18082        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18083
18084        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18085                "installPackageLI")) {
18086            if (replace) {
18087                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18088                    // Static libs have a synthetic package name containing the version
18089                    // and cannot be updated as an update would get a new package name,
18090                    // unless this is the exact same version code which is useful for
18091                    // development.
18092                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18093                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18094                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18095                                + "static-shared libs cannot be updated");
18096                        return;
18097                    }
18098                }
18099                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18100                        installerPackageName, res, args.installReason);
18101            } else {
18102                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18103                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18104            }
18105        }
18106
18107        synchronized (mPackages) {
18108            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18109            if (ps != null) {
18110                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18111                ps.setUpdateAvailable(false /*updateAvailable*/);
18112            }
18113
18114            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18115            for (int i = 0; i < childCount; i++) {
18116                PackageParser.Package childPkg = pkg.childPackages.get(i);
18117                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18118                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18119                if (childPs != null) {
18120                    childRes.newUsers = childPs.queryInstalledUsers(
18121                            sUserManager.getUserIds(), true);
18122                }
18123            }
18124
18125            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18126                updateSequenceNumberLP(ps, res.newUsers);
18127                updateInstantAppInstallerLocked(pkgName);
18128            }
18129        }
18130    }
18131
18132    private void startIntentFilterVerifications(int userId, boolean replacing,
18133            PackageParser.Package pkg) {
18134        if (mIntentFilterVerifierComponent == null) {
18135            Slog.w(TAG, "No IntentFilter verification will not be done as "
18136                    + "there is no IntentFilterVerifier available!");
18137            return;
18138        }
18139
18140        final int verifierUid = getPackageUid(
18141                mIntentFilterVerifierComponent.getPackageName(),
18142                MATCH_DEBUG_TRIAGED_MISSING,
18143                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18144
18145        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18146        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18147        mHandler.sendMessage(msg);
18148
18149        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18150        for (int i = 0; i < childCount; i++) {
18151            PackageParser.Package childPkg = pkg.childPackages.get(i);
18152            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18153            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18154            mHandler.sendMessage(msg);
18155        }
18156    }
18157
18158    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18159            PackageParser.Package pkg) {
18160        int size = pkg.activities.size();
18161        if (size == 0) {
18162            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18163                    "No activity, so no need to verify any IntentFilter!");
18164            return;
18165        }
18166
18167        final boolean hasDomainURLs = hasDomainURLs(pkg);
18168        if (!hasDomainURLs) {
18169            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18170                    "No domain URLs, so no need to verify any IntentFilter!");
18171            return;
18172        }
18173
18174        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18175                + " if any IntentFilter from the " + size
18176                + " Activities needs verification ...");
18177
18178        int count = 0;
18179        final String packageName = pkg.packageName;
18180
18181        synchronized (mPackages) {
18182            // If this is a new install and we see that we've already run verification for this
18183            // package, we have nothing to do: it means the state was restored from backup.
18184            if (!replacing) {
18185                IntentFilterVerificationInfo ivi =
18186                        mSettings.getIntentFilterVerificationLPr(packageName);
18187                if (ivi != null) {
18188                    if (DEBUG_DOMAIN_VERIFICATION) {
18189                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18190                                + ivi.getStatusString());
18191                    }
18192                    return;
18193                }
18194            }
18195
18196            // If any filters need to be verified, then all need to be.
18197            boolean needToVerify = false;
18198            for (PackageParser.Activity a : pkg.activities) {
18199                for (ActivityIntentInfo filter : a.intents) {
18200                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18201                        if (DEBUG_DOMAIN_VERIFICATION) {
18202                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18203                        }
18204                        needToVerify = true;
18205                        break;
18206                    }
18207                }
18208            }
18209
18210            if (needToVerify) {
18211                final int verificationId = mIntentFilterVerificationToken++;
18212                for (PackageParser.Activity a : pkg.activities) {
18213                    for (ActivityIntentInfo filter : a.intents) {
18214                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18215                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18216                                    "Verification needed for IntentFilter:" + filter.toString());
18217                            mIntentFilterVerifier.addOneIntentFilterVerification(
18218                                    verifierUid, userId, verificationId, filter, packageName);
18219                            count++;
18220                        }
18221                    }
18222                }
18223            }
18224        }
18225
18226        if (count > 0) {
18227            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18228                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18229                    +  " for userId:" + userId);
18230            mIntentFilterVerifier.startVerifications(userId);
18231        } else {
18232            if (DEBUG_DOMAIN_VERIFICATION) {
18233                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18234            }
18235        }
18236    }
18237
18238    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18239        final ComponentName cn  = filter.activity.getComponentName();
18240        final String packageName = cn.getPackageName();
18241
18242        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18243                packageName);
18244        if (ivi == null) {
18245            return true;
18246        }
18247        int status = ivi.getStatus();
18248        switch (status) {
18249            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18250            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18251                return true;
18252
18253            default:
18254                // Nothing to do
18255                return false;
18256        }
18257    }
18258
18259    private static boolean isMultiArch(ApplicationInfo info) {
18260        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18261    }
18262
18263    private static boolean isExternal(PackageParser.Package pkg) {
18264        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18265    }
18266
18267    private static boolean isExternal(PackageSetting ps) {
18268        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18269    }
18270
18271    private static boolean isSystemApp(PackageParser.Package pkg) {
18272        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18273    }
18274
18275    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18276        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18277    }
18278
18279    private static boolean isOemApp(PackageParser.Package pkg) {
18280        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
18281    }
18282
18283    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18284        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18285    }
18286
18287    private static boolean isSystemApp(PackageSetting ps) {
18288        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18289    }
18290
18291    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18292        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18293    }
18294
18295    private int packageFlagsToInstallFlags(PackageSetting ps) {
18296        int installFlags = 0;
18297        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18298            // This existing package was an external ASEC install when we have
18299            // the external flag without a UUID
18300            installFlags |= PackageManager.INSTALL_EXTERNAL;
18301        }
18302        if (ps.isForwardLocked()) {
18303            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18304        }
18305        return installFlags;
18306    }
18307
18308    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18309        if (isExternal(pkg)) {
18310            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18311                return StorageManager.UUID_PRIMARY_PHYSICAL;
18312            } else {
18313                return pkg.volumeUuid;
18314            }
18315        } else {
18316            return StorageManager.UUID_PRIVATE_INTERNAL;
18317        }
18318    }
18319
18320    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18321        if (isExternal(pkg)) {
18322            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18323                return mSettings.getExternalVersion();
18324            } else {
18325                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18326            }
18327        } else {
18328            return mSettings.getInternalVersion();
18329        }
18330    }
18331
18332    private void deleteTempPackageFiles() {
18333        final FilenameFilter filter = new FilenameFilter() {
18334            public boolean accept(File dir, String name) {
18335                return name.startsWith("vmdl") && name.endsWith(".tmp");
18336            }
18337        };
18338        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18339            file.delete();
18340        }
18341    }
18342
18343    @Override
18344    public void deletePackageAsUser(String packageName, int versionCode,
18345            IPackageDeleteObserver observer, int userId, int flags) {
18346        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18347                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18348    }
18349
18350    @Override
18351    public void deletePackageVersioned(VersionedPackage versionedPackage,
18352            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18353        final int callingUid = Binder.getCallingUid();
18354        mContext.enforceCallingOrSelfPermission(
18355                android.Manifest.permission.DELETE_PACKAGES, null);
18356        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18357        Preconditions.checkNotNull(versionedPackage);
18358        Preconditions.checkNotNull(observer);
18359        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18360                PackageManager.VERSION_CODE_HIGHEST,
18361                Integer.MAX_VALUE, "versionCode must be >= -1");
18362
18363        final String packageName = versionedPackage.getPackageName();
18364        final int versionCode = versionedPackage.getVersionCode();
18365        final String internalPackageName;
18366        synchronized (mPackages) {
18367            // Normalize package name to handle renamed packages and static libs
18368            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18369                    versionedPackage.getVersionCode());
18370        }
18371
18372        final int uid = Binder.getCallingUid();
18373        if (!isOrphaned(internalPackageName)
18374                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18375            try {
18376                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18377                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18378                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18379                observer.onUserActionRequired(intent);
18380            } catch (RemoteException re) {
18381            }
18382            return;
18383        }
18384        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18385        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18386        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18387            mContext.enforceCallingOrSelfPermission(
18388                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18389                    "deletePackage for user " + userId);
18390        }
18391
18392        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18393            try {
18394                observer.onPackageDeleted(packageName,
18395                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18396            } catch (RemoteException re) {
18397            }
18398            return;
18399        }
18400
18401        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18402            try {
18403                observer.onPackageDeleted(packageName,
18404                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18405            } catch (RemoteException re) {
18406            }
18407            return;
18408        }
18409
18410        if (DEBUG_REMOVE) {
18411            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18412                    + " deleteAllUsers: " + deleteAllUsers + " version="
18413                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18414                    ? "VERSION_CODE_HIGHEST" : versionCode));
18415        }
18416        // Queue up an async operation since the package deletion may take a little while.
18417        mHandler.post(new Runnable() {
18418            public void run() {
18419                mHandler.removeCallbacks(this);
18420                int returnCode;
18421                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18422                boolean doDeletePackage = true;
18423                if (ps != null) {
18424                    final boolean targetIsInstantApp =
18425                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18426                    doDeletePackage = !targetIsInstantApp
18427                            || canViewInstantApps;
18428                }
18429                if (doDeletePackage) {
18430                    if (!deleteAllUsers) {
18431                        returnCode = deletePackageX(internalPackageName, versionCode,
18432                                userId, deleteFlags);
18433                    } else {
18434                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18435                                internalPackageName, users);
18436                        // If nobody is blocking uninstall, proceed with delete for all users
18437                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18438                            returnCode = deletePackageX(internalPackageName, versionCode,
18439                                    userId, deleteFlags);
18440                        } else {
18441                            // Otherwise uninstall individually for users with blockUninstalls=false
18442                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18443                            for (int userId : users) {
18444                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18445                                    returnCode = deletePackageX(internalPackageName, versionCode,
18446                                            userId, userFlags);
18447                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18448                                        Slog.w(TAG, "Package delete failed for user " + userId
18449                                                + ", returnCode " + returnCode);
18450                                    }
18451                                }
18452                            }
18453                            // The app has only been marked uninstalled for certain users.
18454                            // We still need to report that delete was blocked
18455                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18456                        }
18457                    }
18458                } else {
18459                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18460                }
18461                try {
18462                    observer.onPackageDeleted(packageName, returnCode, null);
18463                } catch (RemoteException e) {
18464                    Log.i(TAG, "Observer no longer exists.");
18465                } //end catch
18466            } //end run
18467        });
18468    }
18469
18470    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18471        if (pkg.staticSharedLibName != null) {
18472            return pkg.manifestPackageName;
18473        }
18474        return pkg.packageName;
18475    }
18476
18477    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18478        // Handle renamed packages
18479        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18480        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18481
18482        // Is this a static library?
18483        SparseArray<SharedLibraryEntry> versionedLib =
18484                mStaticLibsByDeclaringPackage.get(packageName);
18485        if (versionedLib == null || versionedLib.size() <= 0) {
18486            return packageName;
18487        }
18488
18489        // Figure out which lib versions the caller can see
18490        SparseIntArray versionsCallerCanSee = null;
18491        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18492        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18493                && callingAppId != Process.ROOT_UID) {
18494            versionsCallerCanSee = new SparseIntArray();
18495            String libName = versionedLib.valueAt(0).info.getName();
18496            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18497            if (uidPackages != null) {
18498                for (String uidPackage : uidPackages) {
18499                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18500                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18501                    if (libIdx >= 0) {
18502                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18503                        versionsCallerCanSee.append(libVersion, libVersion);
18504                    }
18505                }
18506            }
18507        }
18508
18509        // Caller can see nothing - done
18510        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18511            return packageName;
18512        }
18513
18514        // Find the version the caller can see and the app version code
18515        SharedLibraryEntry highestVersion = null;
18516        final int versionCount = versionedLib.size();
18517        for (int i = 0; i < versionCount; i++) {
18518            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18519            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18520                    libEntry.info.getVersion()) < 0) {
18521                continue;
18522            }
18523            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18524            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18525                if (libVersionCode == versionCode) {
18526                    return libEntry.apk;
18527                }
18528            } else if (highestVersion == null) {
18529                highestVersion = libEntry;
18530            } else if (libVersionCode  > highestVersion.info
18531                    .getDeclaringPackage().getVersionCode()) {
18532                highestVersion = libEntry;
18533            }
18534        }
18535
18536        if (highestVersion != null) {
18537            return highestVersion.apk;
18538        }
18539
18540        return packageName;
18541    }
18542
18543    boolean isCallerVerifier(int callingUid) {
18544        final int callingUserId = UserHandle.getUserId(callingUid);
18545        return mRequiredVerifierPackage != null &&
18546                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18547    }
18548
18549    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18550        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18551              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18552            return true;
18553        }
18554        final int callingUserId = UserHandle.getUserId(callingUid);
18555        // If the caller installed the pkgName, then allow it to silently uninstall.
18556        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18557            return true;
18558        }
18559
18560        // Allow package verifier to silently uninstall.
18561        if (mRequiredVerifierPackage != null &&
18562                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18563            return true;
18564        }
18565
18566        // Allow package uninstaller to silently uninstall.
18567        if (mRequiredUninstallerPackage != null &&
18568                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18569            return true;
18570        }
18571
18572        // Allow storage manager to silently uninstall.
18573        if (mStorageManagerPackage != null &&
18574                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18575            return true;
18576        }
18577
18578        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18579        // uninstall for device owner provisioning.
18580        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18581                == PERMISSION_GRANTED) {
18582            return true;
18583        }
18584
18585        return false;
18586    }
18587
18588    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18589        int[] result = EMPTY_INT_ARRAY;
18590        for (int userId : userIds) {
18591            if (getBlockUninstallForUser(packageName, userId)) {
18592                result = ArrayUtils.appendInt(result, userId);
18593            }
18594        }
18595        return result;
18596    }
18597
18598    @Override
18599    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18600        final int callingUid = Binder.getCallingUid();
18601        if (getInstantAppPackageName(callingUid) != null
18602                && !isCallerSameApp(packageName, callingUid)) {
18603            return false;
18604        }
18605        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18606    }
18607
18608    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18609        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18610                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18611        try {
18612            if (dpm != null) {
18613                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18614                        /* callingUserOnly =*/ false);
18615                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18616                        : deviceOwnerComponentName.getPackageName();
18617                // Does the package contains the device owner?
18618                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18619                // this check is probably not needed, since DO should be registered as a device
18620                // admin on some user too. (Original bug for this: b/17657954)
18621                if (packageName.equals(deviceOwnerPackageName)) {
18622                    return true;
18623                }
18624                // Does it contain a device admin for any user?
18625                int[] users;
18626                if (userId == UserHandle.USER_ALL) {
18627                    users = sUserManager.getUserIds();
18628                } else {
18629                    users = new int[]{userId};
18630                }
18631                for (int i = 0; i < users.length; ++i) {
18632                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18633                        return true;
18634                    }
18635                }
18636            }
18637        } catch (RemoteException e) {
18638        }
18639        return false;
18640    }
18641
18642    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18643        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18644    }
18645
18646    /**
18647     *  This method is an internal method that could be get invoked either
18648     *  to delete an installed package or to clean up a failed installation.
18649     *  After deleting an installed package, a broadcast is sent to notify any
18650     *  listeners that the package has been removed. For cleaning up a failed
18651     *  installation, the broadcast is not necessary since the package's
18652     *  installation wouldn't have sent the initial broadcast either
18653     *  The key steps in deleting a package are
18654     *  deleting the package information in internal structures like mPackages,
18655     *  deleting the packages base directories through installd
18656     *  updating mSettings to reflect current status
18657     *  persisting settings for later use
18658     *  sending a broadcast if necessary
18659     */
18660    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18661        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18662        final boolean res;
18663
18664        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18665                ? UserHandle.USER_ALL : userId;
18666
18667        if (isPackageDeviceAdmin(packageName, removeUser)) {
18668            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18669            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18670        }
18671
18672        PackageSetting uninstalledPs = null;
18673        PackageParser.Package pkg = null;
18674
18675        // for the uninstall-updates case and restricted profiles, remember the per-
18676        // user handle installed state
18677        int[] allUsers;
18678        synchronized (mPackages) {
18679            uninstalledPs = mSettings.mPackages.get(packageName);
18680            if (uninstalledPs == null) {
18681                Slog.w(TAG, "Not removing non-existent package " + packageName);
18682                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18683            }
18684
18685            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18686                    && uninstalledPs.versionCode != versionCode) {
18687                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18688                        + uninstalledPs.versionCode + " != " + versionCode);
18689                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18690            }
18691
18692            // Static shared libs can be declared by any package, so let us not
18693            // allow removing a package if it provides a lib others depend on.
18694            pkg = mPackages.get(packageName);
18695
18696            allUsers = sUserManager.getUserIds();
18697
18698            if (pkg != null && pkg.staticSharedLibName != null) {
18699                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18700                        pkg.staticSharedLibVersion);
18701                if (libEntry != null) {
18702                    for (int currUserId : allUsers) {
18703                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18704                            continue;
18705                        }
18706                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18707                                libEntry.info, 0, currUserId);
18708                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18709                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18710                                    + " hosting lib " + libEntry.info.getName() + " version "
18711                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18712                                    + " for user " + currUserId);
18713                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18714                        }
18715                    }
18716                }
18717            }
18718
18719            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18720        }
18721
18722        final int freezeUser;
18723        if (isUpdatedSystemApp(uninstalledPs)
18724                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18725            // We're downgrading a system app, which will apply to all users, so
18726            // freeze them all during the downgrade
18727            freezeUser = UserHandle.USER_ALL;
18728        } else {
18729            freezeUser = removeUser;
18730        }
18731
18732        synchronized (mInstallLock) {
18733            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18734            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18735                    deleteFlags, "deletePackageX")) {
18736                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18737                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18738            }
18739            synchronized (mPackages) {
18740                if (res) {
18741                    if (pkg != null) {
18742                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18743                    }
18744                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18745                    updateInstantAppInstallerLocked(packageName);
18746                }
18747            }
18748        }
18749
18750        if (res) {
18751            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18752            info.sendPackageRemovedBroadcasts(killApp);
18753            info.sendSystemPackageUpdatedBroadcasts();
18754            info.sendSystemPackageAppearedBroadcasts();
18755        }
18756        // Force a gc here.
18757        Runtime.getRuntime().gc();
18758        // Delete the resources here after sending the broadcast to let
18759        // other processes clean up before deleting resources.
18760        if (info.args != null) {
18761            synchronized (mInstallLock) {
18762                info.args.doPostDeleteLI(true);
18763            }
18764        }
18765
18766        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18767    }
18768
18769    static class PackageRemovedInfo {
18770        final PackageSender packageSender;
18771        String removedPackage;
18772        String installerPackageName;
18773        int uid = -1;
18774        int removedAppId = -1;
18775        int[] origUsers;
18776        int[] removedUsers = null;
18777        int[] broadcastUsers = null;
18778        SparseArray<Integer> installReasons;
18779        boolean isRemovedPackageSystemUpdate = false;
18780        boolean isUpdate;
18781        boolean dataRemoved;
18782        boolean removedForAllUsers;
18783        boolean isStaticSharedLib;
18784        // Clean up resources deleted packages.
18785        InstallArgs args = null;
18786        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18787        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18788
18789        PackageRemovedInfo(PackageSender packageSender) {
18790            this.packageSender = packageSender;
18791        }
18792
18793        void sendPackageRemovedBroadcasts(boolean killApp) {
18794            sendPackageRemovedBroadcastInternal(killApp);
18795            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18796            for (int i = 0; i < childCount; i++) {
18797                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18798                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18799            }
18800        }
18801
18802        void sendSystemPackageUpdatedBroadcasts() {
18803            if (isRemovedPackageSystemUpdate) {
18804                sendSystemPackageUpdatedBroadcastsInternal();
18805                final int childCount = (removedChildPackages != null)
18806                        ? removedChildPackages.size() : 0;
18807                for (int i = 0; i < childCount; i++) {
18808                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18809                    if (childInfo.isRemovedPackageSystemUpdate) {
18810                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18811                    }
18812                }
18813            }
18814        }
18815
18816        void sendSystemPackageAppearedBroadcasts() {
18817            final int packageCount = (appearedChildPackages != null)
18818                    ? appearedChildPackages.size() : 0;
18819            for (int i = 0; i < packageCount; i++) {
18820                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18821                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18822                    true /*sendBootCompleted*/, false /*startReceiver*/,
18823                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18824            }
18825        }
18826
18827        private void sendSystemPackageUpdatedBroadcastsInternal() {
18828            Bundle extras = new Bundle(2);
18829            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18830            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18831            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18832                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18833            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18834                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18835            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18836                null, null, 0, removedPackage, null, null);
18837            if (installerPackageName != null) {
18838                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18839                        removedPackage, extras, 0 /*flags*/,
18840                        installerPackageName, null, null);
18841                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18842                        removedPackage, extras, 0 /*flags*/,
18843                        installerPackageName, null, null);
18844            }
18845        }
18846
18847        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18848            // Don't send static shared library removal broadcasts as these
18849            // libs are visible only the the apps that depend on them an one
18850            // cannot remove the library if it has a dependency.
18851            if (isStaticSharedLib) {
18852                return;
18853            }
18854            Bundle extras = new Bundle(2);
18855            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18856            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18857            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18858            if (isUpdate || isRemovedPackageSystemUpdate) {
18859                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18860            }
18861            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18862            if (removedPackage != null) {
18863                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18864                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18865                if (installerPackageName != null) {
18866                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18867                            removedPackage, extras, 0 /*flags*/,
18868                            installerPackageName, null, broadcastUsers);
18869                }
18870                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18871                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18872                        removedPackage, extras,
18873                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18874                        null, null, broadcastUsers);
18875                }
18876            }
18877            if (removedAppId >= 0) {
18878                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18879                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18880                    null, null, broadcastUsers);
18881            }
18882        }
18883
18884        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18885            removedUsers = userIds;
18886            if (removedUsers == null) {
18887                broadcastUsers = null;
18888                return;
18889            }
18890
18891            broadcastUsers = EMPTY_INT_ARRAY;
18892            for (int i = userIds.length - 1; i >= 0; --i) {
18893                final int userId = userIds[i];
18894                if (deletedPackageSetting.getInstantApp(userId)) {
18895                    continue;
18896                }
18897                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18898            }
18899        }
18900    }
18901
18902    /*
18903     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18904     * flag is not set, the data directory is removed as well.
18905     * make sure this flag is set for partially installed apps. If not its meaningless to
18906     * delete a partially installed application.
18907     */
18908    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18909            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18910        String packageName = ps.name;
18911        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18912        // Retrieve object to delete permissions for shared user later on
18913        final PackageParser.Package deletedPkg;
18914        final PackageSetting deletedPs;
18915        // reader
18916        synchronized (mPackages) {
18917            deletedPkg = mPackages.get(packageName);
18918            deletedPs = mSettings.mPackages.get(packageName);
18919            if (outInfo != null) {
18920                outInfo.removedPackage = packageName;
18921                outInfo.installerPackageName = ps.installerPackageName;
18922                outInfo.isStaticSharedLib = deletedPkg != null
18923                        && deletedPkg.staticSharedLibName != null;
18924                outInfo.populateUsers(deletedPs == null ? null
18925                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18926            }
18927        }
18928
18929        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18930
18931        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18932            final PackageParser.Package resolvedPkg;
18933            if (deletedPkg != null) {
18934                resolvedPkg = deletedPkg;
18935            } else {
18936                // We don't have a parsed package when it lives on an ejected
18937                // adopted storage device, so fake something together
18938                resolvedPkg = new PackageParser.Package(ps.name);
18939                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18940            }
18941            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18942                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18943            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18944            if (outInfo != null) {
18945                outInfo.dataRemoved = true;
18946            }
18947            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18948        }
18949
18950        int removedAppId = -1;
18951
18952        // writer
18953        synchronized (mPackages) {
18954            boolean installedStateChanged = false;
18955            if (deletedPs != null) {
18956                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18957                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18958                    clearDefaultBrowserIfNeeded(packageName);
18959                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18960                    removedAppId = mSettings.removePackageLPw(packageName);
18961                    if (outInfo != null) {
18962                        outInfo.removedAppId = removedAppId;
18963                    }
18964                    updatePermissionsLPw(deletedPs.name, null, 0);
18965                    if (deletedPs.sharedUser != null) {
18966                        // Remove permissions associated with package. Since runtime
18967                        // permissions are per user we have to kill the removed package
18968                        // or packages running under the shared user of the removed
18969                        // package if revoking the permissions requested only by the removed
18970                        // package is successful and this causes a change in gids.
18971                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18972                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18973                                    userId);
18974                            if (userIdToKill == UserHandle.USER_ALL
18975                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18976                                // If gids changed for this user, kill all affected packages.
18977                                mHandler.post(new Runnable() {
18978                                    @Override
18979                                    public void run() {
18980                                        // This has to happen with no lock held.
18981                                        killApplication(deletedPs.name, deletedPs.appId,
18982                                                KILL_APP_REASON_GIDS_CHANGED);
18983                                    }
18984                                });
18985                                break;
18986                            }
18987                        }
18988                    }
18989                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18990                }
18991                // make sure to preserve per-user disabled state if this removal was just
18992                // a downgrade of a system app to the factory package
18993                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18994                    if (DEBUG_REMOVE) {
18995                        Slog.d(TAG, "Propagating install state across downgrade");
18996                    }
18997                    for (int userId : allUserHandles) {
18998                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18999                        if (DEBUG_REMOVE) {
19000                            Slog.d(TAG, "    user " + userId + " => " + installed);
19001                        }
19002                        if (installed != ps.getInstalled(userId)) {
19003                            installedStateChanged = true;
19004                        }
19005                        ps.setInstalled(installed, userId);
19006                    }
19007                }
19008            }
19009            // can downgrade to reader
19010            if (writeSettings) {
19011                // Save settings now
19012                mSettings.writeLPr();
19013            }
19014            if (installedStateChanged) {
19015                mSettings.writeKernelMappingLPr(ps);
19016            }
19017        }
19018        if (removedAppId != -1) {
19019            // A user ID was deleted here. Go through all users and remove it
19020            // from KeyStore.
19021            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19022        }
19023    }
19024
19025    static boolean locationIsPrivileged(File path) {
19026        try {
19027            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19028                    .getCanonicalPath();
19029            return path.getCanonicalPath().startsWith(privilegedAppDir);
19030        } catch (IOException e) {
19031            Slog.e(TAG, "Unable to access code path " + path);
19032        }
19033        return false;
19034    }
19035
19036    static boolean locationIsOem(File path) {
19037        try {
19038            return path.getCanonicalPath().startsWith(
19039                    Environment.getOemDirectory().getCanonicalPath());
19040        } catch (IOException e) {
19041            Slog.e(TAG, "Unable to access code path " + path);
19042        }
19043        return false;
19044    }
19045
19046    /*
19047     * Tries to delete system package.
19048     */
19049    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19050            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19051            boolean writeSettings) {
19052        if (deletedPs.parentPackageName != null) {
19053            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19054            return false;
19055        }
19056
19057        final boolean applyUserRestrictions
19058                = (allUserHandles != null) && (outInfo.origUsers != null);
19059        final PackageSetting disabledPs;
19060        // Confirm if the system package has been updated
19061        // An updated system app can be deleted. This will also have to restore
19062        // the system pkg from system partition
19063        // reader
19064        synchronized (mPackages) {
19065            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19066        }
19067
19068        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19069                + " disabledPs=" + disabledPs);
19070
19071        if (disabledPs == null) {
19072            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19073            return false;
19074        } else if (DEBUG_REMOVE) {
19075            Slog.d(TAG, "Deleting system pkg from data partition");
19076        }
19077
19078        if (DEBUG_REMOVE) {
19079            if (applyUserRestrictions) {
19080                Slog.d(TAG, "Remembering install states:");
19081                for (int userId : allUserHandles) {
19082                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19083                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19084                }
19085            }
19086        }
19087
19088        // Delete the updated package
19089        outInfo.isRemovedPackageSystemUpdate = true;
19090        if (outInfo.removedChildPackages != null) {
19091            final int childCount = (deletedPs.childPackageNames != null)
19092                    ? deletedPs.childPackageNames.size() : 0;
19093            for (int i = 0; i < childCount; i++) {
19094                String childPackageName = deletedPs.childPackageNames.get(i);
19095                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19096                        .contains(childPackageName)) {
19097                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19098                            childPackageName);
19099                    if (childInfo != null) {
19100                        childInfo.isRemovedPackageSystemUpdate = true;
19101                    }
19102                }
19103            }
19104        }
19105
19106        if (disabledPs.versionCode < deletedPs.versionCode) {
19107            // Delete data for downgrades
19108            flags &= ~PackageManager.DELETE_KEEP_DATA;
19109        } else {
19110            // Preserve data by setting flag
19111            flags |= PackageManager.DELETE_KEEP_DATA;
19112        }
19113
19114        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19115                outInfo, writeSettings, disabledPs.pkg);
19116        if (!ret) {
19117            return false;
19118        }
19119
19120        // writer
19121        synchronized (mPackages) {
19122            // NOTE: The system package always needs to be enabled; even if it's for
19123            // a compressed stub. If we don't, installing the system package fails
19124            // during scan [scanning checks the disabled packages]. We will reverse
19125            // this later, after we've "installed" the stub.
19126            // Reinstate the old system package
19127            enableSystemPackageLPw(disabledPs.pkg);
19128            // Remove any native libraries from the upgraded package.
19129            removeNativeBinariesLI(deletedPs);
19130        }
19131
19132        // Install the system package
19133        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19134        try {
19135            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19136                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19137        } catch (PackageManagerException e) {
19138            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19139                    + e.getMessage());
19140            return false;
19141        } finally {
19142            if (disabledPs.pkg.isStub) {
19143                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19144            }
19145        }
19146        return true;
19147    }
19148
19149    /**
19150     * Installs a package that's already on the system partition.
19151     */
19152    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19153            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19154            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19155                    throws PackageManagerException {
19156        int parseFlags = mDefParseFlags
19157                | PackageParser.PARSE_MUST_BE_APK
19158                | PackageParser.PARSE_IS_SYSTEM
19159                | PackageParser.PARSE_IS_SYSTEM_DIR;
19160        if (isPrivileged || locationIsPrivileged(codePath)) {
19161            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19162        }
19163        if (locationIsOem(codePath)) {
19164            parseFlags |= PackageParser.PARSE_IS_OEM;
19165        }
19166
19167        final PackageParser.Package newPkg =
19168                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19169
19170        try {
19171            // update shared libraries for the newly re-installed system package
19172            updateSharedLibrariesLPr(newPkg, null);
19173        } catch (PackageManagerException e) {
19174            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19175        }
19176
19177        prepareAppDataAfterInstallLIF(newPkg);
19178
19179        // writer
19180        synchronized (mPackages) {
19181            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19182
19183            // Propagate the permissions state as we do not want to drop on the floor
19184            // runtime permissions. The update permissions method below will take
19185            // care of removing obsolete permissions and grant install permissions.
19186            if (origPermissionState != null) {
19187                ps.getPermissionsState().copyFrom(origPermissionState);
19188            }
19189            updatePermissionsLPw(newPkg.packageName, newPkg,
19190                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19191
19192            final boolean applyUserRestrictions
19193                    = (allUserHandles != null) && (origUserHandles != null);
19194            if (applyUserRestrictions) {
19195                boolean installedStateChanged = false;
19196                if (DEBUG_REMOVE) {
19197                    Slog.d(TAG, "Propagating install state across reinstall");
19198                }
19199                for (int userId : allUserHandles) {
19200                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19201                    if (DEBUG_REMOVE) {
19202                        Slog.d(TAG, "    user " + userId + " => " + installed);
19203                    }
19204                    if (installed != ps.getInstalled(userId)) {
19205                        installedStateChanged = true;
19206                    }
19207                    ps.setInstalled(installed, userId);
19208
19209                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19210                }
19211                // Regardless of writeSettings we need to ensure that this restriction
19212                // state propagation is persisted
19213                mSettings.writeAllUsersPackageRestrictionsLPr();
19214                if (installedStateChanged) {
19215                    mSettings.writeKernelMappingLPr(ps);
19216                }
19217            }
19218            // can downgrade to reader here
19219            if (writeSettings) {
19220                mSettings.writeLPr();
19221            }
19222        }
19223        return newPkg;
19224    }
19225
19226    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19227            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19228            PackageRemovedInfo outInfo, boolean writeSettings,
19229            PackageParser.Package replacingPackage) {
19230        synchronized (mPackages) {
19231            if (outInfo != null) {
19232                outInfo.uid = ps.appId;
19233            }
19234
19235            if (outInfo != null && outInfo.removedChildPackages != null) {
19236                final int childCount = (ps.childPackageNames != null)
19237                        ? ps.childPackageNames.size() : 0;
19238                for (int i = 0; i < childCount; i++) {
19239                    String childPackageName = ps.childPackageNames.get(i);
19240                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19241                    if (childPs == null) {
19242                        return false;
19243                    }
19244                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19245                            childPackageName);
19246                    if (childInfo != null) {
19247                        childInfo.uid = childPs.appId;
19248                    }
19249                }
19250            }
19251        }
19252
19253        // Delete package data from internal structures and also remove data if flag is set
19254        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19255
19256        // Delete the child packages data
19257        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19258        for (int i = 0; i < childCount; i++) {
19259            PackageSetting childPs;
19260            synchronized (mPackages) {
19261                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19262            }
19263            if (childPs != null) {
19264                PackageRemovedInfo childOutInfo = (outInfo != null
19265                        && outInfo.removedChildPackages != null)
19266                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19267                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19268                        && (replacingPackage != null
19269                        && !replacingPackage.hasChildPackage(childPs.name))
19270                        ? flags & ~DELETE_KEEP_DATA : flags;
19271                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19272                        deleteFlags, writeSettings);
19273            }
19274        }
19275
19276        // Delete application code and resources only for parent packages
19277        if (ps.parentPackageName == null) {
19278            if (deleteCodeAndResources && (outInfo != null)) {
19279                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19280                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19281                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19282            }
19283        }
19284
19285        return true;
19286    }
19287
19288    @Override
19289    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19290            int userId) {
19291        mContext.enforceCallingOrSelfPermission(
19292                android.Manifest.permission.DELETE_PACKAGES, null);
19293        synchronized (mPackages) {
19294            // Cannot block uninstall of static shared libs as they are
19295            // considered a part of the using app (emulating static linking).
19296            // Also static libs are installed always on internal storage.
19297            PackageParser.Package pkg = mPackages.get(packageName);
19298            if (pkg != null && pkg.staticSharedLibName != null) {
19299                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19300                        + " providing static shared library: " + pkg.staticSharedLibName);
19301                return false;
19302            }
19303            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19304            mSettings.writePackageRestrictionsLPr(userId);
19305        }
19306        return true;
19307    }
19308
19309    @Override
19310    public boolean getBlockUninstallForUser(String packageName, int userId) {
19311        synchronized (mPackages) {
19312            final PackageSetting ps = mSettings.mPackages.get(packageName);
19313            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19314                return false;
19315            }
19316            return mSettings.getBlockUninstallLPr(userId, packageName);
19317        }
19318    }
19319
19320    @Override
19321    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19322        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19323        synchronized (mPackages) {
19324            PackageSetting ps = mSettings.mPackages.get(packageName);
19325            if (ps == null) {
19326                Log.w(TAG, "Package doesn't exist: " + packageName);
19327                return false;
19328            }
19329            if (systemUserApp) {
19330                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19331            } else {
19332                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19333            }
19334            mSettings.writeLPr();
19335        }
19336        return true;
19337    }
19338
19339    /*
19340     * This method handles package deletion in general
19341     */
19342    private boolean deletePackageLIF(String packageName, UserHandle user,
19343            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19344            PackageRemovedInfo outInfo, boolean writeSettings,
19345            PackageParser.Package replacingPackage) {
19346        if (packageName == null) {
19347            Slog.w(TAG, "Attempt to delete null packageName.");
19348            return false;
19349        }
19350
19351        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19352
19353        PackageSetting ps;
19354        synchronized (mPackages) {
19355            ps = mSettings.mPackages.get(packageName);
19356            if (ps == null) {
19357                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19358                return false;
19359            }
19360
19361            if (ps.parentPackageName != null && (!isSystemApp(ps)
19362                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19363                if (DEBUG_REMOVE) {
19364                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19365                            + ((user == null) ? UserHandle.USER_ALL : user));
19366                }
19367                final int removedUserId = (user != null) ? user.getIdentifier()
19368                        : UserHandle.USER_ALL;
19369                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19370                    return false;
19371                }
19372                markPackageUninstalledForUserLPw(ps, user);
19373                scheduleWritePackageRestrictionsLocked(user);
19374                return true;
19375            }
19376        }
19377
19378        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19379                && user.getIdentifier() != UserHandle.USER_ALL)) {
19380            // The caller is asking that the package only be deleted for a single
19381            // user.  To do this, we just mark its uninstalled state and delete
19382            // its data. If this is a system app, we only allow this to happen if
19383            // they have set the special DELETE_SYSTEM_APP which requests different
19384            // semantics than normal for uninstalling system apps.
19385            markPackageUninstalledForUserLPw(ps, user);
19386
19387            if (!isSystemApp(ps)) {
19388                // Do not uninstall the APK if an app should be cached
19389                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19390                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19391                    // Other user still have this package installed, so all
19392                    // we need to do is clear this user's data and save that
19393                    // it is uninstalled.
19394                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19395                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19396                        return false;
19397                    }
19398                    scheduleWritePackageRestrictionsLocked(user);
19399                    return true;
19400                } else {
19401                    // We need to set it back to 'installed' so the uninstall
19402                    // broadcasts will be sent correctly.
19403                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19404                    ps.setInstalled(true, user.getIdentifier());
19405                    mSettings.writeKernelMappingLPr(ps);
19406                }
19407            } else {
19408                // This is a system app, so we assume that the
19409                // other users still have this package installed, so all
19410                // we need to do is clear this user's data and save that
19411                // it is uninstalled.
19412                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19413                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19414                    return false;
19415                }
19416                scheduleWritePackageRestrictionsLocked(user);
19417                return true;
19418            }
19419        }
19420
19421        // If we are deleting a composite package for all users, keep track
19422        // of result for each child.
19423        if (ps.childPackageNames != null && outInfo != null) {
19424            synchronized (mPackages) {
19425                final int childCount = ps.childPackageNames.size();
19426                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19427                for (int i = 0; i < childCount; i++) {
19428                    String childPackageName = ps.childPackageNames.get(i);
19429                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19430                    childInfo.removedPackage = childPackageName;
19431                    childInfo.installerPackageName = ps.installerPackageName;
19432                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19433                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19434                    if (childPs != null) {
19435                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19436                    }
19437                }
19438            }
19439        }
19440
19441        boolean ret = false;
19442        if (isSystemApp(ps)) {
19443            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19444            // When an updated system application is deleted we delete the existing resources
19445            // as well and fall back to existing code in system partition
19446            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19447        } else {
19448            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19449            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19450                    outInfo, writeSettings, replacingPackage);
19451        }
19452
19453        // Take a note whether we deleted the package for all users
19454        if (outInfo != null) {
19455            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19456            if (outInfo.removedChildPackages != null) {
19457                synchronized (mPackages) {
19458                    final int childCount = outInfo.removedChildPackages.size();
19459                    for (int i = 0; i < childCount; i++) {
19460                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19461                        if (childInfo != null) {
19462                            childInfo.removedForAllUsers = mPackages.get(
19463                                    childInfo.removedPackage) == null;
19464                        }
19465                    }
19466                }
19467            }
19468            // If we uninstalled an update to a system app there may be some
19469            // child packages that appeared as they are declared in the system
19470            // app but were not declared in the update.
19471            if (isSystemApp(ps)) {
19472                synchronized (mPackages) {
19473                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19474                    final int childCount = (updatedPs.childPackageNames != null)
19475                            ? updatedPs.childPackageNames.size() : 0;
19476                    for (int i = 0; i < childCount; i++) {
19477                        String childPackageName = updatedPs.childPackageNames.get(i);
19478                        if (outInfo.removedChildPackages == null
19479                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19480                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19481                            if (childPs == null) {
19482                                continue;
19483                            }
19484                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19485                            installRes.name = childPackageName;
19486                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19487                            installRes.pkg = mPackages.get(childPackageName);
19488                            installRes.uid = childPs.pkg.applicationInfo.uid;
19489                            if (outInfo.appearedChildPackages == null) {
19490                                outInfo.appearedChildPackages = new ArrayMap<>();
19491                            }
19492                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19493                        }
19494                    }
19495                }
19496            }
19497        }
19498
19499        return ret;
19500    }
19501
19502    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19503        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19504                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19505        for (int nextUserId : userIds) {
19506            if (DEBUG_REMOVE) {
19507                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19508            }
19509            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19510                    false /*installed*/,
19511                    true /*stopped*/,
19512                    true /*notLaunched*/,
19513                    false /*hidden*/,
19514                    false /*suspended*/,
19515                    false /*instantApp*/,
19516                    false /*virtualPreload*/,
19517                    null /*lastDisableAppCaller*/,
19518                    null /*enabledComponents*/,
19519                    null /*disabledComponents*/,
19520                    ps.readUserState(nextUserId).domainVerificationStatus,
19521                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19522        }
19523        mSettings.writeKernelMappingLPr(ps);
19524    }
19525
19526    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19527            PackageRemovedInfo outInfo) {
19528        final PackageParser.Package pkg;
19529        synchronized (mPackages) {
19530            pkg = mPackages.get(ps.name);
19531        }
19532
19533        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19534                : new int[] {userId};
19535        for (int nextUserId : userIds) {
19536            if (DEBUG_REMOVE) {
19537                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19538                        + nextUserId);
19539            }
19540
19541            destroyAppDataLIF(pkg, userId,
19542                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19543            destroyAppProfilesLIF(pkg, userId);
19544            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19545            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19546            schedulePackageCleaning(ps.name, nextUserId, false);
19547            synchronized (mPackages) {
19548                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19549                    scheduleWritePackageRestrictionsLocked(nextUserId);
19550                }
19551                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19552            }
19553        }
19554
19555        if (outInfo != null) {
19556            outInfo.removedPackage = ps.name;
19557            outInfo.installerPackageName = ps.installerPackageName;
19558            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19559            outInfo.removedAppId = ps.appId;
19560            outInfo.removedUsers = userIds;
19561            outInfo.broadcastUsers = userIds;
19562        }
19563
19564        return true;
19565    }
19566
19567    private final class ClearStorageConnection implements ServiceConnection {
19568        IMediaContainerService mContainerService;
19569
19570        @Override
19571        public void onServiceConnected(ComponentName name, IBinder service) {
19572            synchronized (this) {
19573                mContainerService = IMediaContainerService.Stub
19574                        .asInterface(Binder.allowBlocking(service));
19575                notifyAll();
19576            }
19577        }
19578
19579        @Override
19580        public void onServiceDisconnected(ComponentName name) {
19581        }
19582    }
19583
19584    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19585        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19586
19587        final boolean mounted;
19588        if (Environment.isExternalStorageEmulated()) {
19589            mounted = true;
19590        } else {
19591            final String status = Environment.getExternalStorageState();
19592
19593            mounted = status.equals(Environment.MEDIA_MOUNTED)
19594                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19595        }
19596
19597        if (!mounted) {
19598            return;
19599        }
19600
19601        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19602        int[] users;
19603        if (userId == UserHandle.USER_ALL) {
19604            users = sUserManager.getUserIds();
19605        } else {
19606            users = new int[] { userId };
19607        }
19608        final ClearStorageConnection conn = new ClearStorageConnection();
19609        if (mContext.bindServiceAsUser(
19610                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19611            try {
19612                for (int curUser : users) {
19613                    long timeout = SystemClock.uptimeMillis() + 5000;
19614                    synchronized (conn) {
19615                        long now;
19616                        while (conn.mContainerService == null &&
19617                                (now = SystemClock.uptimeMillis()) < timeout) {
19618                            try {
19619                                conn.wait(timeout - now);
19620                            } catch (InterruptedException e) {
19621                            }
19622                        }
19623                    }
19624                    if (conn.mContainerService == null) {
19625                        return;
19626                    }
19627
19628                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19629                    clearDirectory(conn.mContainerService,
19630                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19631                    if (allData) {
19632                        clearDirectory(conn.mContainerService,
19633                                userEnv.buildExternalStorageAppDataDirs(packageName));
19634                        clearDirectory(conn.mContainerService,
19635                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19636                    }
19637                }
19638            } finally {
19639                mContext.unbindService(conn);
19640            }
19641        }
19642    }
19643
19644    @Override
19645    public void clearApplicationProfileData(String packageName) {
19646        enforceSystemOrRoot("Only the system can clear all profile data");
19647
19648        final PackageParser.Package pkg;
19649        synchronized (mPackages) {
19650            pkg = mPackages.get(packageName);
19651        }
19652
19653        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19654            synchronized (mInstallLock) {
19655                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19656            }
19657        }
19658    }
19659
19660    @Override
19661    public void clearApplicationUserData(final String packageName,
19662            final IPackageDataObserver observer, final int userId) {
19663        mContext.enforceCallingOrSelfPermission(
19664                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19665
19666        final int callingUid = Binder.getCallingUid();
19667        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19668                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19669
19670        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19671        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19672        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19673            throw new SecurityException("Cannot clear data for a protected package: "
19674                    + packageName);
19675        }
19676        // Queue up an async operation since the package deletion may take a little while.
19677        mHandler.post(new Runnable() {
19678            public void run() {
19679                mHandler.removeCallbacks(this);
19680                final boolean succeeded;
19681                if (!filterApp) {
19682                    try (PackageFreezer freezer = freezePackage(packageName,
19683                            "clearApplicationUserData")) {
19684                        synchronized (mInstallLock) {
19685                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19686                        }
19687                        clearExternalStorageDataSync(packageName, userId, true);
19688                        synchronized (mPackages) {
19689                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19690                                    packageName, userId);
19691                        }
19692                    }
19693                    if (succeeded) {
19694                        // invoke DeviceStorageMonitor's update method to clear any notifications
19695                        DeviceStorageMonitorInternal dsm = LocalServices
19696                                .getService(DeviceStorageMonitorInternal.class);
19697                        if (dsm != null) {
19698                            dsm.checkMemory();
19699                        }
19700                    }
19701                } else {
19702                    succeeded = false;
19703                }
19704                if (observer != null) {
19705                    try {
19706                        observer.onRemoveCompleted(packageName, succeeded);
19707                    } catch (RemoteException e) {
19708                        Log.i(TAG, "Observer no longer exists.");
19709                    }
19710                } //end if observer
19711            } //end run
19712        });
19713    }
19714
19715    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19716        if (packageName == null) {
19717            Slog.w(TAG, "Attempt to delete null packageName.");
19718            return false;
19719        }
19720
19721        // Try finding details about the requested package
19722        PackageParser.Package pkg;
19723        synchronized (mPackages) {
19724            pkg = mPackages.get(packageName);
19725            if (pkg == null) {
19726                final PackageSetting ps = mSettings.mPackages.get(packageName);
19727                if (ps != null) {
19728                    pkg = ps.pkg;
19729                }
19730            }
19731
19732            if (pkg == null) {
19733                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19734                return false;
19735            }
19736
19737            PackageSetting ps = (PackageSetting) pkg.mExtras;
19738            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19739        }
19740
19741        clearAppDataLIF(pkg, userId,
19742                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19743
19744        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19745        removeKeystoreDataIfNeeded(userId, appId);
19746
19747        UserManagerInternal umInternal = getUserManagerInternal();
19748        final int flags;
19749        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19750            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19751        } else if (umInternal.isUserRunning(userId)) {
19752            flags = StorageManager.FLAG_STORAGE_DE;
19753        } else {
19754            flags = 0;
19755        }
19756        prepareAppDataContentsLIF(pkg, userId, flags);
19757
19758        return true;
19759    }
19760
19761    /**
19762     * Reverts user permission state changes (permissions and flags) in
19763     * all packages for a given user.
19764     *
19765     * @param userId The device user for which to do a reset.
19766     */
19767    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19768        final int packageCount = mPackages.size();
19769        for (int i = 0; i < packageCount; i++) {
19770            PackageParser.Package pkg = mPackages.valueAt(i);
19771            PackageSetting ps = (PackageSetting) pkg.mExtras;
19772            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19773        }
19774    }
19775
19776    private void resetNetworkPolicies(int userId) {
19777        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19778    }
19779
19780    /**
19781     * Reverts user permission state changes (permissions and flags).
19782     *
19783     * @param ps The package for which to reset.
19784     * @param userId The device user for which to do a reset.
19785     */
19786    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19787            final PackageSetting ps, final int userId) {
19788        if (ps.pkg == null) {
19789            return;
19790        }
19791
19792        // These are flags that can change base on user actions.
19793        final int userSettableMask = FLAG_PERMISSION_USER_SET
19794                | FLAG_PERMISSION_USER_FIXED
19795                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19796                | FLAG_PERMISSION_REVIEW_REQUIRED;
19797
19798        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19799                | FLAG_PERMISSION_POLICY_FIXED;
19800
19801        boolean writeInstallPermissions = false;
19802        boolean writeRuntimePermissions = false;
19803
19804        final int permissionCount = ps.pkg.requestedPermissions.size();
19805        for (int i = 0; i < permissionCount; i++) {
19806            final String permName = ps.pkg.requestedPermissions.get(i);
19807            final BasePermission bp =
19808                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19809            if (bp == null) {
19810                continue;
19811            }
19812
19813            // If shared user we just reset the state to which only this app contributed.
19814            if (ps.sharedUser != null) {
19815                boolean used = false;
19816                final int packageCount = ps.sharedUser.packages.size();
19817                for (int j = 0; j < packageCount; j++) {
19818                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19819                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19820                            && pkg.pkg.requestedPermissions.contains(permName)) {
19821                        used = true;
19822                        break;
19823                    }
19824                }
19825                if (used) {
19826                    continue;
19827                }
19828            }
19829
19830            final PermissionsState permissionsState = ps.getPermissionsState();
19831
19832            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19833
19834            // Always clear the user settable flags.
19835            final boolean hasInstallState =
19836                    permissionsState.getInstallPermissionState(permName) != null;
19837            // If permission review is enabled and this is a legacy app, mark the
19838            // permission as requiring a review as this is the initial state.
19839            int flags = 0;
19840            if (mPermissionReviewRequired
19841                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19842                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19843            }
19844            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19845                if (hasInstallState) {
19846                    writeInstallPermissions = true;
19847                } else {
19848                    writeRuntimePermissions = true;
19849                }
19850            }
19851
19852            // Below is only runtime permission handling.
19853            if (!bp.isRuntime()) {
19854                continue;
19855            }
19856
19857            // Never clobber system or policy.
19858            if ((oldFlags & policyOrSystemFlags) != 0) {
19859                continue;
19860            }
19861
19862            // If this permission was granted by default, make sure it is.
19863            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19864                if (permissionsState.grantRuntimePermission(bp, userId)
19865                        != PERMISSION_OPERATION_FAILURE) {
19866                    writeRuntimePermissions = true;
19867                }
19868            // If permission review is enabled the permissions for a legacy apps
19869            // are represented as constantly granted runtime ones, so don't revoke.
19870            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19871                // Otherwise, reset the permission.
19872                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19873                switch (revokeResult) {
19874                    case PERMISSION_OPERATION_SUCCESS:
19875                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19876                        writeRuntimePermissions = true;
19877                        final int appId = ps.appId;
19878                        mHandler.post(new Runnable() {
19879                            @Override
19880                            public void run() {
19881                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19882                            }
19883                        });
19884                    } break;
19885                }
19886            }
19887        }
19888
19889        // Synchronously write as we are taking permissions away.
19890        if (writeRuntimePermissions) {
19891            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19892        }
19893
19894        // Synchronously write as we are taking permissions away.
19895        if (writeInstallPermissions) {
19896            mSettings.writeLPr();
19897        }
19898    }
19899
19900    /**
19901     * Remove entries from the keystore daemon. Will only remove it if the
19902     * {@code appId} is valid.
19903     */
19904    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19905        if (appId < 0) {
19906            return;
19907        }
19908
19909        final KeyStore keyStore = KeyStore.getInstance();
19910        if (keyStore != null) {
19911            if (userId == UserHandle.USER_ALL) {
19912                for (final int individual : sUserManager.getUserIds()) {
19913                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19914                }
19915            } else {
19916                keyStore.clearUid(UserHandle.getUid(userId, appId));
19917            }
19918        } else {
19919            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19920        }
19921    }
19922
19923    @Override
19924    public void deleteApplicationCacheFiles(final String packageName,
19925            final IPackageDataObserver observer) {
19926        final int userId = UserHandle.getCallingUserId();
19927        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19928    }
19929
19930    @Override
19931    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19932            final IPackageDataObserver observer) {
19933        final int callingUid = Binder.getCallingUid();
19934        mContext.enforceCallingOrSelfPermission(
19935                android.Manifest.permission.DELETE_CACHE_FILES, null);
19936        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19937                /* requireFullPermission= */ true, /* checkShell= */ false,
19938                "delete application cache files");
19939        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19940                android.Manifest.permission.ACCESS_INSTANT_APPS);
19941
19942        final PackageParser.Package pkg;
19943        synchronized (mPackages) {
19944            pkg = mPackages.get(packageName);
19945        }
19946
19947        // Queue up an async operation since the package deletion may take a little while.
19948        mHandler.post(new Runnable() {
19949            public void run() {
19950                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19951                boolean doClearData = true;
19952                if (ps != null) {
19953                    final boolean targetIsInstantApp =
19954                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19955                    doClearData = !targetIsInstantApp
19956                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19957                }
19958                if (doClearData) {
19959                    synchronized (mInstallLock) {
19960                        final int flags = StorageManager.FLAG_STORAGE_DE
19961                                | StorageManager.FLAG_STORAGE_CE;
19962                        // We're only clearing cache files, so we don't care if the
19963                        // app is unfrozen and still able to run
19964                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19965                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19966                    }
19967                    clearExternalStorageDataSync(packageName, userId, false);
19968                }
19969                if (observer != null) {
19970                    try {
19971                        observer.onRemoveCompleted(packageName, true);
19972                    } catch (RemoteException e) {
19973                        Log.i(TAG, "Observer no longer exists.");
19974                    }
19975                }
19976            }
19977        });
19978    }
19979
19980    @Override
19981    public void getPackageSizeInfo(final String packageName, int userHandle,
19982            final IPackageStatsObserver observer) {
19983        throw new UnsupportedOperationException(
19984                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19985    }
19986
19987    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19988        final PackageSetting ps;
19989        synchronized (mPackages) {
19990            ps = mSettings.mPackages.get(packageName);
19991            if (ps == null) {
19992                Slog.w(TAG, "Failed to find settings for " + packageName);
19993                return false;
19994            }
19995        }
19996
19997        final String[] packageNames = { packageName };
19998        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19999        final String[] codePaths = { ps.codePathString };
20000
20001        try {
20002            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20003                    ps.appId, ceDataInodes, codePaths, stats);
20004
20005            // For now, ignore code size of packages on system partition
20006            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20007                stats.codeSize = 0;
20008            }
20009
20010            // External clients expect these to be tracked separately
20011            stats.dataSize -= stats.cacheSize;
20012
20013        } catch (InstallerException e) {
20014            Slog.w(TAG, String.valueOf(e));
20015            return false;
20016        }
20017
20018        return true;
20019    }
20020
20021    private int getUidTargetSdkVersionLockedLPr(int uid) {
20022        Object obj = mSettings.getUserIdLPr(uid);
20023        if (obj instanceof SharedUserSetting) {
20024            final SharedUserSetting sus = (SharedUserSetting) obj;
20025            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20026            final Iterator<PackageSetting> it = sus.packages.iterator();
20027            while (it.hasNext()) {
20028                final PackageSetting ps = it.next();
20029                if (ps.pkg != null) {
20030                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20031                    if (v < vers) vers = v;
20032                }
20033            }
20034            return vers;
20035        } else if (obj instanceof PackageSetting) {
20036            final PackageSetting ps = (PackageSetting) obj;
20037            if (ps.pkg != null) {
20038                return ps.pkg.applicationInfo.targetSdkVersion;
20039            }
20040        }
20041        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20042    }
20043
20044    @Override
20045    public void addPreferredActivity(IntentFilter filter, int match,
20046            ComponentName[] set, ComponentName activity, int userId) {
20047        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20048                "Adding preferred");
20049    }
20050
20051    private void addPreferredActivityInternal(IntentFilter filter, int match,
20052            ComponentName[] set, ComponentName activity, boolean always, int userId,
20053            String opname) {
20054        // writer
20055        int callingUid = Binder.getCallingUid();
20056        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20057                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20058        if (filter.countActions() == 0) {
20059            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20060            return;
20061        }
20062        synchronized (mPackages) {
20063            if (mContext.checkCallingOrSelfPermission(
20064                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20065                    != PackageManager.PERMISSION_GRANTED) {
20066                if (getUidTargetSdkVersionLockedLPr(callingUid)
20067                        < Build.VERSION_CODES.FROYO) {
20068                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20069                            + callingUid);
20070                    return;
20071                }
20072                mContext.enforceCallingOrSelfPermission(
20073                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20074            }
20075
20076            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20077            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20078                    + userId + ":");
20079            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20080            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20081            scheduleWritePackageRestrictionsLocked(userId);
20082            postPreferredActivityChangedBroadcast(userId);
20083        }
20084    }
20085
20086    private void postPreferredActivityChangedBroadcast(int userId) {
20087        mHandler.post(() -> {
20088            final IActivityManager am = ActivityManager.getService();
20089            if (am == null) {
20090                return;
20091            }
20092
20093            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20094            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20095            try {
20096                am.broadcastIntent(null, intent, null, null,
20097                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20098                        null, false, false, userId);
20099            } catch (RemoteException e) {
20100            }
20101        });
20102    }
20103
20104    @Override
20105    public void replacePreferredActivity(IntentFilter filter, int match,
20106            ComponentName[] set, ComponentName activity, int userId) {
20107        if (filter.countActions() != 1) {
20108            throw new IllegalArgumentException(
20109                    "replacePreferredActivity expects filter to have only 1 action.");
20110        }
20111        if (filter.countDataAuthorities() != 0
20112                || filter.countDataPaths() != 0
20113                || filter.countDataSchemes() > 1
20114                || filter.countDataTypes() != 0) {
20115            throw new IllegalArgumentException(
20116                    "replacePreferredActivity expects filter to have no data authorities, " +
20117                    "paths, or types; and at most one scheme.");
20118        }
20119
20120        final int callingUid = Binder.getCallingUid();
20121        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20122                true /* requireFullPermission */, false /* checkShell */,
20123                "replace preferred activity");
20124        synchronized (mPackages) {
20125            if (mContext.checkCallingOrSelfPermission(
20126                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20127                    != PackageManager.PERMISSION_GRANTED) {
20128                if (getUidTargetSdkVersionLockedLPr(callingUid)
20129                        < Build.VERSION_CODES.FROYO) {
20130                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20131                            + Binder.getCallingUid());
20132                    return;
20133                }
20134                mContext.enforceCallingOrSelfPermission(
20135                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20136            }
20137
20138            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20139            if (pir != null) {
20140                // Get all of the existing entries that exactly match this filter.
20141                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20142                if (existing != null && existing.size() == 1) {
20143                    PreferredActivity cur = existing.get(0);
20144                    if (DEBUG_PREFERRED) {
20145                        Slog.i(TAG, "Checking replace of preferred:");
20146                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20147                        if (!cur.mPref.mAlways) {
20148                            Slog.i(TAG, "  -- CUR; not mAlways!");
20149                        } else {
20150                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20151                            Slog.i(TAG, "  -- CUR: mSet="
20152                                    + Arrays.toString(cur.mPref.mSetComponents));
20153                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20154                            Slog.i(TAG, "  -- NEW: mMatch="
20155                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20156                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20157                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20158                        }
20159                    }
20160                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20161                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20162                            && cur.mPref.sameSet(set)) {
20163                        // Setting the preferred activity to what it happens to be already
20164                        if (DEBUG_PREFERRED) {
20165                            Slog.i(TAG, "Replacing with same preferred activity "
20166                                    + cur.mPref.mShortComponent + " for user "
20167                                    + userId + ":");
20168                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20169                        }
20170                        return;
20171                    }
20172                }
20173
20174                if (existing != null) {
20175                    if (DEBUG_PREFERRED) {
20176                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20177                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20178                    }
20179                    for (int i = 0; i < existing.size(); i++) {
20180                        PreferredActivity pa = existing.get(i);
20181                        if (DEBUG_PREFERRED) {
20182                            Slog.i(TAG, "Removing existing preferred activity "
20183                                    + pa.mPref.mComponent + ":");
20184                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20185                        }
20186                        pir.removeFilter(pa);
20187                    }
20188                }
20189            }
20190            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20191                    "Replacing preferred");
20192        }
20193    }
20194
20195    @Override
20196    public void clearPackagePreferredActivities(String packageName) {
20197        final int callingUid = Binder.getCallingUid();
20198        if (getInstantAppPackageName(callingUid) != null) {
20199            return;
20200        }
20201        // writer
20202        synchronized (mPackages) {
20203            PackageParser.Package pkg = mPackages.get(packageName);
20204            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20205                if (mContext.checkCallingOrSelfPermission(
20206                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20207                        != PackageManager.PERMISSION_GRANTED) {
20208                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20209                            < Build.VERSION_CODES.FROYO) {
20210                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20211                                + callingUid);
20212                        return;
20213                    }
20214                    mContext.enforceCallingOrSelfPermission(
20215                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20216                }
20217            }
20218            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20219            if (ps != null
20220                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20221                return;
20222            }
20223            int user = UserHandle.getCallingUserId();
20224            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20225                scheduleWritePackageRestrictionsLocked(user);
20226            }
20227        }
20228    }
20229
20230    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20231    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20232        ArrayList<PreferredActivity> removed = null;
20233        boolean changed = false;
20234        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20235            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20236            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20237            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20238                continue;
20239            }
20240            Iterator<PreferredActivity> it = pir.filterIterator();
20241            while (it.hasNext()) {
20242                PreferredActivity pa = it.next();
20243                // Mark entry for removal only if it matches the package name
20244                // and the entry is of type "always".
20245                if (packageName == null ||
20246                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20247                                && pa.mPref.mAlways)) {
20248                    if (removed == null) {
20249                        removed = new ArrayList<PreferredActivity>();
20250                    }
20251                    removed.add(pa);
20252                }
20253            }
20254            if (removed != null) {
20255                for (int j=0; j<removed.size(); j++) {
20256                    PreferredActivity pa = removed.get(j);
20257                    pir.removeFilter(pa);
20258                }
20259                changed = true;
20260            }
20261        }
20262        if (changed) {
20263            postPreferredActivityChangedBroadcast(userId);
20264        }
20265        return changed;
20266    }
20267
20268    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20269    private void clearIntentFilterVerificationsLPw(int userId) {
20270        final int packageCount = mPackages.size();
20271        for (int i = 0; i < packageCount; i++) {
20272            PackageParser.Package pkg = mPackages.valueAt(i);
20273            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20274        }
20275    }
20276
20277    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20278    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20279        if (userId == UserHandle.USER_ALL) {
20280            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20281                    sUserManager.getUserIds())) {
20282                for (int oneUserId : sUserManager.getUserIds()) {
20283                    scheduleWritePackageRestrictionsLocked(oneUserId);
20284                }
20285            }
20286        } else {
20287            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20288                scheduleWritePackageRestrictionsLocked(userId);
20289            }
20290        }
20291    }
20292
20293    /** Clears state for all users, and touches intent filter verification policy */
20294    void clearDefaultBrowserIfNeeded(String packageName) {
20295        for (int oneUserId : sUserManager.getUserIds()) {
20296            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20297        }
20298    }
20299
20300    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20301        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20302        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20303            if (packageName.equals(defaultBrowserPackageName)) {
20304                setDefaultBrowserPackageName(null, userId);
20305            }
20306        }
20307    }
20308
20309    @Override
20310    public void resetApplicationPreferences(int userId) {
20311        mContext.enforceCallingOrSelfPermission(
20312                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20313        final long identity = Binder.clearCallingIdentity();
20314        // writer
20315        try {
20316            synchronized (mPackages) {
20317                clearPackagePreferredActivitiesLPw(null, userId);
20318                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20319                // TODO: We have to reset the default SMS and Phone. This requires
20320                // significant refactoring to keep all default apps in the package
20321                // manager (cleaner but more work) or have the services provide
20322                // callbacks to the package manager to request a default app reset.
20323                applyFactoryDefaultBrowserLPw(userId);
20324                clearIntentFilterVerificationsLPw(userId);
20325                primeDomainVerificationsLPw(userId);
20326                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20327                scheduleWritePackageRestrictionsLocked(userId);
20328            }
20329            resetNetworkPolicies(userId);
20330        } finally {
20331            Binder.restoreCallingIdentity(identity);
20332        }
20333    }
20334
20335    @Override
20336    public int getPreferredActivities(List<IntentFilter> outFilters,
20337            List<ComponentName> outActivities, String packageName) {
20338        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20339            return 0;
20340        }
20341        int num = 0;
20342        final int userId = UserHandle.getCallingUserId();
20343        // reader
20344        synchronized (mPackages) {
20345            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20346            if (pir != null) {
20347                final Iterator<PreferredActivity> it = pir.filterIterator();
20348                while (it.hasNext()) {
20349                    final PreferredActivity pa = it.next();
20350                    if (packageName == null
20351                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20352                                    && pa.mPref.mAlways)) {
20353                        if (outFilters != null) {
20354                            outFilters.add(new IntentFilter(pa));
20355                        }
20356                        if (outActivities != null) {
20357                            outActivities.add(pa.mPref.mComponent);
20358                        }
20359                    }
20360                }
20361            }
20362        }
20363
20364        return num;
20365    }
20366
20367    @Override
20368    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20369            int userId) {
20370        int callingUid = Binder.getCallingUid();
20371        if (callingUid != Process.SYSTEM_UID) {
20372            throw new SecurityException(
20373                    "addPersistentPreferredActivity can only be run by the system");
20374        }
20375        if (filter.countActions() == 0) {
20376            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20377            return;
20378        }
20379        synchronized (mPackages) {
20380            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20381                    ":");
20382            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20383            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20384                    new PersistentPreferredActivity(filter, activity));
20385            scheduleWritePackageRestrictionsLocked(userId);
20386            postPreferredActivityChangedBroadcast(userId);
20387        }
20388    }
20389
20390    @Override
20391    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20392        int callingUid = Binder.getCallingUid();
20393        if (callingUid != Process.SYSTEM_UID) {
20394            throw new SecurityException(
20395                    "clearPackagePersistentPreferredActivities can only be run by the system");
20396        }
20397        ArrayList<PersistentPreferredActivity> removed = null;
20398        boolean changed = false;
20399        synchronized (mPackages) {
20400            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20401                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20402                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20403                        .valueAt(i);
20404                if (userId != thisUserId) {
20405                    continue;
20406                }
20407                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20408                while (it.hasNext()) {
20409                    PersistentPreferredActivity ppa = it.next();
20410                    // Mark entry for removal only if it matches the package name.
20411                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20412                        if (removed == null) {
20413                            removed = new ArrayList<PersistentPreferredActivity>();
20414                        }
20415                        removed.add(ppa);
20416                    }
20417                }
20418                if (removed != null) {
20419                    for (int j=0; j<removed.size(); j++) {
20420                        PersistentPreferredActivity ppa = removed.get(j);
20421                        ppir.removeFilter(ppa);
20422                    }
20423                    changed = true;
20424                }
20425            }
20426
20427            if (changed) {
20428                scheduleWritePackageRestrictionsLocked(userId);
20429                postPreferredActivityChangedBroadcast(userId);
20430            }
20431        }
20432    }
20433
20434    /**
20435     * Common machinery for picking apart a restored XML blob and passing
20436     * it to a caller-supplied functor to be applied to the running system.
20437     */
20438    private void restoreFromXml(XmlPullParser parser, int userId,
20439            String expectedStartTag, BlobXmlRestorer functor)
20440            throws IOException, XmlPullParserException {
20441        int type;
20442        while ((type = parser.next()) != XmlPullParser.START_TAG
20443                && type != XmlPullParser.END_DOCUMENT) {
20444        }
20445        if (type != XmlPullParser.START_TAG) {
20446            // oops didn't find a start tag?!
20447            if (DEBUG_BACKUP) {
20448                Slog.e(TAG, "Didn't find start tag during restore");
20449            }
20450            return;
20451        }
20452Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20453        // this is supposed to be TAG_PREFERRED_BACKUP
20454        if (!expectedStartTag.equals(parser.getName())) {
20455            if (DEBUG_BACKUP) {
20456                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20457            }
20458            return;
20459        }
20460
20461        // skip interfering stuff, then we're aligned with the backing implementation
20462        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20463Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20464        functor.apply(parser, userId);
20465    }
20466
20467    private interface BlobXmlRestorer {
20468        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20469    }
20470
20471    /**
20472     * Non-Binder method, support for the backup/restore mechanism: write the
20473     * full set of preferred activities in its canonical XML format.  Returns the
20474     * XML output as a byte array, or null if there is none.
20475     */
20476    @Override
20477    public byte[] getPreferredActivityBackup(int userId) {
20478        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20479            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20480        }
20481
20482        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20483        try {
20484            final XmlSerializer serializer = new FastXmlSerializer();
20485            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20486            serializer.startDocument(null, true);
20487            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20488
20489            synchronized (mPackages) {
20490                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20491            }
20492
20493            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20494            serializer.endDocument();
20495            serializer.flush();
20496        } catch (Exception e) {
20497            if (DEBUG_BACKUP) {
20498                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20499            }
20500            return null;
20501        }
20502
20503        return dataStream.toByteArray();
20504    }
20505
20506    @Override
20507    public void restorePreferredActivities(byte[] backup, int userId) {
20508        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20509            throw new SecurityException("Only the system may call restorePreferredActivities()");
20510        }
20511
20512        try {
20513            final XmlPullParser parser = Xml.newPullParser();
20514            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20515            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20516                    new BlobXmlRestorer() {
20517                        @Override
20518                        public void apply(XmlPullParser parser, int userId)
20519                                throws XmlPullParserException, IOException {
20520                            synchronized (mPackages) {
20521                                mSettings.readPreferredActivitiesLPw(parser, userId);
20522                            }
20523                        }
20524                    } );
20525        } catch (Exception e) {
20526            if (DEBUG_BACKUP) {
20527                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20528            }
20529        }
20530    }
20531
20532    /**
20533     * Non-Binder method, support for the backup/restore mechanism: write the
20534     * default browser (etc) settings in its canonical XML format.  Returns the default
20535     * browser XML representation as a byte array, or null if there is none.
20536     */
20537    @Override
20538    public byte[] getDefaultAppsBackup(int userId) {
20539        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20540            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20541        }
20542
20543        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20544        try {
20545            final XmlSerializer serializer = new FastXmlSerializer();
20546            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20547            serializer.startDocument(null, true);
20548            serializer.startTag(null, TAG_DEFAULT_APPS);
20549
20550            synchronized (mPackages) {
20551                mSettings.writeDefaultAppsLPr(serializer, userId);
20552            }
20553
20554            serializer.endTag(null, TAG_DEFAULT_APPS);
20555            serializer.endDocument();
20556            serializer.flush();
20557        } catch (Exception e) {
20558            if (DEBUG_BACKUP) {
20559                Slog.e(TAG, "Unable to write default apps for backup", e);
20560            }
20561            return null;
20562        }
20563
20564        return dataStream.toByteArray();
20565    }
20566
20567    @Override
20568    public void restoreDefaultApps(byte[] backup, int userId) {
20569        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20570            throw new SecurityException("Only the system may call restoreDefaultApps()");
20571        }
20572
20573        try {
20574            final XmlPullParser parser = Xml.newPullParser();
20575            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20576            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20577                    new BlobXmlRestorer() {
20578                        @Override
20579                        public void apply(XmlPullParser parser, int userId)
20580                                throws XmlPullParserException, IOException {
20581                            synchronized (mPackages) {
20582                                mSettings.readDefaultAppsLPw(parser, userId);
20583                            }
20584                        }
20585                    } );
20586        } catch (Exception e) {
20587            if (DEBUG_BACKUP) {
20588                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20589            }
20590        }
20591    }
20592
20593    @Override
20594    public byte[] getIntentFilterVerificationBackup(int userId) {
20595        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20596            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20597        }
20598
20599        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20600        try {
20601            final XmlSerializer serializer = new FastXmlSerializer();
20602            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20603            serializer.startDocument(null, true);
20604            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20605
20606            synchronized (mPackages) {
20607                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20608            }
20609
20610            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20611            serializer.endDocument();
20612            serializer.flush();
20613        } catch (Exception e) {
20614            if (DEBUG_BACKUP) {
20615                Slog.e(TAG, "Unable to write default apps for backup", e);
20616            }
20617            return null;
20618        }
20619
20620        return dataStream.toByteArray();
20621    }
20622
20623    @Override
20624    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20625        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20626            throw new SecurityException("Only the system may call restorePreferredActivities()");
20627        }
20628
20629        try {
20630            final XmlPullParser parser = Xml.newPullParser();
20631            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20632            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20633                    new BlobXmlRestorer() {
20634                        @Override
20635                        public void apply(XmlPullParser parser, int userId)
20636                                throws XmlPullParserException, IOException {
20637                            synchronized (mPackages) {
20638                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20639                                mSettings.writeLPr();
20640                            }
20641                        }
20642                    } );
20643        } catch (Exception e) {
20644            if (DEBUG_BACKUP) {
20645                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20646            }
20647        }
20648    }
20649
20650    @Override
20651    public byte[] getPermissionGrantBackup(int userId) {
20652        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20653            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20654        }
20655
20656        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20657        try {
20658            final XmlSerializer serializer = new FastXmlSerializer();
20659            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20660            serializer.startDocument(null, true);
20661            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20662
20663            synchronized (mPackages) {
20664                serializeRuntimePermissionGrantsLPr(serializer, userId);
20665            }
20666
20667            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20668            serializer.endDocument();
20669            serializer.flush();
20670        } catch (Exception e) {
20671            if (DEBUG_BACKUP) {
20672                Slog.e(TAG, "Unable to write default apps for backup", e);
20673            }
20674            return null;
20675        }
20676
20677        return dataStream.toByteArray();
20678    }
20679
20680    @Override
20681    public void restorePermissionGrants(byte[] backup, int userId) {
20682        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20683            throw new SecurityException("Only the system may call restorePermissionGrants()");
20684        }
20685
20686        try {
20687            final XmlPullParser parser = Xml.newPullParser();
20688            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20689            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20690                    new BlobXmlRestorer() {
20691                        @Override
20692                        public void apply(XmlPullParser parser, int userId)
20693                                throws XmlPullParserException, IOException {
20694                            synchronized (mPackages) {
20695                                processRestoredPermissionGrantsLPr(parser, userId);
20696                            }
20697                        }
20698                    } );
20699        } catch (Exception e) {
20700            if (DEBUG_BACKUP) {
20701                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20702            }
20703        }
20704    }
20705
20706    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20707            throws IOException {
20708        serializer.startTag(null, TAG_ALL_GRANTS);
20709
20710        final int N = mSettings.mPackages.size();
20711        for (int i = 0; i < N; i++) {
20712            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20713            boolean pkgGrantsKnown = false;
20714
20715            PermissionsState packagePerms = ps.getPermissionsState();
20716
20717            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20718                final int grantFlags = state.getFlags();
20719                // only look at grants that are not system/policy fixed
20720                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20721                    final boolean isGranted = state.isGranted();
20722                    // And only back up the user-twiddled state bits
20723                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20724                        final String packageName = mSettings.mPackages.keyAt(i);
20725                        if (!pkgGrantsKnown) {
20726                            serializer.startTag(null, TAG_GRANT);
20727                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20728                            pkgGrantsKnown = true;
20729                        }
20730
20731                        final boolean userSet =
20732                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20733                        final boolean userFixed =
20734                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20735                        final boolean revoke =
20736                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20737
20738                        serializer.startTag(null, TAG_PERMISSION);
20739                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20740                        if (isGranted) {
20741                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20742                        }
20743                        if (userSet) {
20744                            serializer.attribute(null, ATTR_USER_SET, "true");
20745                        }
20746                        if (userFixed) {
20747                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20748                        }
20749                        if (revoke) {
20750                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20751                        }
20752                        serializer.endTag(null, TAG_PERMISSION);
20753                    }
20754                }
20755            }
20756
20757            if (pkgGrantsKnown) {
20758                serializer.endTag(null, TAG_GRANT);
20759            }
20760        }
20761
20762        serializer.endTag(null, TAG_ALL_GRANTS);
20763    }
20764
20765    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20766            throws XmlPullParserException, IOException {
20767        String pkgName = null;
20768        int outerDepth = parser.getDepth();
20769        int type;
20770        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20771                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20772            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20773                continue;
20774            }
20775
20776            final String tagName = parser.getName();
20777            if (tagName.equals(TAG_GRANT)) {
20778                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20779                if (DEBUG_BACKUP) {
20780                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20781                }
20782            } else if (tagName.equals(TAG_PERMISSION)) {
20783
20784                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20785                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20786
20787                int newFlagSet = 0;
20788                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20789                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20790                }
20791                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20792                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20793                }
20794                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20795                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20796                }
20797                if (DEBUG_BACKUP) {
20798                    Slog.v(TAG, "  + Restoring grant:"
20799                            + " pkg=" + pkgName
20800                            + " perm=" + permName
20801                            + " granted=" + isGranted
20802                            + " bits=0x" + Integer.toHexString(newFlagSet));
20803                }
20804                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20805                if (ps != null) {
20806                    // Already installed so we apply the grant immediately
20807                    if (DEBUG_BACKUP) {
20808                        Slog.v(TAG, "        + already installed; applying");
20809                    }
20810                    PermissionsState perms = ps.getPermissionsState();
20811                    BasePermission bp =
20812                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20813                    if (bp != null) {
20814                        if (isGranted) {
20815                            perms.grantRuntimePermission(bp, userId);
20816                        }
20817                        if (newFlagSet != 0) {
20818                            perms.updatePermissionFlags(
20819                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20820                        }
20821                    }
20822                } else {
20823                    // Need to wait for post-restore install to apply the grant
20824                    if (DEBUG_BACKUP) {
20825                        Slog.v(TAG, "        - not yet installed; saving for later");
20826                    }
20827                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20828                            isGranted, newFlagSet, userId);
20829                }
20830            } else {
20831                PackageManagerService.reportSettingsProblem(Log.WARN,
20832                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20833                XmlUtils.skipCurrentTag(parser);
20834            }
20835        }
20836
20837        scheduleWriteSettingsLocked();
20838        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20839    }
20840
20841    @Override
20842    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20843            int sourceUserId, int targetUserId, int flags) {
20844        mContext.enforceCallingOrSelfPermission(
20845                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20846        int callingUid = Binder.getCallingUid();
20847        enforceOwnerRights(ownerPackage, callingUid);
20848        PackageManagerServiceUtils.enforceShellRestriction(
20849                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20850        if (intentFilter.countActions() == 0) {
20851            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20852            return;
20853        }
20854        synchronized (mPackages) {
20855            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20856                    ownerPackage, targetUserId, flags);
20857            CrossProfileIntentResolver resolver =
20858                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20859            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20860            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20861            if (existing != null) {
20862                int size = existing.size();
20863                for (int i = 0; i < size; i++) {
20864                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20865                        return;
20866                    }
20867                }
20868            }
20869            resolver.addFilter(newFilter);
20870            scheduleWritePackageRestrictionsLocked(sourceUserId);
20871        }
20872    }
20873
20874    @Override
20875    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20876        mContext.enforceCallingOrSelfPermission(
20877                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20878        final int callingUid = Binder.getCallingUid();
20879        enforceOwnerRights(ownerPackage, callingUid);
20880        PackageManagerServiceUtils.enforceShellRestriction(
20881                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20882        synchronized (mPackages) {
20883            CrossProfileIntentResolver resolver =
20884                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20885            ArraySet<CrossProfileIntentFilter> set =
20886                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20887            for (CrossProfileIntentFilter filter : set) {
20888                if (filter.getOwnerPackage().equals(ownerPackage)) {
20889                    resolver.removeFilter(filter);
20890                }
20891            }
20892            scheduleWritePackageRestrictionsLocked(sourceUserId);
20893        }
20894    }
20895
20896    // Enforcing that callingUid is owning pkg on userId
20897    private void enforceOwnerRights(String pkg, int callingUid) {
20898        // The system owns everything.
20899        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20900            return;
20901        }
20902        final int callingUserId = UserHandle.getUserId(callingUid);
20903        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20904        if (pi == null) {
20905            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20906                    + callingUserId);
20907        }
20908        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20909            throw new SecurityException("Calling uid " + callingUid
20910                    + " does not own package " + pkg);
20911        }
20912    }
20913
20914    @Override
20915    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20916        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20917            return null;
20918        }
20919        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20920    }
20921
20922    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20923        UserManagerService ums = UserManagerService.getInstance();
20924        if (ums != null) {
20925            final UserInfo parent = ums.getProfileParent(userId);
20926            final int launcherUid = (parent != null) ? parent.id : userId;
20927            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20928            if (launcherComponent != null) {
20929                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20930                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20931                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20932                        .setPackage(launcherComponent.getPackageName());
20933                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20934            }
20935        }
20936    }
20937
20938    /**
20939     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20940     * then reports the most likely home activity or null if there are more than one.
20941     */
20942    private ComponentName getDefaultHomeActivity(int userId) {
20943        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20944        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20945        if (cn != null) {
20946            return cn;
20947        }
20948
20949        // Find the launcher with the highest priority and return that component if there are no
20950        // other home activity with the same priority.
20951        int lastPriority = Integer.MIN_VALUE;
20952        ComponentName lastComponent = null;
20953        final int size = allHomeCandidates.size();
20954        for (int i = 0; i < size; i++) {
20955            final ResolveInfo ri = allHomeCandidates.get(i);
20956            if (ri.priority > lastPriority) {
20957                lastComponent = ri.activityInfo.getComponentName();
20958                lastPriority = ri.priority;
20959            } else if (ri.priority == lastPriority) {
20960                // Two components found with same priority.
20961                lastComponent = null;
20962            }
20963        }
20964        return lastComponent;
20965    }
20966
20967    private Intent getHomeIntent() {
20968        Intent intent = new Intent(Intent.ACTION_MAIN);
20969        intent.addCategory(Intent.CATEGORY_HOME);
20970        intent.addCategory(Intent.CATEGORY_DEFAULT);
20971        return intent;
20972    }
20973
20974    private IntentFilter getHomeFilter() {
20975        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20976        filter.addCategory(Intent.CATEGORY_HOME);
20977        filter.addCategory(Intent.CATEGORY_DEFAULT);
20978        return filter;
20979    }
20980
20981    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20982            int userId) {
20983        Intent intent  = getHomeIntent();
20984        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20985                PackageManager.GET_META_DATA, userId);
20986        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20987                true, false, false, userId);
20988
20989        allHomeCandidates.clear();
20990        if (list != null) {
20991            for (ResolveInfo ri : list) {
20992                allHomeCandidates.add(ri);
20993            }
20994        }
20995        return (preferred == null || preferred.activityInfo == null)
20996                ? null
20997                : new ComponentName(preferred.activityInfo.packageName,
20998                        preferred.activityInfo.name);
20999    }
21000
21001    @Override
21002    public void setHomeActivity(ComponentName comp, int userId) {
21003        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21004            return;
21005        }
21006        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21007        getHomeActivitiesAsUser(homeActivities, userId);
21008
21009        boolean found = false;
21010
21011        final int size = homeActivities.size();
21012        final ComponentName[] set = new ComponentName[size];
21013        for (int i = 0; i < size; i++) {
21014            final ResolveInfo candidate = homeActivities.get(i);
21015            final ActivityInfo info = candidate.activityInfo;
21016            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21017            set[i] = activityName;
21018            if (!found && activityName.equals(comp)) {
21019                found = true;
21020            }
21021        }
21022        if (!found) {
21023            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21024                    + userId);
21025        }
21026        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21027                set, comp, userId);
21028    }
21029
21030    private @Nullable String getSetupWizardPackageName() {
21031        final Intent intent = new Intent(Intent.ACTION_MAIN);
21032        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21033
21034        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21035                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21036                        | MATCH_DISABLED_COMPONENTS,
21037                UserHandle.myUserId());
21038        if (matches.size() == 1) {
21039            return matches.get(0).getComponentInfo().packageName;
21040        } else {
21041            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21042                    + ": matches=" + matches);
21043            return null;
21044        }
21045    }
21046
21047    private @Nullable String getStorageManagerPackageName() {
21048        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21049
21050        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21051                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21052                        | MATCH_DISABLED_COMPONENTS,
21053                UserHandle.myUserId());
21054        if (matches.size() == 1) {
21055            return matches.get(0).getComponentInfo().packageName;
21056        } else {
21057            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21058                    + matches.size() + ": matches=" + matches);
21059            return null;
21060        }
21061    }
21062
21063    @Override
21064    public void setApplicationEnabledSetting(String appPackageName,
21065            int newState, int flags, int userId, String callingPackage) {
21066        if (!sUserManager.exists(userId)) return;
21067        if (callingPackage == null) {
21068            callingPackage = Integer.toString(Binder.getCallingUid());
21069        }
21070        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21071    }
21072
21073    @Override
21074    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21075        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21076        synchronized (mPackages) {
21077            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21078            if (pkgSetting != null) {
21079                pkgSetting.setUpdateAvailable(updateAvailable);
21080            }
21081        }
21082    }
21083
21084    @Override
21085    public void setComponentEnabledSetting(ComponentName componentName,
21086            int newState, int flags, int userId) {
21087        if (!sUserManager.exists(userId)) return;
21088        setEnabledSetting(componentName.getPackageName(),
21089                componentName.getClassName(), newState, flags, userId, null);
21090    }
21091
21092    private void setEnabledSetting(final String packageName, String className, int newState,
21093            final int flags, int userId, String callingPackage) {
21094        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21095              || newState == COMPONENT_ENABLED_STATE_ENABLED
21096              || newState == COMPONENT_ENABLED_STATE_DISABLED
21097              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21098              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21099            throw new IllegalArgumentException("Invalid new component state: "
21100                    + newState);
21101        }
21102        PackageSetting pkgSetting;
21103        final int callingUid = Binder.getCallingUid();
21104        final int permission;
21105        if (callingUid == Process.SYSTEM_UID) {
21106            permission = PackageManager.PERMISSION_GRANTED;
21107        } else {
21108            permission = mContext.checkCallingOrSelfPermission(
21109                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21110        }
21111        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21112                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21113        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21114        boolean sendNow = false;
21115        boolean isApp = (className == null);
21116        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21117        String componentName = isApp ? packageName : className;
21118        int packageUid = -1;
21119        ArrayList<String> components;
21120
21121        // reader
21122        synchronized (mPackages) {
21123            pkgSetting = mSettings.mPackages.get(packageName);
21124            if (pkgSetting == null) {
21125                if (!isCallerInstantApp) {
21126                    if (className == null) {
21127                        throw new IllegalArgumentException("Unknown package: " + packageName);
21128                    }
21129                    throw new IllegalArgumentException(
21130                            "Unknown component: " + packageName + "/" + className);
21131                } else {
21132                    // throw SecurityException to prevent leaking package information
21133                    throw new SecurityException(
21134                            "Attempt to change component state; "
21135                            + "pid=" + Binder.getCallingPid()
21136                            + ", uid=" + callingUid
21137                            + (className == null
21138                                    ? ", package=" + packageName
21139                                    : ", component=" + packageName + "/" + className));
21140                }
21141            }
21142        }
21143
21144        // Limit who can change which apps
21145        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21146            // Don't allow apps that don't have permission to modify other apps
21147            if (!allowedByPermission
21148                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21149                throw new SecurityException(
21150                        "Attempt to change component state; "
21151                        + "pid=" + Binder.getCallingPid()
21152                        + ", uid=" + callingUid
21153                        + (className == null
21154                                ? ", package=" + packageName
21155                                : ", component=" + packageName + "/" + className));
21156            }
21157            // Don't allow changing protected packages.
21158            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21159                throw new SecurityException("Cannot disable a protected package: " + packageName);
21160            }
21161        }
21162
21163        synchronized (mPackages) {
21164            if (callingUid == Process.SHELL_UID
21165                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21166                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21167                // unless it is a test package.
21168                int oldState = pkgSetting.getEnabled(userId);
21169                if (className == null
21170                        &&
21171                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21172                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21173                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21174                        &&
21175                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21176                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21177                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21178                    // ok
21179                } else {
21180                    throw new SecurityException(
21181                            "Shell cannot change component state for " + packageName + "/"
21182                                    + className + " to " + newState);
21183                }
21184            }
21185        }
21186        if (className == null) {
21187            // We're dealing with an application/package level state change
21188            synchronized (mPackages) {
21189                if (pkgSetting.getEnabled(userId) == newState) {
21190                    // Nothing to do
21191                    return;
21192                }
21193            }
21194            // If we're enabling a system stub, there's a little more work to do.
21195            // Prior to enabling the package, we need to decompress the APK(s) to the
21196            // data partition and then replace the version on the system partition.
21197            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21198            final boolean isSystemStub = deletedPkg.isStub
21199                    && deletedPkg.isSystemApp();
21200            if (isSystemStub
21201                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21202                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21203                final File codePath = decompressPackage(deletedPkg);
21204                if (codePath == null) {
21205                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21206                    return;
21207                }
21208                // TODO remove direct parsing of the package object during internal cleanup
21209                // of scan package
21210                // We need to call parse directly here for no other reason than we need
21211                // the new package in order to disable the old one [we use the information
21212                // for some internal optimization to optionally create a new package setting
21213                // object on replace]. However, we can't get the package from the scan
21214                // because the scan modifies live structures and we need to remove the
21215                // old [system] package from the system before a scan can be attempted.
21216                // Once scan is indempotent we can remove this parse and use the package
21217                // object we scanned, prior to adding it to package settings.
21218                final PackageParser pp = new PackageParser();
21219                pp.setSeparateProcesses(mSeparateProcesses);
21220                pp.setDisplayMetrics(mMetrics);
21221                pp.setCallback(mPackageParserCallback);
21222                final PackageParser.Package tmpPkg;
21223                try {
21224                    final int parseFlags = mDefParseFlags
21225                            | PackageParser.PARSE_MUST_BE_APK
21226                            | PackageParser.PARSE_IS_SYSTEM
21227                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21228                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21229                } catch (PackageParserException e) {
21230                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21231                    return;
21232                }
21233                synchronized (mInstallLock) {
21234                    // Disable the stub and remove any package entries
21235                    removePackageLI(deletedPkg, true);
21236                    synchronized (mPackages) {
21237                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21238                    }
21239                    final PackageParser.Package newPkg;
21240                    try (PackageFreezer freezer =
21241                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21242                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21243                                | PackageParser.PARSE_ENFORCE_CODE;
21244                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21245                                0 /*currentTime*/, null /*user*/);
21246                        prepareAppDataAfterInstallLIF(newPkg);
21247                        synchronized (mPackages) {
21248                            try {
21249                                updateSharedLibrariesLPr(newPkg, null);
21250                            } catch (PackageManagerException e) {
21251                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21252                            }
21253                            updatePermissionsLPw(newPkg.packageName, newPkg,
21254                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21255                            mSettings.writeLPr();
21256                        }
21257                    } catch (PackageManagerException e) {
21258                        // Whoops! Something went wrong; try to roll back to the stub
21259                        Slog.w(TAG, "Failed to install compressed system package:"
21260                                + pkgSetting.name, e);
21261                        // Remove the failed install
21262                        removeCodePathLI(codePath);
21263
21264                        // Install the system package
21265                        try (PackageFreezer freezer =
21266                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21267                            synchronized (mPackages) {
21268                                // NOTE: The system package always needs to be enabled; even
21269                                // if it's for a compressed stub. If we don't, installing the
21270                                // system package fails during scan [scanning checks the disabled
21271                                // packages]. We will reverse this later, after we've "installed"
21272                                // the stub.
21273                                // This leaves us in a fragile state; the stub should never be
21274                                // enabled, so, cross your fingers and hope nothing goes wrong
21275                                // until we can disable the package later.
21276                                enableSystemPackageLPw(deletedPkg);
21277                            }
21278                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21279                                    false /*isPrivileged*/, null /*allUserHandles*/,
21280                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21281                                    true /*writeSettings*/);
21282                        } catch (PackageManagerException pme) {
21283                            Slog.w(TAG, "Failed to restore system package:"
21284                                    + deletedPkg.packageName, pme);
21285                        } finally {
21286                            synchronized (mPackages) {
21287                                mSettings.disableSystemPackageLPw(
21288                                        deletedPkg.packageName, true /*replaced*/);
21289                                mSettings.writeLPr();
21290                            }
21291                        }
21292                        return;
21293                    }
21294                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21295                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21296                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21297                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21298                            newPkg.baseCodePath, newPkg.splitCodePaths);
21299                }
21300            }
21301            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21302                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21303                // Don't care about who enables an app.
21304                callingPackage = null;
21305            }
21306            synchronized (mPackages) {
21307                pkgSetting.setEnabled(newState, userId, callingPackage);
21308            }
21309        } else {
21310            synchronized (mPackages) {
21311                // We're dealing with a component level state change
21312                // First, verify that this is a valid class name.
21313                PackageParser.Package pkg = pkgSetting.pkg;
21314                if (pkg == null || !pkg.hasComponentClassName(className)) {
21315                    if (pkg != null &&
21316                            pkg.applicationInfo.targetSdkVersion >=
21317                                    Build.VERSION_CODES.JELLY_BEAN) {
21318                        throw new IllegalArgumentException("Component class " + className
21319                                + " does not exist in " + packageName);
21320                    } else {
21321                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21322                                + className + " does not exist in " + packageName);
21323                    }
21324                }
21325                switch (newState) {
21326                    case COMPONENT_ENABLED_STATE_ENABLED:
21327                        if (!pkgSetting.enableComponentLPw(className, userId)) {
21328                            return;
21329                        }
21330                        break;
21331                    case COMPONENT_ENABLED_STATE_DISABLED:
21332                        if (!pkgSetting.disableComponentLPw(className, userId)) {
21333                            return;
21334                        }
21335                        break;
21336                    case COMPONENT_ENABLED_STATE_DEFAULT:
21337                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
21338                            return;
21339                        }
21340                        break;
21341                    default:
21342                        Slog.e(TAG, "Invalid new component state: " + newState);
21343                        return;
21344                }
21345            }
21346        }
21347        synchronized (mPackages) {
21348            scheduleWritePackageRestrictionsLocked(userId);
21349            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21350            final long callingId = Binder.clearCallingIdentity();
21351            try {
21352                updateInstantAppInstallerLocked(packageName);
21353            } finally {
21354                Binder.restoreCallingIdentity(callingId);
21355            }
21356            components = mPendingBroadcasts.get(userId, packageName);
21357            final boolean newPackage = components == null;
21358            if (newPackage) {
21359                components = new ArrayList<String>();
21360            }
21361            if (!components.contains(componentName)) {
21362                components.add(componentName);
21363            }
21364            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21365                sendNow = true;
21366                // Purge entry from pending broadcast list if another one exists already
21367                // since we are sending one right away.
21368                mPendingBroadcasts.remove(userId, packageName);
21369            } else {
21370                if (newPackage) {
21371                    mPendingBroadcasts.put(userId, packageName, components);
21372                }
21373                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21374                    // Schedule a message
21375                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21376                }
21377            }
21378        }
21379
21380        long callingId = Binder.clearCallingIdentity();
21381        try {
21382            if (sendNow) {
21383                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21384                sendPackageChangedBroadcast(packageName,
21385                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21386            }
21387        } finally {
21388            Binder.restoreCallingIdentity(callingId);
21389        }
21390    }
21391
21392    @Override
21393    public void flushPackageRestrictionsAsUser(int userId) {
21394        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21395            return;
21396        }
21397        if (!sUserManager.exists(userId)) {
21398            return;
21399        }
21400        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21401                false /* checkShell */, "flushPackageRestrictions");
21402        synchronized (mPackages) {
21403            mSettings.writePackageRestrictionsLPr(userId);
21404            mDirtyUsers.remove(userId);
21405            if (mDirtyUsers.isEmpty()) {
21406                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21407            }
21408        }
21409    }
21410
21411    private void sendPackageChangedBroadcast(String packageName,
21412            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21413        if (DEBUG_INSTALL)
21414            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21415                    + componentNames);
21416        Bundle extras = new Bundle(4);
21417        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21418        String nameList[] = new String[componentNames.size()];
21419        componentNames.toArray(nameList);
21420        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21421        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21422        extras.putInt(Intent.EXTRA_UID, packageUid);
21423        // If this is not reporting a change of the overall package, then only send it
21424        // to registered receivers.  We don't want to launch a swath of apps for every
21425        // little component state change.
21426        final int flags = !componentNames.contains(packageName)
21427                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21428        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21429                new int[] {UserHandle.getUserId(packageUid)});
21430    }
21431
21432    @Override
21433    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21434        if (!sUserManager.exists(userId)) return;
21435        final int callingUid = Binder.getCallingUid();
21436        if (getInstantAppPackageName(callingUid) != null) {
21437            return;
21438        }
21439        final int permission = mContext.checkCallingOrSelfPermission(
21440                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21441        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21442        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21443                true /* requireFullPermission */, true /* checkShell */, "stop package");
21444        // writer
21445        synchronized (mPackages) {
21446            final PackageSetting ps = mSettings.mPackages.get(packageName);
21447            if (!filterAppAccessLPr(ps, callingUid, userId)
21448                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21449                            allowedByPermission, callingUid, userId)) {
21450                scheduleWritePackageRestrictionsLocked(userId);
21451            }
21452        }
21453    }
21454
21455    @Override
21456    public String getInstallerPackageName(String packageName) {
21457        final int callingUid = Binder.getCallingUid();
21458        if (getInstantAppPackageName(callingUid) != null) {
21459            return null;
21460        }
21461        // reader
21462        synchronized (mPackages) {
21463            final PackageSetting ps = mSettings.mPackages.get(packageName);
21464            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21465                return null;
21466            }
21467            return mSettings.getInstallerPackageNameLPr(packageName);
21468        }
21469    }
21470
21471    public boolean isOrphaned(String packageName) {
21472        // reader
21473        synchronized (mPackages) {
21474            return mSettings.isOrphaned(packageName);
21475        }
21476    }
21477
21478    @Override
21479    public int getApplicationEnabledSetting(String packageName, int userId) {
21480        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21481        int callingUid = Binder.getCallingUid();
21482        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21483                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21484        // reader
21485        synchronized (mPackages) {
21486            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21487                return COMPONENT_ENABLED_STATE_DISABLED;
21488            }
21489            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21490        }
21491    }
21492
21493    @Override
21494    public int getComponentEnabledSetting(ComponentName component, int userId) {
21495        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21496        int callingUid = Binder.getCallingUid();
21497        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21498                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21499        synchronized (mPackages) {
21500            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21501                    component, TYPE_UNKNOWN, userId)) {
21502                return COMPONENT_ENABLED_STATE_DISABLED;
21503            }
21504            return mSettings.getComponentEnabledSettingLPr(component, userId);
21505        }
21506    }
21507
21508    @Override
21509    public void enterSafeMode() {
21510        enforceSystemOrRoot("Only the system can request entering safe mode");
21511
21512        if (!mSystemReady) {
21513            mSafeMode = true;
21514        }
21515    }
21516
21517    @Override
21518    public void systemReady() {
21519        enforceSystemOrRoot("Only the system can claim the system is ready");
21520
21521        mSystemReady = true;
21522        final ContentResolver resolver = mContext.getContentResolver();
21523        ContentObserver co = new ContentObserver(mHandler) {
21524            @Override
21525            public void onChange(boolean selfChange) {
21526                mEphemeralAppsDisabled =
21527                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21528                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21529            }
21530        };
21531        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21532                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21533                false, co, UserHandle.USER_SYSTEM);
21534        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21535                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21536        co.onChange(true);
21537
21538        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21539        // disabled after already being started.
21540        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21541                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21542
21543        // Read the compatibilty setting when the system is ready.
21544        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21545                mContext.getContentResolver(),
21546                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21547        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21548        if (DEBUG_SETTINGS) {
21549            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21550        }
21551
21552        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21553
21554        synchronized (mPackages) {
21555            // Verify that all of the preferred activity components actually
21556            // exist.  It is possible for applications to be updated and at
21557            // that point remove a previously declared activity component that
21558            // had been set as a preferred activity.  We try to clean this up
21559            // the next time we encounter that preferred activity, but it is
21560            // possible for the user flow to never be able to return to that
21561            // situation so here we do a sanity check to make sure we haven't
21562            // left any junk around.
21563            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21564            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21565                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21566                removed.clear();
21567                for (PreferredActivity pa : pir.filterSet()) {
21568                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21569                        removed.add(pa);
21570                    }
21571                }
21572                if (removed.size() > 0) {
21573                    for (int r=0; r<removed.size(); r++) {
21574                        PreferredActivity pa = removed.get(r);
21575                        Slog.w(TAG, "Removing dangling preferred activity: "
21576                                + pa.mPref.mComponent);
21577                        pir.removeFilter(pa);
21578                    }
21579                    mSettings.writePackageRestrictionsLPr(
21580                            mSettings.mPreferredActivities.keyAt(i));
21581                }
21582            }
21583
21584            for (int userId : UserManagerService.getInstance().getUserIds()) {
21585                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21586                    grantPermissionsUserIds = ArrayUtils.appendInt(
21587                            grantPermissionsUserIds, userId);
21588                }
21589            }
21590        }
21591        sUserManager.systemReady();
21592
21593        synchronized(mPackages) {
21594            // If we upgraded grant all default permissions before kicking off.
21595            for (int userId : grantPermissionsUserIds) {
21596                mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21597            }
21598        }
21599
21600        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21601            // If we did not grant default permissions, we preload from this the
21602            // default permission exceptions lazily to ensure we don't hit the
21603            // disk on a new user creation.
21604            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21605        }
21606
21607        // Now that we've scanned all packages, and granted any default
21608        // permissions, ensure permissions are updated. Beware of dragons if you
21609        // try optimizing this.
21610        synchronized (mPackages) {
21611            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21612                    UPDATE_PERMISSIONS_ALL);
21613        }
21614
21615        // Kick off any messages waiting for system ready
21616        if (mPostSystemReadyMessages != null) {
21617            for (Message msg : mPostSystemReadyMessages) {
21618                msg.sendToTarget();
21619            }
21620            mPostSystemReadyMessages = null;
21621        }
21622
21623        // Watch for external volumes that come and go over time
21624        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21625        storage.registerListener(mStorageListener);
21626
21627        mInstallerService.systemReady();
21628        mPackageDexOptimizer.systemReady();
21629
21630        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21631                StorageManagerInternal.class);
21632        StorageManagerInternal.addExternalStoragePolicy(
21633                new StorageManagerInternal.ExternalStorageMountPolicy() {
21634            @Override
21635            public int getMountMode(int uid, String packageName) {
21636                if (Process.isIsolated(uid)) {
21637                    return Zygote.MOUNT_EXTERNAL_NONE;
21638                }
21639                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21640                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21641                }
21642                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21643                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21644                }
21645                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21646                    return Zygote.MOUNT_EXTERNAL_READ;
21647                }
21648                return Zygote.MOUNT_EXTERNAL_WRITE;
21649            }
21650
21651            @Override
21652            public boolean hasExternalStorage(int uid, String packageName) {
21653                return true;
21654            }
21655        });
21656
21657        // Now that we're mostly running, clean up stale users and apps
21658        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21659        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21660
21661        if (mPrivappPermissionsViolations != null) {
21662            Slog.wtf(TAG,"Signature|privileged permissions not in "
21663                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21664            mPrivappPermissionsViolations = null;
21665        }
21666    }
21667
21668    public void waitForAppDataPrepared() {
21669        if (mPrepareAppDataFuture == null) {
21670            return;
21671        }
21672        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21673        mPrepareAppDataFuture = null;
21674    }
21675
21676    @Override
21677    public boolean isSafeMode() {
21678        // allow instant applications
21679        return mSafeMode;
21680    }
21681
21682    @Override
21683    public boolean hasSystemUidErrors() {
21684        // allow instant applications
21685        return mHasSystemUidErrors;
21686    }
21687
21688    static String arrayToString(int[] array) {
21689        StringBuffer buf = new StringBuffer(128);
21690        buf.append('[');
21691        if (array != null) {
21692            for (int i=0; i<array.length; i++) {
21693                if (i > 0) buf.append(", ");
21694                buf.append(array[i]);
21695            }
21696        }
21697        buf.append(']');
21698        return buf.toString();
21699    }
21700
21701    @Override
21702    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21703            FileDescriptor err, String[] args, ShellCallback callback,
21704            ResultReceiver resultReceiver) {
21705        (new PackageManagerShellCommand(this)).exec(
21706                this, in, out, err, args, callback, resultReceiver);
21707    }
21708
21709    @Override
21710    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21711        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21712
21713        DumpState dumpState = new DumpState();
21714        boolean fullPreferred = false;
21715        boolean checkin = false;
21716
21717        String packageName = null;
21718        ArraySet<String> permissionNames = null;
21719
21720        int opti = 0;
21721        while (opti < args.length) {
21722            String opt = args[opti];
21723            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21724                break;
21725            }
21726            opti++;
21727
21728            if ("-a".equals(opt)) {
21729                // Right now we only know how to print all.
21730            } else if ("-h".equals(opt)) {
21731                pw.println("Package manager dump options:");
21732                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21733                pw.println("    --checkin: dump for a checkin");
21734                pw.println("    -f: print details of intent filters");
21735                pw.println("    -h: print this help");
21736                pw.println("  cmd may be one of:");
21737                pw.println("    l[ibraries]: list known shared libraries");
21738                pw.println("    f[eatures]: list device features");
21739                pw.println("    k[eysets]: print known keysets");
21740                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21741                pw.println("    perm[issions]: dump permissions");
21742                pw.println("    permission [name ...]: dump declaration and use of given permission");
21743                pw.println("    pref[erred]: print preferred package settings");
21744                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21745                pw.println("    prov[iders]: dump content providers");
21746                pw.println("    p[ackages]: dump installed packages");
21747                pw.println("    s[hared-users]: dump shared user IDs");
21748                pw.println("    m[essages]: print collected runtime messages");
21749                pw.println("    v[erifiers]: print package verifier info");
21750                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21751                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21752                pw.println("    version: print database version info");
21753                pw.println("    write: write current settings now");
21754                pw.println("    installs: details about install sessions");
21755                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21756                pw.println("    dexopt: dump dexopt state");
21757                pw.println("    compiler-stats: dump compiler statistics");
21758                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21759                pw.println("    <package.name>: info about given package");
21760                return;
21761            } else if ("--checkin".equals(opt)) {
21762                checkin = true;
21763            } else if ("-f".equals(opt)) {
21764                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21765            } else if ("--proto".equals(opt)) {
21766                dumpProto(fd);
21767                return;
21768            } else {
21769                pw.println("Unknown argument: " + opt + "; use -h for help");
21770            }
21771        }
21772
21773        // Is the caller requesting to dump a particular piece of data?
21774        if (opti < args.length) {
21775            String cmd = args[opti];
21776            opti++;
21777            // Is this a package name?
21778            if ("android".equals(cmd) || cmd.contains(".")) {
21779                packageName = cmd;
21780                // When dumping a single package, we always dump all of its
21781                // filter information since the amount of data will be reasonable.
21782                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21783            } else if ("check-permission".equals(cmd)) {
21784                if (opti >= args.length) {
21785                    pw.println("Error: check-permission missing permission argument");
21786                    return;
21787                }
21788                String perm = args[opti];
21789                opti++;
21790                if (opti >= args.length) {
21791                    pw.println("Error: check-permission missing package argument");
21792                    return;
21793                }
21794
21795                String pkg = args[opti];
21796                opti++;
21797                int user = UserHandle.getUserId(Binder.getCallingUid());
21798                if (opti < args.length) {
21799                    try {
21800                        user = Integer.parseInt(args[opti]);
21801                    } catch (NumberFormatException e) {
21802                        pw.println("Error: check-permission user argument is not a number: "
21803                                + args[opti]);
21804                        return;
21805                    }
21806                }
21807
21808                // Normalize package name to handle renamed packages and static libs
21809                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21810
21811                pw.println(checkPermission(perm, pkg, user));
21812                return;
21813            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21814                dumpState.setDump(DumpState.DUMP_LIBS);
21815            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21816                dumpState.setDump(DumpState.DUMP_FEATURES);
21817            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21818                if (opti >= args.length) {
21819                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21820                            | DumpState.DUMP_SERVICE_RESOLVERS
21821                            | DumpState.DUMP_RECEIVER_RESOLVERS
21822                            | DumpState.DUMP_CONTENT_RESOLVERS);
21823                } else {
21824                    while (opti < args.length) {
21825                        String name = args[opti];
21826                        if ("a".equals(name) || "activity".equals(name)) {
21827                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21828                        } else if ("s".equals(name) || "service".equals(name)) {
21829                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21830                        } else if ("r".equals(name) || "receiver".equals(name)) {
21831                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21832                        } else if ("c".equals(name) || "content".equals(name)) {
21833                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21834                        } else {
21835                            pw.println("Error: unknown resolver table type: " + name);
21836                            return;
21837                        }
21838                        opti++;
21839                    }
21840                }
21841            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21842                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21843            } else if ("permission".equals(cmd)) {
21844                if (opti >= args.length) {
21845                    pw.println("Error: permission requires permission name");
21846                    return;
21847                }
21848                permissionNames = new ArraySet<>();
21849                while (opti < args.length) {
21850                    permissionNames.add(args[opti]);
21851                    opti++;
21852                }
21853                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21854                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21855            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21856                dumpState.setDump(DumpState.DUMP_PREFERRED);
21857            } else if ("preferred-xml".equals(cmd)) {
21858                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21859                if (opti < args.length && "--full".equals(args[opti])) {
21860                    fullPreferred = true;
21861                    opti++;
21862                }
21863            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21864                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21865            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21866                dumpState.setDump(DumpState.DUMP_PACKAGES);
21867            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21868                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21869            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21870                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21871            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21872                dumpState.setDump(DumpState.DUMP_MESSAGES);
21873            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21874                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21875            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21876                    || "intent-filter-verifiers".equals(cmd)) {
21877                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21878            } else if ("version".equals(cmd)) {
21879                dumpState.setDump(DumpState.DUMP_VERSION);
21880            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21881                dumpState.setDump(DumpState.DUMP_KEYSETS);
21882            } else if ("installs".equals(cmd)) {
21883                dumpState.setDump(DumpState.DUMP_INSTALLS);
21884            } else if ("frozen".equals(cmd)) {
21885                dumpState.setDump(DumpState.DUMP_FROZEN);
21886            } else if ("volumes".equals(cmd)) {
21887                dumpState.setDump(DumpState.DUMP_VOLUMES);
21888            } else if ("dexopt".equals(cmd)) {
21889                dumpState.setDump(DumpState.DUMP_DEXOPT);
21890            } else if ("compiler-stats".equals(cmd)) {
21891                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21892            } else if ("changes".equals(cmd)) {
21893                dumpState.setDump(DumpState.DUMP_CHANGES);
21894            } else if ("write".equals(cmd)) {
21895                synchronized (mPackages) {
21896                    mSettings.writeLPr();
21897                    pw.println("Settings written.");
21898                    return;
21899                }
21900            }
21901        }
21902
21903        if (checkin) {
21904            pw.println("vers,1");
21905        }
21906
21907        // reader
21908        synchronized (mPackages) {
21909            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21910                if (!checkin) {
21911                    if (dumpState.onTitlePrinted())
21912                        pw.println();
21913                    pw.println("Database versions:");
21914                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21915                }
21916            }
21917
21918            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21919                if (!checkin) {
21920                    if (dumpState.onTitlePrinted())
21921                        pw.println();
21922                    pw.println("Verifiers:");
21923                    pw.print("  Required: ");
21924                    pw.print(mRequiredVerifierPackage);
21925                    pw.print(" (uid=");
21926                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21927                            UserHandle.USER_SYSTEM));
21928                    pw.println(")");
21929                } else if (mRequiredVerifierPackage != null) {
21930                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21931                    pw.print(",");
21932                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21933                            UserHandle.USER_SYSTEM));
21934                }
21935            }
21936
21937            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21938                    packageName == null) {
21939                if (mIntentFilterVerifierComponent != null) {
21940                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21941                    if (!checkin) {
21942                        if (dumpState.onTitlePrinted())
21943                            pw.println();
21944                        pw.println("Intent Filter Verifier:");
21945                        pw.print("  Using: ");
21946                        pw.print(verifierPackageName);
21947                        pw.print(" (uid=");
21948                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21949                                UserHandle.USER_SYSTEM));
21950                        pw.println(")");
21951                    } else if (verifierPackageName != null) {
21952                        pw.print("ifv,"); pw.print(verifierPackageName);
21953                        pw.print(",");
21954                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21955                                UserHandle.USER_SYSTEM));
21956                    }
21957                } else {
21958                    pw.println();
21959                    pw.println("No Intent Filter Verifier available!");
21960                }
21961            }
21962
21963            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21964                boolean printedHeader = false;
21965                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21966                while (it.hasNext()) {
21967                    String libName = it.next();
21968                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21969                    if (versionedLib == null) {
21970                        continue;
21971                    }
21972                    final int versionCount = versionedLib.size();
21973                    for (int i = 0; i < versionCount; i++) {
21974                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21975                        if (!checkin) {
21976                            if (!printedHeader) {
21977                                if (dumpState.onTitlePrinted())
21978                                    pw.println();
21979                                pw.println("Libraries:");
21980                                printedHeader = true;
21981                            }
21982                            pw.print("  ");
21983                        } else {
21984                            pw.print("lib,");
21985                        }
21986                        pw.print(libEntry.info.getName());
21987                        if (libEntry.info.isStatic()) {
21988                            pw.print(" version=" + libEntry.info.getVersion());
21989                        }
21990                        if (!checkin) {
21991                            pw.print(" -> ");
21992                        }
21993                        if (libEntry.path != null) {
21994                            pw.print(" (jar) ");
21995                            pw.print(libEntry.path);
21996                        } else {
21997                            pw.print(" (apk) ");
21998                            pw.print(libEntry.apk);
21999                        }
22000                        pw.println();
22001                    }
22002                }
22003            }
22004
22005            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22006                if (dumpState.onTitlePrinted())
22007                    pw.println();
22008                if (!checkin) {
22009                    pw.println("Features:");
22010                }
22011
22012                synchronized (mAvailableFeatures) {
22013                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22014                        if (checkin) {
22015                            pw.print("feat,");
22016                            pw.print(feat.name);
22017                            pw.print(",");
22018                            pw.println(feat.version);
22019                        } else {
22020                            pw.print("  ");
22021                            pw.print(feat.name);
22022                            if (feat.version > 0) {
22023                                pw.print(" version=");
22024                                pw.print(feat.version);
22025                            }
22026                            pw.println();
22027                        }
22028                    }
22029                }
22030            }
22031
22032            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22033                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22034                        : "Activity Resolver Table:", "  ", packageName,
22035                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22036                    dumpState.setTitlePrinted(true);
22037                }
22038            }
22039            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22040                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22041                        : "Receiver Resolver Table:", "  ", packageName,
22042                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22043                    dumpState.setTitlePrinted(true);
22044                }
22045            }
22046            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22047                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22048                        : "Service Resolver Table:", "  ", packageName,
22049                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22050                    dumpState.setTitlePrinted(true);
22051                }
22052            }
22053            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22054                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22055                        : "Provider Resolver Table:", "  ", packageName,
22056                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22057                    dumpState.setTitlePrinted(true);
22058                }
22059            }
22060
22061            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22062                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22063                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22064                    int user = mSettings.mPreferredActivities.keyAt(i);
22065                    if (pir.dump(pw,
22066                            dumpState.getTitlePrinted()
22067                                ? "\nPreferred Activities User " + user + ":"
22068                                : "Preferred Activities User " + user + ":", "  ",
22069                            packageName, true, false)) {
22070                        dumpState.setTitlePrinted(true);
22071                    }
22072                }
22073            }
22074
22075            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22076                pw.flush();
22077                FileOutputStream fout = new FileOutputStream(fd);
22078                BufferedOutputStream str = new BufferedOutputStream(fout);
22079                XmlSerializer serializer = new FastXmlSerializer();
22080                try {
22081                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22082                    serializer.startDocument(null, true);
22083                    serializer.setFeature(
22084                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22085                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22086                    serializer.endDocument();
22087                    serializer.flush();
22088                } catch (IllegalArgumentException e) {
22089                    pw.println("Failed writing: " + e);
22090                } catch (IllegalStateException e) {
22091                    pw.println("Failed writing: " + e);
22092                } catch (IOException e) {
22093                    pw.println("Failed writing: " + e);
22094                }
22095            }
22096
22097            if (!checkin
22098                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22099                    && packageName == null) {
22100                pw.println();
22101                int count = mSettings.mPackages.size();
22102                if (count == 0) {
22103                    pw.println("No applications!");
22104                    pw.println();
22105                } else {
22106                    final String prefix = "  ";
22107                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22108                    if (allPackageSettings.size() == 0) {
22109                        pw.println("No domain preferred apps!");
22110                        pw.println();
22111                    } else {
22112                        pw.println("App verification status:");
22113                        pw.println();
22114                        count = 0;
22115                        for (PackageSetting ps : allPackageSettings) {
22116                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22117                            if (ivi == null || ivi.getPackageName() == null) continue;
22118                            pw.println(prefix + "Package: " + ivi.getPackageName());
22119                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22120                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22121                            pw.println();
22122                            count++;
22123                        }
22124                        if (count == 0) {
22125                            pw.println(prefix + "No app verification established.");
22126                            pw.println();
22127                        }
22128                        for (int userId : sUserManager.getUserIds()) {
22129                            pw.println("App linkages for user " + userId + ":");
22130                            pw.println();
22131                            count = 0;
22132                            for (PackageSetting ps : allPackageSettings) {
22133                                final long status = ps.getDomainVerificationStatusForUser(userId);
22134                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22135                                        && !DEBUG_DOMAIN_VERIFICATION) {
22136                                    continue;
22137                                }
22138                                pw.println(prefix + "Package: " + ps.name);
22139                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22140                                String statusStr = IntentFilterVerificationInfo.
22141                                        getStatusStringFromValue(status);
22142                                pw.println(prefix + "Status:  " + statusStr);
22143                                pw.println();
22144                                count++;
22145                            }
22146                            if (count == 0) {
22147                                pw.println(prefix + "No configured app linkages.");
22148                                pw.println();
22149                            }
22150                        }
22151                    }
22152                }
22153            }
22154
22155            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22156                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22157                if (packageName == null && permissionNames == null) {
22158                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22159                        if (iperm == 0) {
22160                            if (dumpState.onTitlePrinted())
22161                                pw.println();
22162                            pw.println("AppOp Permissions:");
22163                        }
22164                        pw.print("  AppOp Permission ");
22165                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22166                        pw.println(":");
22167                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22168                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22169                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22170                        }
22171                    }
22172                }
22173            }
22174
22175            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22176                boolean printedSomething = false;
22177                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22178                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22179                        continue;
22180                    }
22181                    if (!printedSomething) {
22182                        if (dumpState.onTitlePrinted())
22183                            pw.println();
22184                        pw.println("Registered ContentProviders:");
22185                        printedSomething = true;
22186                    }
22187                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22188                    pw.print("    "); pw.println(p.toString());
22189                }
22190                printedSomething = false;
22191                for (Map.Entry<String, PackageParser.Provider> entry :
22192                        mProvidersByAuthority.entrySet()) {
22193                    PackageParser.Provider p = entry.getValue();
22194                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22195                        continue;
22196                    }
22197                    if (!printedSomething) {
22198                        if (dumpState.onTitlePrinted())
22199                            pw.println();
22200                        pw.println("ContentProvider Authorities:");
22201                        printedSomething = true;
22202                    }
22203                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22204                    pw.print("    "); pw.println(p.toString());
22205                    if (p.info != null && p.info.applicationInfo != null) {
22206                        final String appInfo = p.info.applicationInfo.toString();
22207                        pw.print("      applicationInfo="); pw.println(appInfo);
22208                    }
22209                }
22210            }
22211
22212            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22213                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22214            }
22215
22216            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22217                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22218            }
22219
22220            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22221                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22222            }
22223
22224            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22225                if (dumpState.onTitlePrinted()) pw.println();
22226                pw.println("Package Changes:");
22227                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22228                final int K = mChangedPackages.size();
22229                for (int i = 0; i < K; i++) {
22230                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22231                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22232                    final int N = changes.size();
22233                    if (N == 0) {
22234                        pw.print("    "); pw.println("No packages changed");
22235                    } else {
22236                        for (int j = 0; j < N; j++) {
22237                            final String pkgName = changes.valueAt(j);
22238                            final int sequenceNumber = changes.keyAt(j);
22239                            pw.print("    ");
22240                            pw.print("seq=");
22241                            pw.print(sequenceNumber);
22242                            pw.print(", package=");
22243                            pw.println(pkgName);
22244                        }
22245                    }
22246                }
22247            }
22248
22249            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22250                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22251            }
22252
22253            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22254                // XXX should handle packageName != null by dumping only install data that
22255                // the given package is involved with.
22256                if (dumpState.onTitlePrinted()) pw.println();
22257
22258                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22259                ipw.println();
22260                ipw.println("Frozen packages:");
22261                ipw.increaseIndent();
22262                if (mFrozenPackages.size() == 0) {
22263                    ipw.println("(none)");
22264                } else {
22265                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22266                        ipw.println(mFrozenPackages.valueAt(i));
22267                    }
22268                }
22269                ipw.decreaseIndent();
22270            }
22271
22272            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22273                if (dumpState.onTitlePrinted()) pw.println();
22274
22275                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22276                ipw.println();
22277                ipw.println("Loaded volumes:");
22278                ipw.increaseIndent();
22279                if (mLoadedVolumes.size() == 0) {
22280                    ipw.println("(none)");
22281                } else {
22282                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22283                        ipw.println(mLoadedVolumes.valueAt(i));
22284                    }
22285                }
22286                ipw.decreaseIndent();
22287            }
22288
22289            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22290                if (dumpState.onTitlePrinted()) pw.println();
22291                dumpDexoptStateLPr(pw, packageName);
22292            }
22293
22294            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22295                if (dumpState.onTitlePrinted()) pw.println();
22296                dumpCompilerStatsLPr(pw, packageName);
22297            }
22298
22299            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22300                if (dumpState.onTitlePrinted()) pw.println();
22301                mSettings.dumpReadMessagesLPr(pw, dumpState);
22302
22303                pw.println();
22304                pw.println("Package warning messages:");
22305                BufferedReader in = null;
22306                String line = null;
22307                try {
22308                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22309                    while ((line = in.readLine()) != null) {
22310                        if (line.contains("ignored: updated version")) continue;
22311                        pw.println(line);
22312                    }
22313                } catch (IOException ignored) {
22314                } finally {
22315                    IoUtils.closeQuietly(in);
22316                }
22317            }
22318
22319            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22320                BufferedReader in = null;
22321                String line = null;
22322                try {
22323                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22324                    while ((line = in.readLine()) != null) {
22325                        if (line.contains("ignored: updated version")) continue;
22326                        pw.print("msg,");
22327                        pw.println(line);
22328                    }
22329                } catch (IOException ignored) {
22330                } finally {
22331                    IoUtils.closeQuietly(in);
22332                }
22333            }
22334        }
22335
22336        // PackageInstaller should be called outside of mPackages lock
22337        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22338            // XXX should handle packageName != null by dumping only install data that
22339            // the given package is involved with.
22340            if (dumpState.onTitlePrinted()) pw.println();
22341            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22342        }
22343    }
22344
22345    private void dumpProto(FileDescriptor fd) {
22346        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22347
22348        synchronized (mPackages) {
22349            final long requiredVerifierPackageToken =
22350                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22351            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22352            proto.write(
22353                    PackageServiceDumpProto.PackageShortProto.UID,
22354                    getPackageUid(
22355                            mRequiredVerifierPackage,
22356                            MATCH_DEBUG_TRIAGED_MISSING,
22357                            UserHandle.USER_SYSTEM));
22358            proto.end(requiredVerifierPackageToken);
22359
22360            if (mIntentFilterVerifierComponent != null) {
22361                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22362                final long verifierPackageToken =
22363                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22364                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22365                proto.write(
22366                        PackageServiceDumpProto.PackageShortProto.UID,
22367                        getPackageUid(
22368                                verifierPackageName,
22369                                MATCH_DEBUG_TRIAGED_MISSING,
22370                                UserHandle.USER_SYSTEM));
22371                proto.end(verifierPackageToken);
22372            }
22373
22374            dumpSharedLibrariesProto(proto);
22375            dumpFeaturesProto(proto);
22376            mSettings.dumpPackagesProto(proto);
22377            mSettings.dumpSharedUsersProto(proto);
22378            dumpMessagesProto(proto);
22379        }
22380        proto.flush();
22381    }
22382
22383    private void dumpMessagesProto(ProtoOutputStream proto) {
22384        BufferedReader in = null;
22385        String line = null;
22386        try {
22387            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22388            while ((line = in.readLine()) != null) {
22389                if (line.contains("ignored: updated version")) continue;
22390                proto.write(PackageServiceDumpProto.MESSAGES, line);
22391            }
22392        } catch (IOException ignored) {
22393        } finally {
22394            IoUtils.closeQuietly(in);
22395        }
22396    }
22397
22398    private void dumpFeaturesProto(ProtoOutputStream proto) {
22399        synchronized (mAvailableFeatures) {
22400            final int count = mAvailableFeatures.size();
22401            for (int i = 0; i < count; i++) {
22402                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22403                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22404                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22405                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22406                proto.end(featureToken);
22407            }
22408        }
22409    }
22410
22411    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22412        final int count = mSharedLibraries.size();
22413        for (int i = 0; i < count; i++) {
22414            final String libName = mSharedLibraries.keyAt(i);
22415            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22416            if (versionedLib == null) {
22417                continue;
22418            }
22419            final int versionCount = versionedLib.size();
22420            for (int j = 0; j < versionCount; j++) {
22421                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22422                final long sharedLibraryToken =
22423                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22424                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22425                final boolean isJar = (libEntry.path != null);
22426                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22427                if (isJar) {
22428                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22429                } else {
22430                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22431                }
22432                proto.end(sharedLibraryToken);
22433            }
22434        }
22435    }
22436
22437    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22438        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22439        ipw.println();
22440        ipw.println("Dexopt state:");
22441        ipw.increaseIndent();
22442        Collection<PackageParser.Package> packages = null;
22443        if (packageName != null) {
22444            PackageParser.Package targetPackage = mPackages.get(packageName);
22445            if (targetPackage != null) {
22446                packages = Collections.singletonList(targetPackage);
22447            } else {
22448                ipw.println("Unable to find package: " + packageName);
22449                return;
22450            }
22451        } else {
22452            packages = mPackages.values();
22453        }
22454
22455        for (PackageParser.Package pkg : packages) {
22456            ipw.println("[" + pkg.packageName + "]");
22457            ipw.increaseIndent();
22458            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22459                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22460            ipw.decreaseIndent();
22461        }
22462    }
22463
22464    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22465        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22466        ipw.println();
22467        ipw.println("Compiler stats:");
22468        ipw.increaseIndent();
22469        Collection<PackageParser.Package> packages = null;
22470        if (packageName != null) {
22471            PackageParser.Package targetPackage = mPackages.get(packageName);
22472            if (targetPackage != null) {
22473                packages = Collections.singletonList(targetPackage);
22474            } else {
22475                ipw.println("Unable to find package: " + packageName);
22476                return;
22477            }
22478        } else {
22479            packages = mPackages.values();
22480        }
22481
22482        for (PackageParser.Package pkg : packages) {
22483            ipw.println("[" + pkg.packageName + "]");
22484            ipw.increaseIndent();
22485
22486            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22487            if (stats == null) {
22488                ipw.println("(No recorded stats)");
22489            } else {
22490                stats.dump(ipw);
22491            }
22492            ipw.decreaseIndent();
22493        }
22494    }
22495
22496    private String dumpDomainString(String packageName) {
22497        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22498                .getList();
22499        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22500
22501        ArraySet<String> result = new ArraySet<>();
22502        if (iviList.size() > 0) {
22503            for (IntentFilterVerificationInfo ivi : iviList) {
22504                for (String host : ivi.getDomains()) {
22505                    result.add(host);
22506                }
22507            }
22508        }
22509        if (filters != null && filters.size() > 0) {
22510            for (IntentFilter filter : filters) {
22511                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22512                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22513                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22514                    result.addAll(filter.getHostsList());
22515                }
22516            }
22517        }
22518
22519        StringBuilder sb = new StringBuilder(result.size() * 16);
22520        for (String domain : result) {
22521            if (sb.length() > 0) sb.append(" ");
22522            sb.append(domain);
22523        }
22524        return sb.toString();
22525    }
22526
22527    // ------- apps on sdcard specific code -------
22528    static final boolean DEBUG_SD_INSTALL = false;
22529
22530    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22531
22532    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22533
22534    private boolean mMediaMounted = false;
22535
22536    static String getEncryptKey() {
22537        try {
22538            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22539                    SD_ENCRYPTION_KEYSTORE_NAME);
22540            if (sdEncKey == null) {
22541                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22542                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22543                if (sdEncKey == null) {
22544                    Slog.e(TAG, "Failed to create encryption keys");
22545                    return null;
22546                }
22547            }
22548            return sdEncKey;
22549        } catch (NoSuchAlgorithmException nsae) {
22550            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22551            return null;
22552        } catch (IOException ioe) {
22553            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22554            return null;
22555        }
22556    }
22557
22558    /*
22559     * Update media status on PackageManager.
22560     */
22561    @Override
22562    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22563        enforceSystemOrRoot("Media status can only be updated by the system");
22564        // reader; this apparently protects mMediaMounted, but should probably
22565        // be a different lock in that case.
22566        synchronized (mPackages) {
22567            Log.i(TAG, "Updating external media status from "
22568                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22569                    + (mediaStatus ? "mounted" : "unmounted"));
22570            if (DEBUG_SD_INSTALL)
22571                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22572                        + ", mMediaMounted=" + mMediaMounted);
22573            if (mediaStatus == mMediaMounted) {
22574                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22575                        : 0, -1);
22576                mHandler.sendMessage(msg);
22577                return;
22578            }
22579            mMediaMounted = mediaStatus;
22580        }
22581        // Queue up an async operation since the package installation may take a
22582        // little while.
22583        mHandler.post(new Runnable() {
22584            public void run() {
22585                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22586            }
22587        });
22588    }
22589
22590    /**
22591     * Called by StorageManagerService when the initial ASECs to scan are available.
22592     * Should block until all the ASEC containers are finished being scanned.
22593     */
22594    public void scanAvailableAsecs() {
22595        updateExternalMediaStatusInner(true, false, false);
22596    }
22597
22598    /*
22599     * Collect information of applications on external media, map them against
22600     * existing containers and update information based on current mount status.
22601     * Please note that we always have to report status if reportStatus has been
22602     * set to true especially when unloading packages.
22603     */
22604    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22605            boolean externalStorage) {
22606        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22607        int[] uidArr = EmptyArray.INT;
22608
22609        final String[] list = PackageHelper.getSecureContainerList();
22610        if (ArrayUtils.isEmpty(list)) {
22611            Log.i(TAG, "No secure containers found");
22612        } else {
22613            // Process list of secure containers and categorize them
22614            // as active or stale based on their package internal state.
22615
22616            // reader
22617            synchronized (mPackages) {
22618                for (String cid : list) {
22619                    // Leave stages untouched for now; installer service owns them
22620                    if (PackageInstallerService.isStageName(cid)) continue;
22621
22622                    if (DEBUG_SD_INSTALL)
22623                        Log.i(TAG, "Processing container " + cid);
22624                    String pkgName = getAsecPackageName(cid);
22625                    if (pkgName == null) {
22626                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22627                        continue;
22628                    }
22629                    if (DEBUG_SD_INSTALL)
22630                        Log.i(TAG, "Looking for pkg : " + pkgName);
22631
22632                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22633                    if (ps == null) {
22634                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22635                        continue;
22636                    }
22637
22638                    /*
22639                     * Skip packages that are not external if we're unmounting
22640                     * external storage.
22641                     */
22642                    if (externalStorage && !isMounted && !isExternal(ps)) {
22643                        continue;
22644                    }
22645
22646                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22647                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22648                    // The package status is changed only if the code path
22649                    // matches between settings and the container id.
22650                    if (ps.codePathString != null
22651                            && ps.codePathString.startsWith(args.getCodePath())) {
22652                        if (DEBUG_SD_INSTALL) {
22653                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22654                                    + " at code path: " + ps.codePathString);
22655                        }
22656
22657                        // We do have a valid package installed on sdcard
22658                        processCids.put(args, ps.codePathString);
22659                        final int uid = ps.appId;
22660                        if (uid != -1) {
22661                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22662                        }
22663                    } else {
22664                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22665                                + ps.codePathString);
22666                    }
22667                }
22668            }
22669
22670            Arrays.sort(uidArr);
22671        }
22672
22673        // Process packages with valid entries.
22674        if (isMounted) {
22675            if (DEBUG_SD_INSTALL)
22676                Log.i(TAG, "Loading packages");
22677            loadMediaPackages(processCids, uidArr, externalStorage);
22678            startCleaningPackages();
22679            mInstallerService.onSecureContainersAvailable();
22680        } else {
22681            if (DEBUG_SD_INSTALL)
22682                Log.i(TAG, "Unloading packages");
22683            unloadMediaPackages(processCids, uidArr, reportStatus);
22684        }
22685    }
22686
22687    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22688            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22689        final int size = infos.size();
22690        final String[] packageNames = new String[size];
22691        final int[] packageUids = new int[size];
22692        for (int i = 0; i < size; i++) {
22693            final ApplicationInfo info = infos.get(i);
22694            packageNames[i] = info.packageName;
22695            packageUids[i] = info.uid;
22696        }
22697        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22698                finishedReceiver);
22699    }
22700
22701    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22702            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22703        sendResourcesChangedBroadcast(mediaStatus, replacing,
22704                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22705    }
22706
22707    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22708            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22709        int size = pkgList.length;
22710        if (size > 0) {
22711            // Send broadcasts here
22712            Bundle extras = new Bundle();
22713            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22714            if (uidArr != null) {
22715                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22716            }
22717            if (replacing) {
22718                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22719            }
22720            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22721                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22722            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22723        }
22724    }
22725
22726   /*
22727     * Look at potentially valid container ids from processCids If package
22728     * information doesn't match the one on record or package scanning fails,
22729     * the cid is added to list of removeCids. We currently don't delete stale
22730     * containers.
22731     */
22732    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22733            boolean externalStorage) {
22734        ArrayList<String> pkgList = new ArrayList<String>();
22735        Set<AsecInstallArgs> keys = processCids.keySet();
22736
22737        for (AsecInstallArgs args : keys) {
22738            String codePath = processCids.get(args);
22739            if (DEBUG_SD_INSTALL)
22740                Log.i(TAG, "Loading container : " + args.cid);
22741            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22742            try {
22743                // Make sure there are no container errors first.
22744                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22745                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22746                            + " when installing from sdcard");
22747                    continue;
22748                }
22749                // Check code path here.
22750                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22751                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22752                            + " does not match one in settings " + codePath);
22753                    continue;
22754                }
22755                // Parse package
22756                int parseFlags = mDefParseFlags;
22757                if (args.isExternalAsec()) {
22758                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22759                }
22760                if (args.isFwdLocked()) {
22761                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22762                }
22763
22764                synchronized (mInstallLock) {
22765                    PackageParser.Package pkg = null;
22766                    try {
22767                        // Sadly we don't know the package name yet to freeze it
22768                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22769                                SCAN_IGNORE_FROZEN, 0, null);
22770                    } catch (PackageManagerException e) {
22771                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22772                    }
22773                    // Scan the package
22774                    if (pkg != null) {
22775                        /*
22776                         * TODO why is the lock being held? doPostInstall is
22777                         * called in other places without the lock. This needs
22778                         * to be straightened out.
22779                         */
22780                        // writer
22781                        synchronized (mPackages) {
22782                            retCode = PackageManager.INSTALL_SUCCEEDED;
22783                            pkgList.add(pkg.packageName);
22784                            // Post process args
22785                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22786                                    pkg.applicationInfo.uid);
22787                        }
22788                    } else {
22789                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22790                    }
22791                }
22792
22793            } finally {
22794                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22795                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22796                }
22797            }
22798        }
22799        // writer
22800        synchronized (mPackages) {
22801            // If the platform SDK has changed since the last time we booted,
22802            // we need to re-grant app permission to catch any new ones that
22803            // appear. This is really a hack, and means that apps can in some
22804            // cases get permissions that the user didn't initially explicitly
22805            // allow... it would be nice to have some better way to handle
22806            // this situation.
22807            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22808                    : mSettings.getInternalVersion();
22809            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22810                    : StorageManager.UUID_PRIVATE_INTERNAL;
22811
22812            int updateFlags = UPDATE_PERMISSIONS_ALL;
22813            if (ver.sdkVersion != mSdkVersion) {
22814                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22815                        + mSdkVersion + "; regranting permissions for external");
22816                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22817            }
22818            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22819
22820            // Yay, everything is now upgraded
22821            ver.forceCurrent();
22822
22823            // can downgrade to reader
22824            // Persist settings
22825            mSettings.writeLPr();
22826        }
22827        // Send a broadcast to let everyone know we are done processing
22828        if (pkgList.size() > 0) {
22829            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22830        }
22831    }
22832
22833   /*
22834     * Utility method to unload a list of specified containers
22835     */
22836    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22837        // Just unmount all valid containers.
22838        for (AsecInstallArgs arg : cidArgs) {
22839            synchronized (mInstallLock) {
22840                arg.doPostDeleteLI(false);
22841           }
22842       }
22843   }
22844
22845    /*
22846     * Unload packages mounted on external media. This involves deleting package
22847     * data from internal structures, sending broadcasts about disabled packages,
22848     * gc'ing to free up references, unmounting all secure containers
22849     * corresponding to packages on external media, and posting a
22850     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22851     * that we always have to post this message if status has been requested no
22852     * matter what.
22853     */
22854    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22855            final boolean reportStatus) {
22856        if (DEBUG_SD_INSTALL)
22857            Log.i(TAG, "unloading media packages");
22858        ArrayList<String> pkgList = new ArrayList<String>();
22859        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22860        final Set<AsecInstallArgs> keys = processCids.keySet();
22861        for (AsecInstallArgs args : keys) {
22862            String pkgName = args.getPackageName();
22863            if (DEBUG_SD_INSTALL)
22864                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22865            // Delete package internally
22866            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22867            synchronized (mInstallLock) {
22868                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22869                final boolean res;
22870                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22871                        "unloadMediaPackages")) {
22872                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22873                            null);
22874                }
22875                if (res) {
22876                    pkgList.add(pkgName);
22877                } else {
22878                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22879                    failedList.add(args);
22880                }
22881            }
22882        }
22883
22884        // reader
22885        synchronized (mPackages) {
22886            // We didn't update the settings after removing each package;
22887            // write them now for all packages.
22888            mSettings.writeLPr();
22889        }
22890
22891        // We have to absolutely send UPDATED_MEDIA_STATUS only
22892        // after confirming that all the receivers processed the ordered
22893        // broadcast when packages get disabled, force a gc to clean things up.
22894        // and unload all the containers.
22895        if (pkgList.size() > 0) {
22896            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22897                    new IIntentReceiver.Stub() {
22898                public void performReceive(Intent intent, int resultCode, String data,
22899                        Bundle extras, boolean ordered, boolean sticky,
22900                        int sendingUser) throws RemoteException {
22901                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22902                            reportStatus ? 1 : 0, 1, keys);
22903                    mHandler.sendMessage(msg);
22904                }
22905            });
22906        } else {
22907            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22908                    keys);
22909            mHandler.sendMessage(msg);
22910        }
22911    }
22912
22913    private void loadPrivatePackages(final VolumeInfo vol) {
22914        mHandler.post(new Runnable() {
22915            @Override
22916            public void run() {
22917                loadPrivatePackagesInner(vol);
22918            }
22919        });
22920    }
22921
22922    private void loadPrivatePackagesInner(VolumeInfo vol) {
22923        final String volumeUuid = vol.fsUuid;
22924        if (TextUtils.isEmpty(volumeUuid)) {
22925            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22926            return;
22927        }
22928
22929        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22930        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22931        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22932
22933        final VersionInfo ver;
22934        final List<PackageSetting> packages;
22935        synchronized (mPackages) {
22936            ver = mSettings.findOrCreateVersion(volumeUuid);
22937            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22938        }
22939
22940        for (PackageSetting ps : packages) {
22941            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22942            synchronized (mInstallLock) {
22943                final PackageParser.Package pkg;
22944                try {
22945                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22946                    loaded.add(pkg.applicationInfo);
22947
22948                } catch (PackageManagerException e) {
22949                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22950                }
22951
22952                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22953                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22954                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22955                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22956                }
22957            }
22958        }
22959
22960        // Reconcile app data for all started/unlocked users
22961        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22962        final UserManager um = mContext.getSystemService(UserManager.class);
22963        UserManagerInternal umInternal = getUserManagerInternal();
22964        for (UserInfo user : um.getUsers()) {
22965            final int flags;
22966            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22967                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22968            } else if (umInternal.isUserRunning(user.id)) {
22969                flags = StorageManager.FLAG_STORAGE_DE;
22970            } else {
22971                continue;
22972            }
22973
22974            try {
22975                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22976                synchronized (mInstallLock) {
22977                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22978                }
22979            } catch (IllegalStateException e) {
22980                // Device was probably ejected, and we'll process that event momentarily
22981                Slog.w(TAG, "Failed to prepare storage: " + e);
22982            }
22983        }
22984
22985        synchronized (mPackages) {
22986            int updateFlags = UPDATE_PERMISSIONS_ALL;
22987            if (ver.sdkVersion != mSdkVersion) {
22988                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22989                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22990                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22991            }
22992            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22993
22994            // Yay, everything is now upgraded
22995            ver.forceCurrent();
22996
22997            mSettings.writeLPr();
22998        }
22999
23000        for (PackageFreezer freezer : freezers) {
23001            freezer.close();
23002        }
23003
23004        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23005        sendResourcesChangedBroadcast(true, false, loaded, null);
23006        mLoadedVolumes.add(vol.getId());
23007    }
23008
23009    private void unloadPrivatePackages(final VolumeInfo vol) {
23010        mHandler.post(new Runnable() {
23011            @Override
23012            public void run() {
23013                unloadPrivatePackagesInner(vol);
23014            }
23015        });
23016    }
23017
23018    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23019        final String volumeUuid = vol.fsUuid;
23020        if (TextUtils.isEmpty(volumeUuid)) {
23021            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23022            return;
23023        }
23024
23025        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23026        synchronized (mInstallLock) {
23027        synchronized (mPackages) {
23028            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23029            for (PackageSetting ps : packages) {
23030                if (ps.pkg == null) continue;
23031
23032                final ApplicationInfo info = ps.pkg.applicationInfo;
23033                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23034                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23035
23036                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23037                        "unloadPrivatePackagesInner")) {
23038                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23039                            false, null)) {
23040                        unloaded.add(info);
23041                    } else {
23042                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23043                    }
23044                }
23045
23046                // Try very hard to release any references to this package
23047                // so we don't risk the system server being killed due to
23048                // open FDs
23049                AttributeCache.instance().removePackage(ps.name);
23050            }
23051
23052            mSettings.writeLPr();
23053        }
23054        }
23055
23056        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23057        sendResourcesChangedBroadcast(false, false, unloaded, null);
23058        mLoadedVolumes.remove(vol.getId());
23059
23060        // Try very hard to release any references to this path so we don't risk
23061        // the system server being killed due to open FDs
23062        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23063
23064        for (int i = 0; i < 3; i++) {
23065            System.gc();
23066            System.runFinalization();
23067        }
23068    }
23069
23070    private void assertPackageKnown(String volumeUuid, String packageName)
23071            throws PackageManagerException {
23072        synchronized (mPackages) {
23073            // Normalize package name to handle renamed packages
23074            packageName = normalizePackageNameLPr(packageName);
23075
23076            final PackageSetting ps = mSettings.mPackages.get(packageName);
23077            if (ps == null) {
23078                throw new PackageManagerException("Package " + packageName + " is unknown");
23079            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23080                throw new PackageManagerException(
23081                        "Package " + packageName + " found on unknown volume " + volumeUuid
23082                                + "; expected volume " + ps.volumeUuid);
23083            }
23084        }
23085    }
23086
23087    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23088            throws PackageManagerException {
23089        synchronized (mPackages) {
23090            // Normalize package name to handle renamed packages
23091            packageName = normalizePackageNameLPr(packageName);
23092
23093            final PackageSetting ps = mSettings.mPackages.get(packageName);
23094            if (ps == null) {
23095                throw new PackageManagerException("Package " + packageName + " is unknown");
23096            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23097                throw new PackageManagerException(
23098                        "Package " + packageName + " found on unknown volume " + volumeUuid
23099                                + "; expected volume " + ps.volumeUuid);
23100            } else if (!ps.getInstalled(userId)) {
23101                throw new PackageManagerException(
23102                        "Package " + packageName + " not installed for user " + userId);
23103            }
23104        }
23105    }
23106
23107    private List<String> collectAbsoluteCodePaths() {
23108        synchronized (mPackages) {
23109            List<String> codePaths = new ArrayList<>();
23110            final int packageCount = mSettings.mPackages.size();
23111            for (int i = 0; i < packageCount; i++) {
23112                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23113                codePaths.add(ps.codePath.getAbsolutePath());
23114            }
23115            return codePaths;
23116        }
23117    }
23118
23119    /**
23120     * Examine all apps present on given mounted volume, and destroy apps that
23121     * aren't expected, either due to uninstallation or reinstallation on
23122     * another volume.
23123     */
23124    private void reconcileApps(String volumeUuid) {
23125        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23126        List<File> filesToDelete = null;
23127
23128        final File[] files = FileUtils.listFilesOrEmpty(
23129                Environment.getDataAppDirectory(volumeUuid));
23130        for (File file : files) {
23131            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23132                    && !PackageInstallerService.isStageName(file.getName());
23133            if (!isPackage) {
23134                // Ignore entries which are not packages
23135                continue;
23136            }
23137
23138            String absolutePath = file.getAbsolutePath();
23139
23140            boolean pathValid = false;
23141            final int absoluteCodePathCount = absoluteCodePaths.size();
23142            for (int i = 0; i < absoluteCodePathCount; i++) {
23143                String absoluteCodePath = absoluteCodePaths.get(i);
23144                if (absolutePath.startsWith(absoluteCodePath)) {
23145                    pathValid = true;
23146                    break;
23147                }
23148            }
23149
23150            if (!pathValid) {
23151                if (filesToDelete == null) {
23152                    filesToDelete = new ArrayList<>();
23153                }
23154                filesToDelete.add(file);
23155            }
23156        }
23157
23158        if (filesToDelete != null) {
23159            final int fileToDeleteCount = filesToDelete.size();
23160            for (int i = 0; i < fileToDeleteCount; i++) {
23161                File fileToDelete = filesToDelete.get(i);
23162                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23163                synchronized (mInstallLock) {
23164                    removeCodePathLI(fileToDelete);
23165                }
23166            }
23167        }
23168    }
23169
23170    /**
23171     * Reconcile all app data for the given user.
23172     * <p>
23173     * Verifies that directories exist and that ownership and labeling is
23174     * correct for all installed apps on all mounted volumes.
23175     */
23176    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23177        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23178        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23179            final String volumeUuid = vol.getFsUuid();
23180            synchronized (mInstallLock) {
23181                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23182            }
23183        }
23184    }
23185
23186    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23187            boolean migrateAppData) {
23188        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23189    }
23190
23191    /**
23192     * Reconcile all app data on given mounted volume.
23193     * <p>
23194     * Destroys app data that isn't expected, either due to uninstallation or
23195     * reinstallation on another volume.
23196     * <p>
23197     * Verifies that directories exist and that ownership and labeling is
23198     * correct for all installed apps.
23199     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23200     */
23201    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23202            boolean migrateAppData, boolean onlyCoreApps) {
23203        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23204                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23205        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23206
23207        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23208        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23209
23210        // First look for stale data that doesn't belong, and check if things
23211        // have changed since we did our last restorecon
23212        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23213            if (StorageManager.isFileEncryptedNativeOrEmulated()
23214                    && !StorageManager.isUserKeyUnlocked(userId)) {
23215                throw new RuntimeException(
23216                        "Yikes, someone asked us to reconcile CE storage while " + userId
23217                                + " was still locked; this would have caused massive data loss!");
23218            }
23219
23220            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23221            for (File file : files) {
23222                final String packageName = file.getName();
23223                try {
23224                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23225                } catch (PackageManagerException e) {
23226                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23227                    try {
23228                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23229                                StorageManager.FLAG_STORAGE_CE, 0);
23230                    } catch (InstallerException e2) {
23231                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23232                    }
23233                }
23234            }
23235        }
23236        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23237            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23238            for (File file : files) {
23239                final String packageName = file.getName();
23240                try {
23241                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23242                } catch (PackageManagerException e) {
23243                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23244                    try {
23245                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23246                                StorageManager.FLAG_STORAGE_DE, 0);
23247                    } catch (InstallerException e2) {
23248                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23249                    }
23250                }
23251            }
23252        }
23253
23254        // Ensure that data directories are ready to roll for all packages
23255        // installed for this volume and user
23256        final List<PackageSetting> packages;
23257        synchronized (mPackages) {
23258            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23259        }
23260        int preparedCount = 0;
23261        for (PackageSetting ps : packages) {
23262            final String packageName = ps.name;
23263            if (ps.pkg == null) {
23264                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23265                // TODO: might be due to legacy ASEC apps; we should circle back
23266                // and reconcile again once they're scanned
23267                continue;
23268            }
23269            // Skip non-core apps if requested
23270            if (onlyCoreApps && !ps.pkg.coreApp) {
23271                result.add(packageName);
23272                continue;
23273            }
23274
23275            if (ps.getInstalled(userId)) {
23276                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23277                preparedCount++;
23278            }
23279        }
23280
23281        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23282        return result;
23283    }
23284
23285    /**
23286     * Prepare app data for the given app just after it was installed or
23287     * upgraded. This method carefully only touches users that it's installed
23288     * for, and it forces a restorecon to handle any seinfo changes.
23289     * <p>
23290     * Verifies that directories exist and that ownership and labeling is
23291     * correct for all installed apps. If there is an ownership mismatch, it
23292     * will try recovering system apps by wiping data; third-party app data is
23293     * left intact.
23294     * <p>
23295     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23296     */
23297    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23298        final PackageSetting ps;
23299        synchronized (mPackages) {
23300            ps = mSettings.mPackages.get(pkg.packageName);
23301            mSettings.writeKernelMappingLPr(ps);
23302        }
23303
23304        final UserManager um = mContext.getSystemService(UserManager.class);
23305        UserManagerInternal umInternal = getUserManagerInternal();
23306        for (UserInfo user : um.getUsers()) {
23307            final int flags;
23308            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23309                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23310            } else if (umInternal.isUserRunning(user.id)) {
23311                flags = StorageManager.FLAG_STORAGE_DE;
23312            } else {
23313                continue;
23314            }
23315
23316            if (ps.getInstalled(user.id)) {
23317                // TODO: when user data is locked, mark that we're still dirty
23318                prepareAppDataLIF(pkg, user.id, flags);
23319            }
23320        }
23321    }
23322
23323    /**
23324     * Prepare app data for the given app.
23325     * <p>
23326     * Verifies that directories exist and that ownership and labeling is
23327     * correct for all installed apps. If there is an ownership mismatch, this
23328     * will try recovering system apps by wiping data; third-party app data is
23329     * left intact.
23330     */
23331    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23332        if (pkg == null) {
23333            Slog.wtf(TAG, "Package was null!", new Throwable());
23334            return;
23335        }
23336        prepareAppDataLeafLIF(pkg, userId, flags);
23337        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23338        for (int i = 0; i < childCount; i++) {
23339            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23340        }
23341    }
23342
23343    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23344            boolean maybeMigrateAppData) {
23345        prepareAppDataLIF(pkg, userId, flags);
23346
23347        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23348            // We may have just shuffled around app data directories, so
23349            // prepare them one more time
23350            prepareAppDataLIF(pkg, userId, flags);
23351        }
23352    }
23353
23354    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23355        if (DEBUG_APP_DATA) {
23356            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23357                    + Integer.toHexString(flags));
23358        }
23359
23360        final String volumeUuid = pkg.volumeUuid;
23361        final String packageName = pkg.packageName;
23362        final ApplicationInfo app = pkg.applicationInfo;
23363        final int appId = UserHandle.getAppId(app.uid);
23364
23365        Preconditions.checkNotNull(app.seInfo);
23366
23367        long ceDataInode = -1;
23368        try {
23369            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23370                    appId, app.seInfo, app.targetSdkVersion);
23371        } catch (InstallerException e) {
23372            if (app.isSystemApp()) {
23373                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23374                        + ", but trying to recover: " + e);
23375                destroyAppDataLeafLIF(pkg, userId, flags);
23376                try {
23377                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23378                            appId, app.seInfo, app.targetSdkVersion);
23379                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23380                } catch (InstallerException e2) {
23381                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23382                }
23383            } else {
23384                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23385            }
23386        }
23387
23388        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23389            // TODO: mark this structure as dirty so we persist it!
23390            synchronized (mPackages) {
23391                final PackageSetting ps = mSettings.mPackages.get(packageName);
23392                if (ps != null) {
23393                    ps.setCeDataInode(ceDataInode, userId);
23394                }
23395            }
23396        }
23397
23398        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23399    }
23400
23401    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23402        if (pkg == null) {
23403            Slog.wtf(TAG, "Package was null!", new Throwable());
23404            return;
23405        }
23406        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23407        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23408        for (int i = 0; i < childCount; i++) {
23409            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23410        }
23411    }
23412
23413    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23414        final String volumeUuid = pkg.volumeUuid;
23415        final String packageName = pkg.packageName;
23416        final ApplicationInfo app = pkg.applicationInfo;
23417
23418        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23419            // Create a native library symlink only if we have native libraries
23420            // and if the native libraries are 32 bit libraries. We do not provide
23421            // this symlink for 64 bit libraries.
23422            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23423                final String nativeLibPath = app.nativeLibraryDir;
23424                try {
23425                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23426                            nativeLibPath, userId);
23427                } catch (InstallerException e) {
23428                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23429                }
23430            }
23431        }
23432    }
23433
23434    /**
23435     * For system apps on non-FBE devices, this method migrates any existing
23436     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23437     * requested by the app.
23438     */
23439    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23440        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23441                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23442            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23443                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23444            try {
23445                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23446                        storageTarget);
23447            } catch (InstallerException e) {
23448                logCriticalInfo(Log.WARN,
23449                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23450            }
23451            return true;
23452        } else {
23453            return false;
23454        }
23455    }
23456
23457    public PackageFreezer freezePackage(String packageName, String killReason) {
23458        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23459    }
23460
23461    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23462        return new PackageFreezer(packageName, userId, killReason);
23463    }
23464
23465    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23466            String killReason) {
23467        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23468    }
23469
23470    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23471            String killReason) {
23472        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23473            return new PackageFreezer();
23474        } else {
23475            return freezePackage(packageName, userId, killReason);
23476        }
23477    }
23478
23479    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23480            String killReason) {
23481        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23482    }
23483
23484    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23485            String killReason) {
23486        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23487            return new PackageFreezer();
23488        } else {
23489            return freezePackage(packageName, userId, killReason);
23490        }
23491    }
23492
23493    /**
23494     * Class that freezes and kills the given package upon creation, and
23495     * unfreezes it upon closing. This is typically used when doing surgery on
23496     * app code/data to prevent the app from running while you're working.
23497     */
23498    private class PackageFreezer implements AutoCloseable {
23499        private final String mPackageName;
23500        private final PackageFreezer[] mChildren;
23501
23502        private final boolean mWeFroze;
23503
23504        private final AtomicBoolean mClosed = new AtomicBoolean();
23505        private final CloseGuard mCloseGuard = CloseGuard.get();
23506
23507        /**
23508         * Create and return a stub freezer that doesn't actually do anything,
23509         * typically used when someone requested
23510         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23511         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23512         */
23513        public PackageFreezer() {
23514            mPackageName = null;
23515            mChildren = null;
23516            mWeFroze = false;
23517            mCloseGuard.open("close");
23518        }
23519
23520        public PackageFreezer(String packageName, int userId, String killReason) {
23521            synchronized (mPackages) {
23522                mPackageName = packageName;
23523                mWeFroze = mFrozenPackages.add(mPackageName);
23524
23525                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23526                if (ps != null) {
23527                    killApplication(ps.name, ps.appId, userId, killReason);
23528                }
23529
23530                final PackageParser.Package p = mPackages.get(packageName);
23531                if (p != null && p.childPackages != null) {
23532                    final int N = p.childPackages.size();
23533                    mChildren = new PackageFreezer[N];
23534                    for (int i = 0; i < N; i++) {
23535                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23536                                userId, killReason);
23537                    }
23538                } else {
23539                    mChildren = null;
23540                }
23541            }
23542            mCloseGuard.open("close");
23543        }
23544
23545        @Override
23546        protected void finalize() throws Throwable {
23547            try {
23548                if (mCloseGuard != null) {
23549                    mCloseGuard.warnIfOpen();
23550                }
23551
23552                close();
23553            } finally {
23554                super.finalize();
23555            }
23556        }
23557
23558        @Override
23559        public void close() {
23560            mCloseGuard.close();
23561            if (mClosed.compareAndSet(false, true)) {
23562                synchronized (mPackages) {
23563                    if (mWeFroze) {
23564                        mFrozenPackages.remove(mPackageName);
23565                    }
23566
23567                    if (mChildren != null) {
23568                        for (PackageFreezer freezer : mChildren) {
23569                            freezer.close();
23570                        }
23571                    }
23572                }
23573            }
23574        }
23575    }
23576
23577    /**
23578     * Verify that given package is currently frozen.
23579     */
23580    private void checkPackageFrozen(String packageName) {
23581        synchronized (mPackages) {
23582            if (!mFrozenPackages.contains(packageName)) {
23583                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23584            }
23585        }
23586    }
23587
23588    @Override
23589    public int movePackage(final String packageName, final String volumeUuid) {
23590        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23591
23592        final int callingUid = Binder.getCallingUid();
23593        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23594        final int moveId = mNextMoveId.getAndIncrement();
23595        mHandler.post(new Runnable() {
23596            @Override
23597            public void run() {
23598                try {
23599                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23600                } catch (PackageManagerException e) {
23601                    Slog.w(TAG, "Failed to move " + packageName, e);
23602                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23603                }
23604            }
23605        });
23606        return moveId;
23607    }
23608
23609    private void movePackageInternal(final String packageName, final String volumeUuid,
23610            final int moveId, final int callingUid, UserHandle user)
23611                    throws PackageManagerException {
23612        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23613        final PackageManager pm = mContext.getPackageManager();
23614
23615        final boolean currentAsec;
23616        final String currentVolumeUuid;
23617        final File codeFile;
23618        final String installerPackageName;
23619        final String packageAbiOverride;
23620        final int appId;
23621        final String seinfo;
23622        final String label;
23623        final int targetSdkVersion;
23624        final PackageFreezer freezer;
23625        final int[] installedUserIds;
23626
23627        // reader
23628        synchronized (mPackages) {
23629            final PackageParser.Package pkg = mPackages.get(packageName);
23630            final PackageSetting ps = mSettings.mPackages.get(packageName);
23631            if (pkg == null
23632                    || ps == null
23633                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23634                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23635            }
23636            if (pkg.applicationInfo.isSystemApp()) {
23637                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23638                        "Cannot move system application");
23639            }
23640
23641            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23642            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23643                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23644            if (isInternalStorage && !allow3rdPartyOnInternal) {
23645                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23646                        "3rd party apps are not allowed on internal storage");
23647            }
23648
23649            if (pkg.applicationInfo.isExternalAsec()) {
23650                currentAsec = true;
23651                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23652            } else if (pkg.applicationInfo.isForwardLocked()) {
23653                currentAsec = true;
23654                currentVolumeUuid = "forward_locked";
23655            } else {
23656                currentAsec = false;
23657                currentVolumeUuid = ps.volumeUuid;
23658
23659                final File probe = new File(pkg.codePath);
23660                final File probeOat = new File(probe, "oat");
23661                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23662                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23663                            "Move only supported for modern cluster style installs");
23664                }
23665            }
23666
23667            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23668                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23669                        "Package already moved to " + volumeUuid);
23670            }
23671            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23672                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23673                        "Device admin cannot be moved");
23674            }
23675
23676            if (mFrozenPackages.contains(packageName)) {
23677                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23678                        "Failed to move already frozen package");
23679            }
23680
23681            codeFile = new File(pkg.codePath);
23682            installerPackageName = ps.installerPackageName;
23683            packageAbiOverride = ps.cpuAbiOverrideString;
23684            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23685            seinfo = pkg.applicationInfo.seInfo;
23686            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23687            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23688            freezer = freezePackage(packageName, "movePackageInternal");
23689            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23690        }
23691
23692        final Bundle extras = new Bundle();
23693        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23694        extras.putString(Intent.EXTRA_TITLE, label);
23695        mMoveCallbacks.notifyCreated(moveId, extras);
23696
23697        int installFlags;
23698        final boolean moveCompleteApp;
23699        final File measurePath;
23700
23701        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23702            installFlags = INSTALL_INTERNAL;
23703            moveCompleteApp = !currentAsec;
23704            measurePath = Environment.getDataAppDirectory(volumeUuid);
23705        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23706            installFlags = INSTALL_EXTERNAL;
23707            moveCompleteApp = false;
23708            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23709        } else {
23710            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23711            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23712                    || !volume.isMountedWritable()) {
23713                freezer.close();
23714                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23715                        "Move location not mounted private volume");
23716            }
23717
23718            Preconditions.checkState(!currentAsec);
23719
23720            installFlags = INSTALL_INTERNAL;
23721            moveCompleteApp = true;
23722            measurePath = Environment.getDataAppDirectory(volumeUuid);
23723        }
23724
23725        // If we're moving app data around, we need all the users unlocked
23726        if (moveCompleteApp) {
23727            for (int userId : installedUserIds) {
23728                if (StorageManager.isFileEncryptedNativeOrEmulated()
23729                        && !StorageManager.isUserKeyUnlocked(userId)) {
23730                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23731                            "User " + userId + " must be unlocked");
23732                }
23733            }
23734        }
23735
23736        final PackageStats stats = new PackageStats(null, -1);
23737        synchronized (mInstaller) {
23738            for (int userId : installedUserIds) {
23739                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23740                    freezer.close();
23741                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23742                            "Failed to measure package size");
23743                }
23744            }
23745        }
23746
23747        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23748                + stats.dataSize);
23749
23750        final long startFreeBytes = measurePath.getUsableSpace();
23751        final long sizeBytes;
23752        if (moveCompleteApp) {
23753            sizeBytes = stats.codeSize + stats.dataSize;
23754        } else {
23755            sizeBytes = stats.codeSize;
23756        }
23757
23758        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23759            freezer.close();
23760            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23761                    "Not enough free space to move");
23762        }
23763
23764        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23765
23766        final CountDownLatch installedLatch = new CountDownLatch(1);
23767        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23768            @Override
23769            public void onUserActionRequired(Intent intent) throws RemoteException {
23770                throw new IllegalStateException();
23771            }
23772
23773            @Override
23774            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23775                    Bundle extras) throws RemoteException {
23776                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23777                        + PackageManager.installStatusToString(returnCode, msg));
23778
23779                installedLatch.countDown();
23780                freezer.close();
23781
23782                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23783                switch (status) {
23784                    case PackageInstaller.STATUS_SUCCESS:
23785                        mMoveCallbacks.notifyStatusChanged(moveId,
23786                                PackageManager.MOVE_SUCCEEDED);
23787                        break;
23788                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23789                        mMoveCallbacks.notifyStatusChanged(moveId,
23790                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23791                        break;
23792                    default:
23793                        mMoveCallbacks.notifyStatusChanged(moveId,
23794                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23795                        break;
23796                }
23797            }
23798        };
23799
23800        final MoveInfo move;
23801        if (moveCompleteApp) {
23802            // Kick off a thread to report progress estimates
23803            new Thread() {
23804                @Override
23805                public void run() {
23806                    while (true) {
23807                        try {
23808                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23809                                break;
23810                            }
23811                        } catch (InterruptedException ignored) {
23812                        }
23813
23814                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23815                        final int progress = 10 + (int) MathUtils.constrain(
23816                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23817                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23818                    }
23819                }
23820            }.start();
23821
23822            final String dataAppName = codeFile.getName();
23823            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23824                    dataAppName, appId, seinfo, targetSdkVersion);
23825        } else {
23826            move = null;
23827        }
23828
23829        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23830
23831        final Message msg = mHandler.obtainMessage(INIT_COPY);
23832        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23833        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23834                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23835                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23836                PackageManager.INSTALL_REASON_UNKNOWN);
23837        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23838        msg.obj = params;
23839
23840        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23841                System.identityHashCode(msg.obj));
23842        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23843                System.identityHashCode(msg.obj));
23844
23845        mHandler.sendMessage(msg);
23846    }
23847
23848    @Override
23849    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23850        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23851
23852        final int realMoveId = mNextMoveId.getAndIncrement();
23853        final Bundle extras = new Bundle();
23854        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23855        mMoveCallbacks.notifyCreated(realMoveId, extras);
23856
23857        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23858            @Override
23859            public void onCreated(int moveId, Bundle extras) {
23860                // Ignored
23861            }
23862
23863            @Override
23864            public void onStatusChanged(int moveId, int status, long estMillis) {
23865                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23866            }
23867        };
23868
23869        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23870        storage.setPrimaryStorageUuid(volumeUuid, callback);
23871        return realMoveId;
23872    }
23873
23874    @Override
23875    public int getMoveStatus(int moveId) {
23876        mContext.enforceCallingOrSelfPermission(
23877                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23878        return mMoveCallbacks.mLastStatus.get(moveId);
23879    }
23880
23881    @Override
23882    public void registerMoveCallback(IPackageMoveObserver callback) {
23883        mContext.enforceCallingOrSelfPermission(
23884                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23885        mMoveCallbacks.register(callback);
23886    }
23887
23888    @Override
23889    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23890        mContext.enforceCallingOrSelfPermission(
23891                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23892        mMoveCallbacks.unregister(callback);
23893    }
23894
23895    @Override
23896    public boolean setInstallLocation(int loc) {
23897        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23898                null);
23899        if (getInstallLocation() == loc) {
23900            return true;
23901        }
23902        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23903                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23904            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23905                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23906            return true;
23907        }
23908        return false;
23909   }
23910
23911    @Override
23912    public int getInstallLocation() {
23913        // allow instant app access
23914        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23915                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23916                PackageHelper.APP_INSTALL_AUTO);
23917    }
23918
23919    /** Called by UserManagerService */
23920    void cleanUpUser(UserManagerService userManager, int userHandle) {
23921        synchronized (mPackages) {
23922            mDirtyUsers.remove(userHandle);
23923            mUserNeedsBadging.delete(userHandle);
23924            mSettings.removeUserLPw(userHandle);
23925            mPendingBroadcasts.remove(userHandle);
23926            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23927            removeUnusedPackagesLPw(userManager, userHandle);
23928        }
23929    }
23930
23931    /**
23932     * We're removing userHandle and would like to remove any downloaded packages
23933     * that are no longer in use by any other user.
23934     * @param userHandle the user being removed
23935     */
23936    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23937        final boolean DEBUG_CLEAN_APKS = false;
23938        int [] users = userManager.getUserIds();
23939        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23940        while (psit.hasNext()) {
23941            PackageSetting ps = psit.next();
23942            if (ps.pkg == null) {
23943                continue;
23944            }
23945            final String packageName = ps.pkg.packageName;
23946            // Skip over if system app
23947            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23948                continue;
23949            }
23950            if (DEBUG_CLEAN_APKS) {
23951                Slog.i(TAG, "Checking package " + packageName);
23952            }
23953            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23954            if (keep) {
23955                if (DEBUG_CLEAN_APKS) {
23956                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23957                }
23958            } else {
23959                for (int i = 0; i < users.length; i++) {
23960                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23961                        keep = true;
23962                        if (DEBUG_CLEAN_APKS) {
23963                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23964                                    + users[i]);
23965                        }
23966                        break;
23967                    }
23968                }
23969            }
23970            if (!keep) {
23971                if (DEBUG_CLEAN_APKS) {
23972                    Slog.i(TAG, "  Removing package " + packageName);
23973                }
23974                mHandler.post(new Runnable() {
23975                    public void run() {
23976                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23977                                userHandle, 0);
23978                    } //end run
23979                });
23980            }
23981        }
23982    }
23983
23984    /** Called by UserManagerService */
23985    void createNewUser(int userId, String[] disallowedPackages) {
23986        synchronized (mInstallLock) {
23987            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23988        }
23989        synchronized (mPackages) {
23990            scheduleWritePackageRestrictionsLocked(userId);
23991            scheduleWritePackageListLocked(userId);
23992            applyFactoryDefaultBrowserLPw(userId);
23993            primeDomainVerificationsLPw(userId);
23994        }
23995    }
23996
23997    void onNewUserCreated(final int userId) {
23998        synchronized(mPackages) {
23999            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
24000        }
24001        // If permission review for legacy apps is required, we represent
24002        // dagerous permissions for such apps as always granted runtime
24003        // permissions to keep per user flag state whether review is needed.
24004        // Hence, if a new user is added we have to propagate dangerous
24005        // permission grants for these legacy apps.
24006        if (mPermissionReviewRequired) {
24007            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24008                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24009        }
24010    }
24011
24012    @Override
24013    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24014        mContext.enforceCallingOrSelfPermission(
24015                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24016                "Only package verification agents can read the verifier device identity");
24017
24018        synchronized (mPackages) {
24019            return mSettings.getVerifierDeviceIdentityLPw();
24020        }
24021    }
24022
24023    @Override
24024    public void setPermissionEnforced(String permission, boolean enforced) {
24025        // TODO: Now that we no longer change GID for storage, this should to away.
24026        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24027                "setPermissionEnforced");
24028        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24029            synchronized (mPackages) {
24030                if (mSettings.mReadExternalStorageEnforced == null
24031                        || mSettings.mReadExternalStorageEnforced != enforced) {
24032                    mSettings.mReadExternalStorageEnforced =
24033                            enforced ? Boolean.TRUE : Boolean.FALSE;
24034                    mSettings.writeLPr();
24035                }
24036            }
24037            // kill any non-foreground processes so we restart them and
24038            // grant/revoke the GID.
24039            final IActivityManager am = ActivityManager.getService();
24040            if (am != null) {
24041                final long token = Binder.clearCallingIdentity();
24042                try {
24043                    am.killProcessesBelowForeground("setPermissionEnforcement");
24044                } catch (RemoteException e) {
24045                } finally {
24046                    Binder.restoreCallingIdentity(token);
24047                }
24048            }
24049        } else {
24050            throw new IllegalArgumentException("No selective enforcement for " + permission);
24051        }
24052    }
24053
24054    @Override
24055    @Deprecated
24056    public boolean isPermissionEnforced(String permission) {
24057        // allow instant applications
24058        return true;
24059    }
24060
24061    @Override
24062    public boolean isStorageLow() {
24063        // allow instant applications
24064        final long token = Binder.clearCallingIdentity();
24065        try {
24066            final DeviceStorageMonitorInternal
24067                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24068            if (dsm != null) {
24069                return dsm.isMemoryLow();
24070            } else {
24071                return false;
24072            }
24073        } finally {
24074            Binder.restoreCallingIdentity(token);
24075        }
24076    }
24077
24078    @Override
24079    public IPackageInstaller getPackageInstaller() {
24080        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24081            return null;
24082        }
24083        return mInstallerService;
24084    }
24085
24086    private boolean userNeedsBadging(int userId) {
24087        int index = mUserNeedsBadging.indexOfKey(userId);
24088        if (index < 0) {
24089            final UserInfo userInfo;
24090            final long token = Binder.clearCallingIdentity();
24091            try {
24092                userInfo = sUserManager.getUserInfo(userId);
24093            } finally {
24094                Binder.restoreCallingIdentity(token);
24095            }
24096            final boolean b;
24097            if (userInfo != null && userInfo.isManagedProfile()) {
24098                b = true;
24099            } else {
24100                b = false;
24101            }
24102            mUserNeedsBadging.put(userId, b);
24103            return b;
24104        }
24105        return mUserNeedsBadging.valueAt(index);
24106    }
24107
24108    @Override
24109    public KeySet getKeySetByAlias(String packageName, String alias) {
24110        if (packageName == null || alias == null) {
24111            return null;
24112        }
24113        synchronized(mPackages) {
24114            final PackageParser.Package pkg = mPackages.get(packageName);
24115            if (pkg == null) {
24116                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24117                throw new IllegalArgumentException("Unknown package: " + packageName);
24118            }
24119            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24120            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24121                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24122                throw new IllegalArgumentException("Unknown package: " + packageName);
24123            }
24124            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24125            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24126        }
24127    }
24128
24129    @Override
24130    public KeySet getSigningKeySet(String packageName) {
24131        if (packageName == null) {
24132            return null;
24133        }
24134        synchronized(mPackages) {
24135            final int callingUid = Binder.getCallingUid();
24136            final int callingUserId = UserHandle.getUserId(callingUid);
24137            final PackageParser.Package pkg = mPackages.get(packageName);
24138            if (pkg == null) {
24139                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24140                throw new IllegalArgumentException("Unknown package: " + packageName);
24141            }
24142            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24143            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24144                // filter and pretend the package doesn't exist
24145                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24146                        + ", uid:" + callingUid);
24147                throw new IllegalArgumentException("Unknown package: " + packageName);
24148            }
24149            if (pkg.applicationInfo.uid != callingUid
24150                    && Process.SYSTEM_UID != callingUid) {
24151                throw new SecurityException("May not access signing KeySet of other apps.");
24152            }
24153            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24154            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24155        }
24156    }
24157
24158    @Override
24159    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24160        final int callingUid = Binder.getCallingUid();
24161        if (getInstantAppPackageName(callingUid) != null) {
24162            return false;
24163        }
24164        if (packageName == null || ks == null) {
24165            return false;
24166        }
24167        synchronized(mPackages) {
24168            final PackageParser.Package pkg = mPackages.get(packageName);
24169            if (pkg == null
24170                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24171                            UserHandle.getUserId(callingUid))) {
24172                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24173                throw new IllegalArgumentException("Unknown package: " + packageName);
24174            }
24175            IBinder ksh = ks.getToken();
24176            if (ksh instanceof KeySetHandle) {
24177                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24178                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24179            }
24180            return false;
24181        }
24182    }
24183
24184    @Override
24185    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24186        final int callingUid = Binder.getCallingUid();
24187        if (getInstantAppPackageName(callingUid) != null) {
24188            return false;
24189        }
24190        if (packageName == null || ks == null) {
24191            return false;
24192        }
24193        synchronized(mPackages) {
24194            final PackageParser.Package pkg = mPackages.get(packageName);
24195            if (pkg == null
24196                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24197                            UserHandle.getUserId(callingUid))) {
24198                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24199                throw new IllegalArgumentException("Unknown package: " + packageName);
24200            }
24201            IBinder ksh = ks.getToken();
24202            if (ksh instanceof KeySetHandle) {
24203                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24204                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24205            }
24206            return false;
24207        }
24208    }
24209
24210    private void deletePackageIfUnusedLPr(final String packageName) {
24211        PackageSetting ps = mSettings.mPackages.get(packageName);
24212        if (ps == null) {
24213            return;
24214        }
24215        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24216            // TODO Implement atomic delete if package is unused
24217            // It is currently possible that the package will be deleted even if it is installed
24218            // after this method returns.
24219            mHandler.post(new Runnable() {
24220                public void run() {
24221                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24222                            0, PackageManager.DELETE_ALL_USERS);
24223                }
24224            });
24225        }
24226    }
24227
24228    /**
24229     * Check and throw if the given before/after packages would be considered a
24230     * downgrade.
24231     */
24232    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24233            throws PackageManagerException {
24234        if (after.versionCode < before.mVersionCode) {
24235            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24236                    "Update version code " + after.versionCode + " is older than current "
24237                    + before.mVersionCode);
24238        } else if (after.versionCode == before.mVersionCode) {
24239            if (after.baseRevisionCode < before.baseRevisionCode) {
24240                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24241                        "Update base revision code " + after.baseRevisionCode
24242                        + " is older than current " + before.baseRevisionCode);
24243            }
24244
24245            if (!ArrayUtils.isEmpty(after.splitNames)) {
24246                for (int i = 0; i < after.splitNames.length; i++) {
24247                    final String splitName = after.splitNames[i];
24248                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24249                    if (j != -1) {
24250                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24251                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24252                                    "Update split " + splitName + " revision code "
24253                                    + after.splitRevisionCodes[i] + " is older than current "
24254                                    + before.splitRevisionCodes[j]);
24255                        }
24256                    }
24257                }
24258            }
24259        }
24260    }
24261
24262    private static class MoveCallbacks extends Handler {
24263        private static final int MSG_CREATED = 1;
24264        private static final int MSG_STATUS_CHANGED = 2;
24265
24266        private final RemoteCallbackList<IPackageMoveObserver>
24267                mCallbacks = new RemoteCallbackList<>();
24268
24269        private final SparseIntArray mLastStatus = new SparseIntArray();
24270
24271        public MoveCallbacks(Looper looper) {
24272            super(looper);
24273        }
24274
24275        public void register(IPackageMoveObserver callback) {
24276            mCallbacks.register(callback);
24277        }
24278
24279        public void unregister(IPackageMoveObserver callback) {
24280            mCallbacks.unregister(callback);
24281        }
24282
24283        @Override
24284        public void handleMessage(Message msg) {
24285            final SomeArgs args = (SomeArgs) msg.obj;
24286            final int n = mCallbacks.beginBroadcast();
24287            for (int i = 0; i < n; i++) {
24288                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24289                try {
24290                    invokeCallback(callback, msg.what, args);
24291                } catch (RemoteException ignored) {
24292                }
24293            }
24294            mCallbacks.finishBroadcast();
24295            args.recycle();
24296        }
24297
24298        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24299                throws RemoteException {
24300            switch (what) {
24301                case MSG_CREATED: {
24302                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24303                    break;
24304                }
24305                case MSG_STATUS_CHANGED: {
24306                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24307                    break;
24308                }
24309            }
24310        }
24311
24312        private void notifyCreated(int moveId, Bundle extras) {
24313            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24314
24315            final SomeArgs args = SomeArgs.obtain();
24316            args.argi1 = moveId;
24317            args.arg2 = extras;
24318            obtainMessage(MSG_CREATED, args).sendToTarget();
24319        }
24320
24321        private void notifyStatusChanged(int moveId, int status) {
24322            notifyStatusChanged(moveId, status, -1);
24323        }
24324
24325        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24326            Slog.v(TAG, "Move " + moveId + " status " + status);
24327
24328            final SomeArgs args = SomeArgs.obtain();
24329            args.argi1 = moveId;
24330            args.argi2 = status;
24331            args.arg3 = estMillis;
24332            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24333
24334            synchronized (mLastStatus) {
24335                mLastStatus.put(moveId, status);
24336            }
24337        }
24338    }
24339
24340    private final static class OnPermissionChangeListeners extends Handler {
24341        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24342
24343        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24344                new RemoteCallbackList<>();
24345
24346        public OnPermissionChangeListeners(Looper looper) {
24347            super(looper);
24348        }
24349
24350        @Override
24351        public void handleMessage(Message msg) {
24352            switch (msg.what) {
24353                case MSG_ON_PERMISSIONS_CHANGED: {
24354                    final int uid = msg.arg1;
24355                    handleOnPermissionsChanged(uid);
24356                } break;
24357            }
24358        }
24359
24360        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24361            mPermissionListeners.register(listener);
24362
24363        }
24364
24365        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24366            mPermissionListeners.unregister(listener);
24367        }
24368
24369        public void onPermissionsChanged(int uid) {
24370            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24371                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24372            }
24373        }
24374
24375        private void handleOnPermissionsChanged(int uid) {
24376            final int count = mPermissionListeners.beginBroadcast();
24377            try {
24378                for (int i = 0; i < count; i++) {
24379                    IOnPermissionsChangeListener callback = mPermissionListeners
24380                            .getBroadcastItem(i);
24381                    try {
24382                        callback.onPermissionsChanged(uid);
24383                    } catch (RemoteException e) {
24384                        Log.e(TAG, "Permission listener is dead", e);
24385                    }
24386                }
24387            } finally {
24388                mPermissionListeners.finishBroadcast();
24389            }
24390        }
24391    }
24392
24393    private class PackageManagerNative extends IPackageManagerNative.Stub {
24394        @Override
24395        public String[] getNamesForUids(int[] uids) throws RemoteException {
24396            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24397            // massage results so they can be parsed by the native binder
24398            for (int i = results.length - 1; i >= 0; --i) {
24399                if (results[i] == null) {
24400                    results[i] = "";
24401                }
24402            }
24403            return results;
24404        }
24405
24406        // NB: this differentiates between preloads and sideloads
24407        @Override
24408        public String getInstallerForPackage(String packageName) throws RemoteException {
24409            final String installerName = getInstallerPackageName(packageName);
24410            if (!TextUtils.isEmpty(installerName)) {
24411                return installerName;
24412            }
24413            // differentiate between preload and sideload
24414            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24415            ApplicationInfo appInfo = getApplicationInfo(packageName,
24416                                    /*flags*/ 0,
24417                                    /*userId*/ callingUser);
24418            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24419                return "preload";
24420            }
24421            return "";
24422        }
24423
24424        @Override
24425        public int getVersionCodeForPackage(String packageName) throws RemoteException {
24426            try {
24427                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24428                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
24429                if (pInfo != null) {
24430                    return pInfo.versionCode;
24431                }
24432            } catch (Exception e) {
24433            }
24434            return 0;
24435        }
24436    }
24437
24438    private class PackageManagerInternalImpl extends PackageManagerInternal {
24439        @Override
24440        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
24441                int flagValues, int userId) {
24442            PackageManagerService.this.updatePermissionFlags(
24443                    permName, packageName, flagMask, flagValues, userId);
24444        }
24445
24446        @Override
24447        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
24448            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
24449        }
24450
24451        @Override
24452        public Object enforcePermissionTreeTEMP(String permName, int callingUid) {
24453            synchronized (mPackages) {
24454                return BasePermission.enforcePermissionTreeLP(
24455                        mSettings.mPermissionTrees, permName, callingUid);
24456            }
24457        }
24458        @Override
24459        public boolean isInstantApp(String packageName, int userId) {
24460            return PackageManagerService.this.isInstantApp(packageName, userId);
24461        }
24462
24463        @Override
24464        public String getInstantAppPackageName(int uid) {
24465            return PackageManagerService.this.getInstantAppPackageName(uid);
24466        }
24467
24468        @Override
24469        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
24470            synchronized (mPackages) {
24471                return PackageManagerService.this.filterAppAccessLPr(
24472                        (PackageSetting) pkg.mExtras, callingUid, userId);
24473            }
24474        }
24475
24476        @Override
24477        public PackageParser.Package getPackage(String packageName) {
24478            synchronized (mPackages) {
24479                packageName = resolveInternalPackageNameLPr(
24480                        packageName, PackageManager.VERSION_CODE_HIGHEST);
24481                return mPackages.get(packageName);
24482            }
24483        }
24484
24485        @Override
24486        public PackageParser.Package getDisabledPackage(String packageName) {
24487            synchronized (mPackages) {
24488                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
24489                return (ps != null) ? ps.pkg : null;
24490            }
24491        }
24492
24493        @Override
24494        public String getKnownPackageName(int knownPackage, int userId) {
24495            switch(knownPackage) {
24496                case PackageManagerInternal.PACKAGE_BROWSER:
24497                    return getDefaultBrowserPackageName(userId);
24498                case PackageManagerInternal.PACKAGE_INSTALLER:
24499                    return mRequiredInstallerPackage;
24500                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
24501                    return mSetupWizardPackage;
24502                case PackageManagerInternal.PACKAGE_SYSTEM:
24503                    return "android";
24504                case PackageManagerInternal.PACKAGE_VERIFIER:
24505                    return mRequiredVerifierPackage;
24506            }
24507            return null;
24508        }
24509
24510        @Override
24511        public boolean isResolveActivityComponent(ComponentInfo component) {
24512            return mResolveActivity.packageName.equals(component.packageName)
24513                    && mResolveActivity.name.equals(component.name);
24514        }
24515
24516        @Override
24517        public void setLocationPackagesProvider(PackagesProvider provider) {
24518            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
24519        }
24520
24521        @Override
24522        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24523            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
24524        }
24525
24526        @Override
24527        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24528            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
24529        }
24530
24531        @Override
24532        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24533            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
24534        }
24535
24536        @Override
24537        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24538            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
24539        }
24540
24541        @Override
24542        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24543            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
24544        }
24545
24546        @Override
24547        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24548            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
24549        }
24550
24551        @Override
24552        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24553            synchronized (mPackages) {
24554                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24555            }
24556            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
24557        }
24558
24559        @Override
24560        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24561            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
24562                    packageName, userId);
24563        }
24564
24565        @Override
24566        public void setKeepUninstalledPackages(final List<String> packageList) {
24567            Preconditions.checkNotNull(packageList);
24568            List<String> removedFromList = null;
24569            synchronized (mPackages) {
24570                if (mKeepUninstalledPackages != null) {
24571                    final int packagesCount = mKeepUninstalledPackages.size();
24572                    for (int i = 0; i < packagesCount; i++) {
24573                        String oldPackage = mKeepUninstalledPackages.get(i);
24574                        if (packageList != null && packageList.contains(oldPackage)) {
24575                            continue;
24576                        }
24577                        if (removedFromList == null) {
24578                            removedFromList = new ArrayList<>();
24579                        }
24580                        removedFromList.add(oldPackage);
24581                    }
24582                }
24583                mKeepUninstalledPackages = new ArrayList<>(packageList);
24584                if (removedFromList != null) {
24585                    final int removedCount = removedFromList.size();
24586                    for (int i = 0; i < removedCount; i++) {
24587                        deletePackageIfUnusedLPr(removedFromList.get(i));
24588                    }
24589                }
24590            }
24591        }
24592
24593        @Override
24594        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24595            synchronized (mPackages) {
24596                // If we do not support permission review, done.
24597                if (!mPermissionReviewRequired) {
24598                    return false;
24599                }
24600
24601                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24602                if (packageSetting == null) {
24603                    return false;
24604                }
24605
24606                // Permission review applies only to apps not supporting the new permission model.
24607                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24608                    return false;
24609                }
24610
24611                // Legacy apps have the permission and get user consent on launch.
24612                PermissionsState permissionsState = packageSetting.getPermissionsState();
24613                return permissionsState.isPermissionReviewRequired(userId);
24614            }
24615        }
24616
24617        @Override
24618        public PackageInfo getPackageInfo(
24619                String packageName, int flags, int filterCallingUid, int userId) {
24620            return PackageManagerService.this
24621                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24622                            flags, filterCallingUid, userId);
24623        }
24624
24625        @Override
24626        public ApplicationInfo getApplicationInfo(
24627                String packageName, int flags, int filterCallingUid, int userId) {
24628            return PackageManagerService.this
24629                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24630        }
24631
24632        @Override
24633        public ActivityInfo getActivityInfo(
24634                ComponentName component, int flags, int filterCallingUid, int userId) {
24635            return PackageManagerService.this
24636                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24637        }
24638
24639        @Override
24640        public List<ResolveInfo> queryIntentActivities(
24641                Intent intent, int flags, int filterCallingUid, int userId) {
24642            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24643            return PackageManagerService.this
24644                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24645                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24646        }
24647
24648        @Override
24649        public List<ResolveInfo> queryIntentServices(
24650                Intent intent, int flags, int callingUid, int userId) {
24651            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24652            return PackageManagerService.this
24653                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
24654                            false);
24655        }
24656
24657        @Override
24658        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24659                int userId) {
24660            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24661        }
24662
24663        @Override
24664        public void setDeviceAndProfileOwnerPackages(
24665                int deviceOwnerUserId, String deviceOwnerPackage,
24666                SparseArray<String> profileOwnerPackages) {
24667            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24668                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24669        }
24670
24671        @Override
24672        public boolean isPackageDataProtected(int userId, String packageName) {
24673            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24674        }
24675
24676        @Override
24677        public boolean isPackageEphemeral(int userId, String packageName) {
24678            synchronized (mPackages) {
24679                final PackageSetting ps = mSettings.mPackages.get(packageName);
24680                return ps != null ? ps.getInstantApp(userId) : false;
24681            }
24682        }
24683
24684        @Override
24685        public boolean wasPackageEverLaunched(String packageName, int userId) {
24686            synchronized (mPackages) {
24687                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24688            }
24689        }
24690
24691        @Override
24692        public void grantRuntimePermission(String packageName, String permName, int userId,
24693                boolean overridePolicy) {
24694            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24695                    permName, packageName, overridePolicy, getCallingUid(), userId,
24696                    mPermissionCallback);
24697        }
24698
24699        @Override
24700        public void revokeRuntimePermission(String packageName, String permName, int userId,
24701                boolean overridePolicy) {
24702            mPermissionManager.revokeRuntimePermission(
24703                    permName, packageName, overridePolicy, getCallingUid(), userId,
24704                    mPermissionCallback);
24705        }
24706
24707        @Override
24708        public String getNameForUid(int uid) {
24709            return PackageManagerService.this.getNameForUid(uid);
24710        }
24711
24712        @Override
24713        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24714                Intent origIntent, String resolvedType, String callingPackage,
24715                Bundle verificationBundle, int userId) {
24716            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24717                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24718                    userId);
24719        }
24720
24721        @Override
24722        public void grantEphemeralAccess(int userId, Intent intent,
24723                int targetAppId, int ephemeralAppId) {
24724            synchronized (mPackages) {
24725                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24726                        targetAppId, ephemeralAppId);
24727            }
24728        }
24729
24730        @Override
24731        public boolean isInstantAppInstallerComponent(ComponentName component) {
24732            synchronized (mPackages) {
24733                return mInstantAppInstallerActivity != null
24734                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24735            }
24736        }
24737
24738        @Override
24739        public void pruneInstantApps() {
24740            mInstantAppRegistry.pruneInstantApps();
24741        }
24742
24743        @Override
24744        public String getSetupWizardPackageName() {
24745            return mSetupWizardPackage;
24746        }
24747
24748        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24749            if (policy != null) {
24750                mExternalSourcesPolicy = policy;
24751            }
24752        }
24753
24754        @Override
24755        public boolean isPackagePersistent(String packageName) {
24756            synchronized (mPackages) {
24757                PackageParser.Package pkg = mPackages.get(packageName);
24758                return pkg != null
24759                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24760                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24761                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24762                        : false;
24763            }
24764        }
24765
24766        @Override
24767        public List<PackageInfo> getOverlayPackages(int userId) {
24768            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24769            synchronized (mPackages) {
24770                for (PackageParser.Package p : mPackages.values()) {
24771                    if (p.mOverlayTarget != null) {
24772                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24773                        if (pkg != null) {
24774                            overlayPackages.add(pkg);
24775                        }
24776                    }
24777                }
24778            }
24779            return overlayPackages;
24780        }
24781
24782        @Override
24783        public List<String> getTargetPackageNames(int userId) {
24784            List<String> targetPackages = new ArrayList<>();
24785            synchronized (mPackages) {
24786                for (PackageParser.Package p : mPackages.values()) {
24787                    if (p.mOverlayTarget == null) {
24788                        targetPackages.add(p.packageName);
24789                    }
24790                }
24791            }
24792            return targetPackages;
24793        }
24794
24795        @Override
24796        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24797                @Nullable List<String> overlayPackageNames) {
24798            synchronized (mPackages) {
24799                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24800                    Slog.e(TAG, "failed to find package " + targetPackageName);
24801                    return false;
24802                }
24803                ArrayList<String> overlayPaths = null;
24804                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24805                    final int N = overlayPackageNames.size();
24806                    overlayPaths = new ArrayList<>(N);
24807                    for (int i = 0; i < N; i++) {
24808                        final String packageName = overlayPackageNames.get(i);
24809                        final PackageParser.Package pkg = mPackages.get(packageName);
24810                        if (pkg == null) {
24811                            Slog.e(TAG, "failed to find package " + packageName);
24812                            return false;
24813                        }
24814                        overlayPaths.add(pkg.baseCodePath);
24815                    }
24816                }
24817
24818                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24819                ps.setOverlayPaths(overlayPaths, userId);
24820                return true;
24821            }
24822        }
24823
24824        @Override
24825        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24826                int flags, int userId, boolean resolveForStart) {
24827            return resolveIntentInternal(
24828                    intent, resolvedType, flags, userId, resolveForStart);
24829        }
24830
24831        @Override
24832        public ResolveInfo resolveService(Intent intent, String resolvedType,
24833                int flags, int userId, int callingUid) {
24834            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24835        }
24836
24837        @Override
24838        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24839            return PackageManagerService.this.resolveContentProviderInternal(
24840                    name, flags, userId);
24841        }
24842
24843        @Override
24844        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24845            synchronized (mPackages) {
24846                mIsolatedOwners.put(isolatedUid, ownerUid);
24847            }
24848        }
24849
24850        @Override
24851        public void removeIsolatedUid(int isolatedUid) {
24852            synchronized (mPackages) {
24853                mIsolatedOwners.delete(isolatedUid);
24854            }
24855        }
24856
24857        @Override
24858        public int getUidTargetSdkVersion(int uid) {
24859            synchronized (mPackages) {
24860                return getUidTargetSdkVersionLockedLPr(uid);
24861            }
24862        }
24863
24864        @Override
24865        public boolean canAccessInstantApps(int callingUid, int userId) {
24866            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24867        }
24868
24869        @Override
24870        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24871            synchronized (mPackages) {
24872                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24873            }
24874        }
24875
24876        @Override
24877        public void notifyPackageUse(String packageName, int reason) {
24878            synchronized (mPackages) {
24879                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24880            }
24881        }
24882    }
24883
24884    @Override
24885    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24886        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24887        synchronized (mPackages) {
24888            final long identity = Binder.clearCallingIdentity();
24889            try {
24890                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24891                        packageNames, userId);
24892            } finally {
24893                Binder.restoreCallingIdentity(identity);
24894            }
24895        }
24896    }
24897
24898    @Override
24899    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24900        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24901        synchronized (mPackages) {
24902            final long identity = Binder.clearCallingIdentity();
24903            try {
24904                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24905                        packageNames, userId);
24906            } finally {
24907                Binder.restoreCallingIdentity(identity);
24908            }
24909        }
24910    }
24911
24912    private static void enforceSystemOrPhoneCaller(String tag) {
24913        int callingUid = Binder.getCallingUid();
24914        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24915            throw new SecurityException(
24916                    "Cannot call " + tag + " from UID " + callingUid);
24917        }
24918    }
24919
24920    boolean isHistoricalPackageUsageAvailable() {
24921        return mPackageUsage.isHistoricalPackageUsageAvailable();
24922    }
24923
24924    /**
24925     * Return a <b>copy</b> of the collection of packages known to the package manager.
24926     * @return A copy of the values of mPackages.
24927     */
24928    Collection<PackageParser.Package> getPackages() {
24929        synchronized (mPackages) {
24930            return new ArrayList<>(mPackages.values());
24931        }
24932    }
24933
24934    /**
24935     * Logs process start information (including base APK hash) to the security log.
24936     * @hide
24937     */
24938    @Override
24939    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24940            String apkFile, int pid) {
24941        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24942            return;
24943        }
24944        if (!SecurityLog.isLoggingEnabled()) {
24945            return;
24946        }
24947        Bundle data = new Bundle();
24948        data.putLong("startTimestamp", System.currentTimeMillis());
24949        data.putString("processName", processName);
24950        data.putInt("uid", uid);
24951        data.putString("seinfo", seinfo);
24952        data.putString("apkFile", apkFile);
24953        data.putInt("pid", pid);
24954        Message msg = mProcessLoggingHandler.obtainMessage(
24955                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24956        msg.setData(data);
24957        mProcessLoggingHandler.sendMessage(msg);
24958    }
24959
24960    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24961        return mCompilerStats.getPackageStats(pkgName);
24962    }
24963
24964    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24965        return getOrCreateCompilerPackageStats(pkg.packageName);
24966    }
24967
24968    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24969        return mCompilerStats.getOrCreatePackageStats(pkgName);
24970    }
24971
24972    public void deleteCompilerPackageStats(String pkgName) {
24973        mCompilerStats.deletePackageStats(pkgName);
24974    }
24975
24976    @Override
24977    public int getInstallReason(String packageName, int userId) {
24978        final int callingUid = Binder.getCallingUid();
24979        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24980                true /* requireFullPermission */, false /* checkShell */,
24981                "get install reason");
24982        synchronized (mPackages) {
24983            final PackageSetting ps = mSettings.mPackages.get(packageName);
24984            if (filterAppAccessLPr(ps, callingUid, userId)) {
24985                return PackageManager.INSTALL_REASON_UNKNOWN;
24986            }
24987            if (ps != null) {
24988                return ps.getInstallReason(userId);
24989            }
24990        }
24991        return PackageManager.INSTALL_REASON_UNKNOWN;
24992    }
24993
24994    @Override
24995    public boolean canRequestPackageInstalls(String packageName, int userId) {
24996        return canRequestPackageInstallsInternal(packageName, 0, userId,
24997                true /* throwIfPermNotDeclared*/);
24998    }
24999
25000    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25001            boolean throwIfPermNotDeclared) {
25002        int callingUid = Binder.getCallingUid();
25003        int uid = getPackageUid(packageName, 0, userId);
25004        if (callingUid != uid && callingUid != Process.ROOT_UID
25005                && callingUid != Process.SYSTEM_UID) {
25006            throw new SecurityException(
25007                    "Caller uid " + callingUid + " does not own package " + packageName);
25008        }
25009        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25010        if (info == null) {
25011            return false;
25012        }
25013        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25014            return false;
25015        }
25016        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25017        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25018        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25019            if (throwIfPermNotDeclared) {
25020                throw new SecurityException("Need to declare " + appOpPermission
25021                        + " to call this api");
25022            } else {
25023                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25024                return false;
25025            }
25026        }
25027        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25028            return false;
25029        }
25030        if (mExternalSourcesPolicy != null) {
25031            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25032            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25033                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25034            }
25035        }
25036        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25037    }
25038
25039    @Override
25040    public ComponentName getInstantAppResolverSettingsComponent() {
25041        return mInstantAppResolverSettingsComponent;
25042    }
25043
25044    @Override
25045    public ComponentName getInstantAppInstallerComponent() {
25046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25047            return null;
25048        }
25049        return mInstantAppInstallerActivity == null
25050                ? null : mInstantAppInstallerActivity.getComponentName();
25051    }
25052
25053    @Override
25054    public String getInstantAppAndroidId(String packageName, int userId) {
25055        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25056                "getInstantAppAndroidId");
25057        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
25058                true /* requireFullPermission */, false /* checkShell */,
25059                "getInstantAppAndroidId");
25060        // Make sure the target is an Instant App.
25061        if (!isInstantApp(packageName, userId)) {
25062            return null;
25063        }
25064        synchronized (mPackages) {
25065            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25066        }
25067    }
25068
25069    boolean canHaveOatDir(String packageName) {
25070        synchronized (mPackages) {
25071            PackageParser.Package p = mPackages.get(packageName);
25072            if (p == null) {
25073                return false;
25074            }
25075            return p.canHaveOatDir();
25076        }
25077    }
25078
25079    private String getOatDir(PackageParser.Package pkg) {
25080        if (!pkg.canHaveOatDir()) {
25081            return null;
25082        }
25083        File codePath = new File(pkg.codePath);
25084        if (codePath.isDirectory()) {
25085            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25086        }
25087        return null;
25088    }
25089
25090    void deleteOatArtifactsOfPackage(String packageName) {
25091        final String[] instructionSets;
25092        final List<String> codePaths;
25093        final String oatDir;
25094        final PackageParser.Package pkg;
25095        synchronized (mPackages) {
25096            pkg = mPackages.get(packageName);
25097        }
25098        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25099        codePaths = pkg.getAllCodePaths();
25100        oatDir = getOatDir(pkg);
25101
25102        for (String codePath : codePaths) {
25103            for (String isa : instructionSets) {
25104                try {
25105                    mInstaller.deleteOdex(codePath, isa, oatDir);
25106                } catch (InstallerException e) {
25107                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25108                }
25109            }
25110        }
25111    }
25112
25113    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25114        Set<String> unusedPackages = new HashSet<>();
25115        long currentTimeInMillis = System.currentTimeMillis();
25116        synchronized (mPackages) {
25117            for (PackageParser.Package pkg : mPackages.values()) {
25118                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25119                if (ps == null) {
25120                    continue;
25121                }
25122                PackageDexUsage.PackageUseInfo packageUseInfo =
25123                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25124                if (PackageManagerServiceUtils
25125                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25126                                downgradeTimeThresholdMillis, packageUseInfo,
25127                                pkg.getLatestPackageUseTimeInMills(),
25128                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25129                    unusedPackages.add(pkg.packageName);
25130                }
25131            }
25132        }
25133        return unusedPackages;
25134    }
25135}
25136
25137interface PackageSender {
25138    void sendPackageBroadcast(final String action, final String pkg,
25139        final Bundle extras, final int flags, final String targetPkg,
25140        final IIntentReceiver finishedReceiver, final int[] userIds);
25141    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25142        boolean includeStopped, int appId, int... userIds);
25143}
25144